-
Notifications
You must be signed in to change notification settings - Fork 15
/
tally.rs
532 lines (475 loc) · 20 KB
/
tally.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use std::ops::{Add, Range};
use std::time::{Duration, SystemTime};
use chain_addr::{Discrimination, Kind};
use chain_core::property::Fragment as _;
use chain_impl_mockchain::account::SpendingCounter;
use chain_impl_mockchain::block::HeaderId;
use chain_impl_mockchain::certificate::{VotePlan, VotePlanId};
use chain_impl_mockchain::chaineval::ConsensusEvalContext;
use chain_impl_mockchain::fee::LinearFee;
use chain_impl_mockchain::transaction::{
TransactionSignDataHash, TransactionSlice, Witness, WitnessAccountData,
};
use chain_impl_mockchain::{
account,
block::{Block, BlockDate},
certificate,
fragment::Fragment,
ledger::Ledger,
transaction::InputEnum,
vote::{CommitteeId, Payload},
};
use chain_time::{SlotDuration, TimeFrame, Timeline};
use jormungandr_lib::crypto::account::Identifier;
use jormungandr_lib::crypto::hash::Hash;
use jormungandr_lib::interfaces::CommitteeIdDef;
use jormungandr_lib::{
interfaces::{
Address, Block0Configuration, FragmentLogDeserializeError, Initial, PersistentFragmentLog,
SlotDuration as Block0SlotDuration,
},
time::SecondsSinceUnixEpoch,
};
use jormungandr_testing_utils::wallet::Wallet;
use log::{debug, error, trace, warn};
use std::collections::{HashMap, HashSet};
#[allow(clippy::large_enum_variant)]
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
DeserializeError(#[from] jormungandr_lib::interfaces::FragmentLogDeserializeError),
#[error(transparent)]
LedgerError(#[from] chain_impl_mockchain::ledger::Error),
#[error("Couldn't initiate a new wallet")]
WalletError(#[from] jormungandr_testing_utils::wallet::WalletError),
#[error(transparent)]
Block0ConfigurationError(#[from] jormungandr_lib::interfaces::Block0ConfigurationError),
#[error("Block0 do not contain any voteplan")]
MissingVoteplanError,
#[error("Could not verify transaction {id} signature with range {range:?}")]
InvalidTransactionSignature {
id: String,
range: std::ops::Range<u32>,
},
#[error("Invalid ballot, only 1 input (subsequently 1 witness) and no output is accepted")]
InvalidVoteCast,
#[error(
"Fragment with id {id} and spending counter value {spending_counter} was already processed"
)]
DuplicatedFragment { id: String, spending_counter: u32 },
#[error("Tried to vote with a non registered account: {0}")]
NonVotingAccount(String),
}
fn timestamp_to_system_time(ts: SecondsSinceUnixEpoch) -> SystemTime {
SystemTime::UNIX_EPOCH.add(Duration::new(ts.to_secs(), 0))
}
fn fragment_log_timestamp_to_blockdate(
timestamp: SecondsSinceUnixEpoch,
timeframe: &TimeFrame,
ledger: &Ledger,
) -> Option<BlockDate> {
let slot = timestamp_to_system_time(timestamp);
let new_slot = timeframe.slot_at(&slot)?;
let epoch_position = ledger.era().from_slot_to_era(new_slot)?;
Some(BlockDate::from(epoch_position))
}
fn timeframe_from_block0_start_and_slot_duration(
block0_start: SecondsSinceUnixEpoch,
slot_duration: Block0SlotDuration,
) -> TimeFrame {
let timeline = Timeline::new(timestamp_to_system_time(block0_start));
TimeFrame::new(
timeline,
SlotDuration::from_secs(<u8>::from(slot_duration) as u32),
)
}
fn committee_id_to_address(id: CommitteeIdDef) -> Address {
let id = CommitteeId::from(id);
let pk = id.public_key();
chain_addr::Address(Discrimination::Production, Kind::Account(pk)).into()
}
fn voteplans_from_block0(block0: &Block) -> HashMap<VotePlanId, VotePlan> {
block0
.fragments()
.filter_map(|fragment| {
if let Fragment::VotePlan(tx) = fragment {
let voteplan = tx.as_slice().payload().into_payload();
Some((voteplan.to_id(), voteplan))
} else {
None
}
})
.collect()
}
/// check that the transaction input/outputs/witnesses is valid for the ballot
/// * Only 1 input (subsequently 1 witness), no output
pub(super) fn valid_vote_cast(tx: &TransactionSlice<certificate::VoteCast>) -> bool {
if tx.inputs().nb_inputs() != 1
|| tx.witnesses().nb_witnesses() != 1
|| tx.outputs().nb_outputs() != 0
{
return false;
}
true
}
fn verify_original_tx(
spending_counter: SpendingCounter,
block0_hash: &HeaderId,
sign_data_hash: &TransactionSignDataHash,
account: &account::Identifier,
witness: &account::Witness,
range_check: Range<u32>,
) -> (bool, u32) {
let spending_counter: u32 = <u32>::from(spending_counter);
for i in range_check {
for op in &[u32::checked_add, u32::checked_sub] {
if let Some(new_spending_counter) = op(spending_counter, i) {
let tidsc = WitnessAccountData::new(
block0_hash,
sign_data_hash,
SpendingCounter::from(new_spending_counter),
);
if witness.verify(account.as_ref(), &tidsc) == chain_crypto::Verification::Success {
trace!(
"expected: {} found: {}",
spending_counter,
new_spending_counter
);
return (true, new_spending_counter);
}
}
}
}
(false, 0)
}
fn increment_ledger_time_up_to(ledger: Ledger, blockdate: BlockDate) -> Ledger {
ledger
.begin_block(
ledger.get_ledger_parameters(),
ledger.chain_length().increase(),
blockdate,
)
.unwrap()
.finish(&ConsensusEvalContext::Bft)
}
pub fn recover_ledger_from_logs(
block0: &Block,
fragment_logs: impl Iterator<Item = Result<PersistentFragmentLog, FragmentLogDeserializeError>>,
) -> Result<(Ledger, Vec<Fragment>), Error> {
let block0_configuration = Block0Configuration::from_block(block0).unwrap();
let mut failed_fragments = Vec::new();
let (mut fragment_replayer, new_block0) = FragmentReplayer::from_block0(block0)?;
// we use block0 header id instead of the new one, to keep validation on old tx that uses the original block0 id.
// This is used so we can run the VoteTally certificates with the original (issued) committee members ones.
let mut ledger =
Ledger::new(block0.header.id(), new_block0.fragments()).map_err(Error::LedgerError)?;
let block0_start = block0_configuration.blockchain_configuration.block0_date;
let slot_duration = block0_configuration.blockchain_configuration.slot_duration;
// we assume that voteplans use the same vote start/end BlockDates as well as committee and tally ones
// hence we only take data from one of them
let active_voteplans = ledger.active_vote_plans();
let voteplan = active_voteplans.last().ok_or(Error::MissingVoteplanError)?;
let vote_start = voteplan.vote_start;
let vote_end = voteplan.vote_end;
let timeframe = timeframe_from_block0_start_and_slot_duration(block0_start, slot_duration);
// do not update ledger epoch if we are already in expected Epoch(0)
if vote_start.epoch != 0 {
ledger = ledger
.begin_block(
ledger.get_ledger_parameters(),
ledger.chain_length().increase(),
vote_start,
)
.unwrap()
.finish(&ConsensusEvalContext::Bft);
}
// flag to check if we already incremented the time for tally (advance to vote_end)
let mut inc_tally = true;
for fragment_log in fragment_logs {
match fragment_log {
Ok(PersistentFragmentLog { fragment, time }) => {
let block_date = fragment_log_timestamp_to_blockdate(time, &timeframe, &ledger)
.expect("BlockDates should always be valid for logs timestamps");
debug!("Fragment processed {}", fragment.hash());
let new_fragment = match &fragment {
fragment @ Fragment::VoteCast(_) => {
if vote_start > block_date || vote_end <= block_date {
warn!(
"Fragment {} skipped because it was out of voting time ({}-{}-{})",
fragment.id(),
vote_start,
block_date,
vote_end,
);
None
} else {
fragment_replayer
.replay(fragment.clone())
.map_err(|e| {
failed_fragments.push(fragment.clone());
warn!(
"Fragment {} couldn't be processed:\n\t {:?}",
fragment.id(),
e
);
})
.ok()
}
}
new_fragment @ Fragment::VoteTally(_) => {
if inc_tally {
ledger = increment_ledger_time_up_to(ledger, vote_end);
inc_tally = false;
}
Some(new_fragment.clone())
}
_ => None,
};
if let Some(new_fragment) = new_fragment {
ledger = ledger.apply_fragment(&ledger.get_ledger_parameters(), &new_fragment, block_date)
.expect("Should be impossible to fail, since we should be using proper spending counters and signatures");
}
}
Err(e) => {
error!("Error deserializing PersistentFragmentLog: {:?}", e);
}
}
}
Ok((ledger, failed_fragments))
}
struct FragmentReplayer {
wallets: HashMap<Address, Wallet>,
spending_counters: HashMap<Address, Vec<u32>>,
processed_fragments: HashSet<(String, u32)>,
voteplans: HashMap<VotePlanId, VotePlan>,
old_block0_hash: Hash,
fees: LinearFee,
range_check: Range<u32>,
}
impl FragmentReplayer {
// build a new block0 with mirror accounts and same configuration as original one
fn from_block0(block0: &Block) -> Result<(Self, Block), Error> {
let mut config =
Block0Configuration::from_block(block0).map_err(Error::Block0ConfigurationError)?;
let voteplans = voteplans_from_block0(&block0);
// use double of proposals range as possible spending counters to check
let spending_counter_max_check: u32 = voteplans
.values()
.flat_map(|voteplan| voteplan.proposals().iter())
.count() as u32
* 2;
let mut wallets = HashMap::new();
let mut rng = rand::thread_rng();
let committee_members = config
.blockchain_configuration
.committees
.iter()
.cloned()
.map(committee_id_to_address)
.collect::<HashSet<_>>();
for initial in &mut config.initial {
if let Initial::Fund(ref mut utxos) = initial {
let mut new_committee_accounts = Vec::new();
for utxo in utxos.iter_mut() {
let wallet = Wallet::new_account_with_discrimination(
&mut rng,
chain_addr::Discrimination::Production,
);
let new_initial_utxo = wallet.to_initial_fund(utxo.value.into());
wallets.insert(utxo.address.clone(), wallet);
if committee_members.contains(&utxo.address) {
trace!("Committee account found {}", &utxo.address);
// push new mirror address
new_committee_accounts.push(new_initial_utxo);
} else {
*utxo = new_initial_utxo;
}
}
utxos.append(&mut new_committee_accounts);
}
}
let fees = config.blockchain_configuration.linear_fees;
Ok((
Self {
wallets,
spending_counters: HashMap::new(),
processed_fragments: HashSet::new(),
voteplans,
old_block0_hash: block0.header.id().into(),
fees,
range_check: (0..spending_counter_max_check),
},
config.to_block(),
))
}
// rebuild a fragment to be used in the new ledger configuration with the account mirror account.
fn replay(&mut self, fragment: Fragment) -> Result<Fragment, Error> {
if let Fragment::VoteCast(ref transaction) = fragment {
let transaction_slice = transaction.as_slice();
let vote_cast = transaction_slice.payload().into_payload();
let account = transaction
.as_slice()
.inputs()
.iter()
.next()
.unwrap()
.to_enum();
let identifier = if let InputEnum::AccountInput(account, _) = account {
Identifier::from(account.to_single_account().unwrap())
} else {
panic!("cannot handle utxo inputs");
};
let address = identifier.to_address(chain_addr::Discrimination::Production);
let choice = if let Payload::Public { choice } = vote_cast.payload() {
choice
} else {
panic!("cannot handle private votes");
};
let sign_data_hash = transaction_slice.transaction_sign_data_hash();
let spending_counter = if let Wallet::Account(account) = self
.wallets
.get(&address.clone().into())
.ok_or_else(|| Error::NonVotingAccount(identifier.to_string()))?
{
account.internal_counter()
} else {
panic!("New accounts spending counters should always be valid.")
};
// check if fragment was processed already
let processed_key = (fragment.id().to_string(), spending_counter.into());
if self.processed_fragments.contains(&processed_key) {
return Err(Error::DuplicatedFragment {
id: fragment.id().to_string(),
spending_counter: spending_counter.into(),
});
}
if transaction_slice.nb_witnesses() != 1 {
unimplemented!("Multi-signature is not supported");
}
let witness = if let Witness::Account(witness) =
transaction_slice.witnesses().iter().next().unwrap()
{
witness
} else {
panic!("utxo witnesses not supported");
};
let is_valid_vote_cast = valid_vote_cast(&transaction_slice);
if !is_valid_vote_cast {
return Err(Error::InvalidVoteCast);
}
let (is_valid_tx, sc) = verify_original_tx(
spending_counter,
&self.old_block0_hash.into_hash(),
&sign_data_hash,
&identifier.to_inner(),
&witness,
self.range_check.clone(),
);
if !is_valid_tx {
return Err(Error::InvalidTransactionSignature {
id: fragment.clone().hash().to_string(),
range: self.range_check.clone(),
});
}
self.spending_counters
.entry(address.clone().into())
.or_insert_with(Vec::new)
.push(sc);
let wallet = self.wallets.get_mut(&address.into()).unwrap();
let vote_plan = self
.voteplans
.get(vote_cast.vote_plan())
.ok_or(Error::MissingVoteplanError)?;
let proposals_idx = vote_cast.proposal_index();
// we still use the old block0 hash because the new ledger will still use the old one for
// verifications. This makes possible the usage of old VoteTally transactions without the need
// to be replayed.
debug!(
"replaying vote from {}, vote plan: {}, proposal idx: {}, choice: {:?}",
identifier,
&vote_plan.to_id(),
proposals_idx,
&choice
);
let res = wallet
.issue_vote_cast_cert(
&self.old_block0_hash,
&self.fees,
&vote_plan,
proposals_idx,
&choice,
)
.unwrap();
wallet.confirm_transaction();
// add to processed list so it is not processed if duplicated
self.processed_fragments.insert(processed_key);
Ok(res)
} else {
unimplemented!();
}
}
}
#[cfg(test)]
mod test {
use super::{increment_ledger_time_up_to, recover_ledger_from_logs, voteplans_from_block0};
use chain_impl_mockchain::block::Block;
use chain_impl_mockchain::certificate::VoteTallyPayload;
use chain_impl_mockchain::vote::Weight;
use chain_ser::deser::Deserialize;
use jormungandr_lib::interfaces::{
load_persistent_fragments_logs_from_folder_path, Block0Configuration,
};
use jormungandr_testing_utils::wallet::Wallet;
use std::io::BufReader;
use std::path::PathBuf;
fn read_block0(path: PathBuf) -> std::io::Result<Block> {
let reader = std::fs::File::open(path)?;
Ok(Block::deserialize(BufReader::new(reader)).unwrap())
}
#[test]
fn test_vote_flow() -> std::io::Result<()> {
println!("{}", std::env::current_dir().unwrap().to_string_lossy());
let path = std::fs::canonicalize(r"../testing/logs").unwrap();
println!(
"{}",
std::fs::canonicalize(path.clone())
.unwrap()
.to_string_lossy()
);
let fragments = load_persistent_fragments_logs_from_folder_path(&path)?;
let block0_path: PathBuf = std::fs::canonicalize(r"../testing/block0.bin").unwrap();
let block0 = read_block0(block0_path)?;
let block0_configuration = Block0Configuration::from_block(&block0).unwrap();
let (ledger, failed) = recover_ledger_from_logs(&block0, fragments).unwrap();
let mut committee = Wallet::from_existing_account("ed25519e_sk1dpqkhtzyeaqvclvjf3hgdkw2rh5q06a2dqrp9qks32g96ta6k9alvhm7a0zp5j4gly90dmjj2w4ky3u86mpwxyctrc2k7s5qfq9dd8sefgey5", 0.into());
let voteplans = voteplans_from_block0(&block0);
let mut ledger =
increment_ledger_time_up_to(ledger, voteplans.values().last().unwrap().vote_end());
for (_, voteplan) in voteplans {
let tally_cert = committee
.issue_vote_tally_cert(
&block0.header.id().into(),
&block0_configuration.blockchain_configuration.linear_fees,
&voteplan,
VoteTallyPayload::Public,
)
.unwrap();
ledger = ledger.apply_fragment(&ledger.get_ledger_parameters(), &tally_cert, ledger.date())
.expect("Should be impossible to fail, since we should be using proper spending counters and signatures");
committee.confirm_transaction();
}
println!("Failed: {}", failed.len());
assert_eq!(failed.len(), 0);
for voteplan in ledger.active_vote_plans() {
println!("Voteplan: {}", voteplan.id);
for proposal in voteplan.proposals {
let result = proposal.tally.unwrap().result().cloned().unwrap();
if result.results().iter().any(|w| w != &Weight::from(0)) {
println!("\tProposal: {}", proposal.proposal_id);
println!("\t\t{:?}", result.results());
}
}
}
Ok(())
}
}