-
Notifications
You must be signed in to change notification settings - Fork 222
/
vote_stage.rs
329 lines (279 loc) · 10.1 KB
/
vote_stage.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
use transaction_processor::TransactionProcessor;
use bincode::serialize;
use fin_plan_transaction::FinPlanTransaction;
use counter::Counter;
use blockthread::BlockThread;
use hash::Hash;
use influx_db_client as influxdb;
use log::Level;
use metrics;
use packet::SharedBlob;
use result::Result;
use signature::Keypair;
use xpz_program_interface::pubkey::Pubkey;
use std::result;
use std::sync::atomic::AtomicUsize;
use std::sync::{Arc, RwLock};
use streamer::BlobSender;
use timing;
use transaction::Transaction;
pub const VOTE_TIMEOUT_MS: u64 = 1000;
#[derive(Debug, PartialEq, Eq)]
enum VoteError {
NoValidLastIdsToVoteOn,
}
pub fn create_new_signed_vote_blob(
last_id: &Hash,
keypair: &Keypair,
blockthread: &Arc<RwLock<BlockThread>>,
) -> Result<SharedBlob> {
let shared_blob = SharedBlob::default();
let (vote, addr) = {
let mut wblockthread = blockthread.write().unwrap();
debug!("voting on {:?}", &last_id.as_ref()[..8]);
wblockthread.new_vote(*last_id)
}?;
let tx = Transaction::fin_plan_new_vote(&keypair, vote, *last_id, 0);
{
let mut blob = shared_blob.write().unwrap();
let bytes = serialize(&tx)?;
let len = bytes.len();
blob.data[..len].copy_from_slice(&bytes);
blob.meta.set_addr(&addr);
blob.meta.size = len;
}
Ok(shared_blob)
}
fn get_last_id_to_vote_on(
id: &Pubkey,
ids: &[Hash],
transaction_processor: &Arc<TransactionProcessor>,
now: u64,
last_vote: &mut u64,
last_valid_validator_timestamp: &mut u64,
) -> result::Result<(Hash, u64), VoteError> {
let mut valid_ids = transaction_processor.count_valid_ids(&ids);
let super_majority_index = (2 * ids.len()) / 3;
debug!(
"{}: valid_ids {}/{} {}",
id,
valid_ids.len(),
ids.len(),
super_majority_index,
);
metrics::submit(
influxdb::Point::new("vote_stage-peer_count")
.add_field("total_peers", influxdb::Value::Integer(ids.len() as i64))
.add_field(
"valid_peers",
influxdb::Value::Integer(valid_ids.len() as i64),
).to_owned(),
);
if valid_ids.len() > super_majority_index {
*last_vote = now;
valid_ids.sort_by(|a, b| a.1.cmp(&b.1));
let last_id = ids[valid_ids[super_majority_index].0];
return Ok((last_id, valid_ids[super_majority_index].1));
}
if *last_valid_validator_timestamp != 0 {
metrics::submit(
influxdb::Point::new(&"leader-finality")
.add_field(
"duration_ms",
influxdb::Value::Integer((now - *last_valid_validator_timestamp) as i64),
).to_owned(),
);
}
Err(VoteError::NoValidLastIdsToVoteOn)
}
pub fn send_leader_vote(
id: &Pubkey,
keypair: &Keypair,
transaction_processor: &Arc<TransactionProcessor>,
blockthread: &Arc<RwLock<BlockThread>>,
vote_blob_sender: &BlobSender,
last_vote: &mut u64,
last_valid_validator_timestamp: &mut u64,
) -> Result<()> {
let now = timing::timestamp();
if now - *last_vote > VOTE_TIMEOUT_MS {
let ids: Vec<_> = blockthread.read().unwrap().valid_last_ids();
if let Ok((last_id, super_majority_timestamp)) = get_last_id_to_vote_on(
id,
&ids,
transaction_processor,
now,
last_vote,
last_valid_validator_timestamp,
) {
if let Ok(shared_blob) = create_new_signed_vote_blob(&last_id, keypair, blockthread) {
vote_blob_sender.send(vec![shared_blob])?;
let finality_ms = now - super_majority_timestamp;
*last_valid_validator_timestamp = super_majority_timestamp;
debug!("{} leader_sent_vote finality: {} ms", id, finality_ms);
inc_new_counter_info!("vote_stage-leader_sent_vote", 1);
transaction_processor.set_finality((now - *last_valid_validator_timestamp) as usize);
metrics::submit(
influxdb::Point::new(&"leader-finality")
.add_field("duration_ms", influxdb::Value::Integer(finality_ms as i64))
.to_owned(),
);
}
}
}
Ok(())
}
pub fn send_validator_vote(
transaction_processor: &Arc<TransactionProcessor>,
keypair: &Arc<Keypair>,
blockthread: &Arc<RwLock<BlockThread>>,
vote_blob_sender: &BlobSender,
) -> Result<()> {
let last_id = transaction_processor.last_id();
if let Ok(shared_blob) = create_new_signed_vote_blob(&last_id, keypair, blockthread) {
inc_new_counter_info!("replicate-vote_sent", 1);
vote_blob_sender.send(vec![shared_blob])?;
}
Ok(())
}
#[cfg(test)]
pub mod tests {
use super::*;
use transaction_processor::TransactionProcessor;
use bincode::deserialize;
use fin_plan_instruction::Vote;
use blockthread::{BlockThread, NodeInfo};
use entry::next_entry;
use hash::{hash, Hash};
use logger;
use mint::Mint;
use std::sync::mpsc::channel;
use std::sync::{Arc, RwLock};
use std::thread::sleep;
use std::time::Duration;
use builtin_tansaction::SystemTransaction;
use transaction::Transaction;
#[test]
fn test_send_leader_vote() {
logger::setup();
let mint = Mint::new(1000);
let transaction_processor = Arc::new(TransactionProcessor::new(&mint));
let hash0 = Hash::default();
let entry = next_entry(&hash0, 1, vec![]);
transaction_processor.register_entry_id(&entry.id);
let leader_data = NodeInfo::new_with_socketaddr(&"127.0.0.1:1234".parse().unwrap());
let leader_pubkey = leader_data.id.clone();
let mut leader_blockthread = BlockThread::new(leader_data).unwrap();
let give_leader_tokens_tx =
Transaction::system_new(&mint.keypair(), leader_pubkey.clone(), 100, entry.id);
transaction_processor.process_transaction(&give_leader_tokens_tx).unwrap();
leader_blockthread.set_leader(leader_pubkey);
for i in 0..10 {
let mut validator =
NodeInfo::new_with_socketaddr(&format!("127.0.0.1:234{}", i).parse().unwrap());
let vote = Vote {
version: validator.version + 1,
contact_info_version: 1,
};
if i < 7 {
validator.ledger_state.last_id = entry.id;
}
leader_blockthread.insert(&validator);
trace!("validator id: {:?}", validator.id);
leader_blockthread.insert_vote(&validator.id, &vote, entry.id);
}
let leader = Arc::new(RwLock::new(leader_blockthread));
let (vote_blob_sender, vote_blob_receiver) = channel();
let mut last_vote: u64 = timing::timestamp() - VOTE_TIMEOUT_MS - 1;
let mut last_valid_validator_timestamp = 0;
let res = send_leader_vote(
&mint.pubkey(),
&mint.keypair(),
&transaction_processor,
&leader,
&vote_blob_sender,
&mut last_vote,
&mut last_valid_validator_timestamp,
);
trace!("vote result: {:?}", res);
assert!(res.is_ok());
let vote_blob = vote_blob_receiver.recv_timeout(Duration::from_millis(500));
trace!("vote_blob: {:?}", vote_blob);
assert!(vote_blob.is_err());
for i in 0..2 {
let mut validator =
NodeInfo::new_with_socketaddr(&format!("127.0.0.1:234{}", i).parse().unwrap());
let vote = Vote {
version: validator.version + 1,
contact_info_version: 1,
};
validator.ledger_state.last_id = entry.id;
leader.write().unwrap().insert(&validator);
trace!("validator id: {:?}", validator.id);
leader
.write()
.unwrap()
.insert_vote(&validator.id, &vote, entry.id);
}
last_vote = timing::timestamp() - VOTE_TIMEOUT_MS - 1;
let res = send_leader_vote(
&Pubkey::default(),
&mint.keypair(),
&transaction_processor,
&leader,
&vote_blob_sender,
&mut last_vote,
&mut last_valid_validator_timestamp,
);
trace!("vote result: {:?}", res);
assert!(res.is_ok());
let vote_blob = vote_blob_receiver.recv_timeout(Duration::from_millis(500));
trace!("vote_blob: {:?}", vote_blob);
assert!(vote_blob.is_ok());
let blob = &vote_blob.unwrap()[0];
let tx = deserialize(&(blob.read().unwrap().data)).unwrap();
assert!(transaction_processor.process_transaction(&tx).is_ok());
}
#[test]
fn test_get_last_id_to_vote_on() {
logger::setup();
let mint = Mint::new(1234);
let transaction_processor = Arc::new(TransactionProcessor::new(&mint));
let mut last_vote = 0;
let mut last_valid_validator_timestamp = 0;
let ids: Vec<_> = (0..10)
.map(|i| {
let last_id = hash(&serialize(&i).unwrap());
if i < 6 {
transaction_processor.register_entry_id(&last_id);
}
sleep(Duration::from_millis(1));
last_id
}).collect();
assert!(
get_last_id_to_vote_on(
&Pubkey::default(),
&ids,
&transaction_processor,
0,
&mut last_vote,
&mut last_valid_validator_timestamp
).is_err()
);
transaction_processor.register_entry_id(&ids[6]);
let res = get_last_id_to_vote_on(
&Pubkey::default(),
&ids,
&transaction_processor,
0,
&mut last_vote,
&mut last_valid_validator_timestamp,
);
if let Ok((hash, timestamp)) = res {
assert!(hash == ids[6]);
assert!(timestamp != 0);
} else {
assert!(false, "get_last_id returned error!: {:?}", res);
}
}
}