-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
finalize.rs
2814 lines (2431 loc) · 131 KB
/
finalize.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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the snarkVM library.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::*;
use ledger_committee::{MAX_DELEGATORS, MIN_DELEGATOR_STAKE, MIN_VALIDATOR_STAKE};
use rand::{rngs::StdRng, SeedableRng};
impl<N: Network, C: ConsensusStorage<N>> VM<N, C> {
/// Speculates on the given list of transactions in the VM.
/// This function aborts all transactions that are not are well-formed or unique.
///
///
/// Returns the confirmed transactions, aborted transaction IDs,
/// and finalize operations from pre-ratify and post-ratify.
///
/// Note: This method is used to create a new block (including the genesis block).
/// - If `coinbase_reward = None`, then the `ratifications` will not be modified.
/// - If `coinbase_reward = Some(coinbase_reward)`, then the method will append a
/// `Ratify::BlockReward(block_reward)` and `Ratify::PuzzleReward(puzzle_reward)`
/// to the front of the `ratifications` list.
#[inline]
pub fn speculate<'a, R: Rng + CryptoRng>(
&self,
state: FinalizeGlobalState,
coinbase_reward: Option<u64>,
candidate_ratifications: Vec<Ratify<N>>,
candidate_solutions: &Solutions<N>,
candidate_transactions: impl ExactSizeIterator<Item = &'a Transaction<N>>,
rng: &mut R,
) -> Result<(Ratifications<N>, Transactions<N>, Vec<N::TransactionID>, Vec<FinalizeOperation<N>>)> {
let timer = timer!("VM::speculate");
// Collect the candidate transactions into a vector.
let candidate_transactions: Vec<_> = candidate_transactions.collect::<Vec<_>>();
let candidate_transaction_ids: Vec<_> = candidate_transactions.iter().map(|tx| tx.id()).collect();
// If the transactions are not part of the genesis block, ensure each transaction is well-formed and unique. Abort any transactions that are not.
let (verified_transactions, verification_aborted_transactions) =
match self.block_store().find_block_height_from_state_root(self.block_store().current_state_root())? {
// If the current state root does not exist in the block store, then the genesis block has not been introduced yet.
None => (candidate_transactions, vec![]),
// Verify transactions for all non-genesis cases.
_ => {
let rngs =
(0..candidate_transactions.len()).map(|_| StdRng::from_seed(rng.gen())).collect::<Vec<_>>();
// Verify the transactions and collect the error message if there is one.
cfg_into_iter!(candidate_transactions).zip(rngs).partition_map(|(transaction, mut rng)| {
// Abort the transaction if it is a fee transaction.
if transaction.is_fee() {
return Either::Right((
transaction,
"Fee transactions are not allowed in speculate".to_string(),
));
}
// Verify the transaction.
match self.check_transaction(transaction, None, &mut rng) {
Ok(_) => Either::Left(transaction),
Err(e) => Either::Right((transaction, e.to_string())),
}
})
}
};
// Performs a **dry-run** over the list of ratifications, solutions, and transactions.
let (ratifications, confirmed_transactions, speculation_aborted_transactions, ratified_finalize_operations) =
self.atomic_speculate(
state,
coinbase_reward,
candidate_ratifications,
candidate_solutions,
verified_transactions.into_iter(),
)?;
// Get the aborted transaction ids.
let verification_aborted_transaction_ids = verification_aborted_transactions.iter().map(|(tx, e)| (tx.id(), e));
let speculation_aborted_transaction_ids = speculation_aborted_transactions.iter().map(|(tx, e)| (tx.id(), e));
let unordered_aborted_transaction_ids: IndexMap<N::TransactionID, &String> =
verification_aborted_transaction_ids.chain(speculation_aborted_transaction_ids).collect();
// Filter and order the aborted transaction ids according to candidate_transactions
let aborted_transaction_ids: Vec<_> = candidate_transaction_ids
.into_iter()
.filter_map(|tx_id| {
unordered_aborted_transaction_ids.get(&tx_id).map(|error| {
warn!("Speculation safely aborted a transaction - {error} ({tx_id})");
tx_id
})
})
.collect();
finish!(timer, "Finished dry-run of the transactions");
// Return the ratifications, confirmed transactions, aborted transaction IDs, and ratified finalize operations.
Ok((
ratifications,
confirmed_transactions.into_iter().collect(),
aborted_transaction_ids,
ratified_finalize_operations,
))
}
/// Checks the speculation on the given transactions in the VM.
/// This function also ensure that the given transactions are well-formed and unique.
///
/// Returns the finalize operations from pre-ratify and post-ratify.
#[inline]
pub fn check_speculate<R: Rng + CryptoRng>(
&self,
state: FinalizeGlobalState,
ratifications: &Ratifications<N>,
solutions: &Solutions<N>,
transactions: &Transactions<N>,
rng: &mut R,
) -> Result<Vec<FinalizeOperation<N>>> {
let timer = timer!("VM::check_speculate");
// Ensure each transaction is well-formed and unique.
// NOTE: We perform the transaction checks here prior to `atomic_speculate` because we must
// ensure that the `Fee` transactions are valid. We can't unify the transaction checks in `atomic_speculate`
// because we run speculation on the unconfirmed variant of the transactions.
let rngs = (0..transactions.len()).map(|_| StdRng::from_seed(rng.gen())).collect::<Vec<_>>();
cfg_iter!(transactions).zip(rngs).try_for_each(|(transaction, mut rng)| {
self.check_transaction(transaction, transaction.to_rejected_id()?, &mut rng)
.map_err(|e| anyhow!("Invalid transaction found in the transactions list: {e}"))
})?;
// Reconstruct the candidate ratifications to verify the speculation.
let candidate_ratifications = ratifications.iter().cloned().collect::<Vec<_>>();
// Reconstruct the unconfirmed transactions to verify the speculation.
let candidate_transactions =
transactions.iter().map(|confirmed| confirmed.to_unconfirmed_transaction()).collect::<Result<Vec<_>>>()?;
// Performs a **dry-run** over the list of ratifications, solutions, and transactions.
let (speculate_ratifications, confirmed_transactions, aborted_transactions, ratified_finalize_operations) =
self.atomic_speculate(state, None, candidate_ratifications, solutions, candidate_transactions.iter())?;
// Ensure the ratifications after speculation match.
if ratifications != &speculate_ratifications {
bail!("The ratifications after speculation do not match the ratifications in the block");
}
// Ensure the transactions after speculation match.
if transactions != &confirmed_transactions.into_iter().collect() {
bail!("The transactions after speculation do not match the transactions in the block");
}
// Ensure there are no aborted transaction IDs from this speculation.
// Note: There should be no aborted transactions, because we are checking a block,
// where any aborted transactions should be in the aborted transaction ID list, not in transactions.
ensure!(aborted_transactions.is_empty(), "Aborted transactions found in the block (from speculation)");
finish!(timer, "Finished dry-run of the transactions");
// Return the ratified finalize operations.
Ok(ratified_finalize_operations)
}
/// Finalizes the given transactions into the VM.
///
/// Returns the finalize operations from pre-ratify and post-ratify.
#[inline]
pub fn finalize(
&self,
state: FinalizeGlobalState,
ratifications: &Ratifications<N>,
solutions: &Solutions<N>,
transactions: &Transactions<N>,
) -> Result<Vec<FinalizeOperation<N>>> {
let timer = timer!("VM::finalize");
// Performs a **real-run** of finalize over the list of ratifications, solutions, and transactions.
let ratified_finalize_operations = self.atomic_finalize(state, ratifications, solutions, transactions)?;
finish!(timer, "Finished real-run of finalize");
Ok(ratified_finalize_operations)
}
}
impl<N: Network, C: ConsensusStorage<N>> VM<N, C> {
/// The maximum number of confirmed transactions allowed in a block.
#[cfg(not(any(test, feature = "test")))]
pub const MAXIMUM_CONFIRMED_TRANSACTIONS: usize = Transactions::<N>::MAX_TRANSACTIONS;
/// The maximum number of confirmed transactions allowed in a block.
/// This is set to a deliberately low value (8) for testing purposes only.
#[cfg(any(test, feature = "test"))]
pub const MAXIMUM_CONFIRMED_TRANSACTIONS: usize = 8;
/// Performs atomic speculation over a list of transactions.
///
/// Returns the ratifications, confirmed transactions, aborted transactions,
/// and finalize operations from pre-ratify and post-ratify.
///
/// Note: This method is used by `VM::speculate` and `VM::check_speculate`.
/// - If `coinbase_reward = None`, then the `ratifications` will not be modified.
/// - If `coinbase_reward = Some(coinbase_reward)`, then the method will append a
/// `Ratify::BlockReward(block_reward)` and `Ratify::PuzzleReward(puzzle_reward)`
/// to the front of the `ratifications` list.
fn atomic_speculate<'a>(
&self,
state: FinalizeGlobalState,
coinbase_reward: Option<u64>,
ratifications: Vec<Ratify<N>>,
solutions: &Solutions<N>,
transactions: impl ExactSizeIterator<Item = &'a Transaction<N>>,
) -> Result<(
Ratifications<N>,
Vec<ConfirmedTransaction<N>>,
Vec<(Transaction<N>, String)>,
Vec<FinalizeOperation<N>>,
)> {
// Acquire the atomic lock, which is needed to ensure this function is not called concurrently
// with other `atomic_finalize!` macro calls, which will cause a `bail!` to be triggered erroneously.
// Note: This lock must be held for the entire scope of the call to `atomic_finalize!`.
let _atomic_lock = self.atomic_lock.lock();
let timer = timer!("VM::atomic_speculate");
// Retrieve the number of solutions.
let num_solutions = solutions.len();
// Retrieve the number of transactions.
let num_transactions = transactions.len();
// Perform the finalize operation on the preset finalize mode.
atomic_finalize!(self.finalize_store(), FinalizeMode::DryRun, {
// Ensure the number of solutions does not exceed the maximum.
if num_solutions > Solutions::<N>::MAX_ABORTED_SOLUTIONS {
// Note: This will abort the entire atomic batch.
return Err(format!(
"Too many solutions in the block - {num_solutions} (max: {})",
Solutions::<N>::MAX_ABORTED_SOLUTIONS
));
}
// Ensure the number of transactions does not exceed the maximum.
if num_transactions > Transactions::<N>::MAX_ABORTED_TRANSACTIONS {
// Note: This will abort the entire atomic batch.
return Err(format!(
"Too many transactions in the block - {num_transactions} (max: {})",
Transactions::<N>::MAX_ABORTED_TRANSACTIONS
));
}
// Initialize an iterator for ratifications before finalize.
let pre_ratifications = ratifications.iter().filter(|r| match r {
Ratify::Genesis(_, _, _) => true,
Ratify::BlockReward(..) | Ratify::PuzzleReward(..) => false,
});
// Initialize an iterator for ratifications after finalize.
let post_ratifications = ratifications.iter().filter(|r| match r {
Ratify::Genesis(_, _, _) => false,
Ratify::BlockReward(..) | Ratify::PuzzleReward(..) => true,
});
// Initialize a list of finalize operations.
let mut ratified_finalize_operations = Vec::new();
// Retrieve the finalize store.
let store = self.finalize_store();
/* Perform the ratifications before finalize. */
match Self::atomic_pre_ratify(store, state, pre_ratifications) {
// Store the finalize operations from the post-ratify.
Ok(operations) => ratified_finalize_operations.extend(operations),
// Note: This will abort the entire atomic batch.
Err(e) => return Err(format!("Failed to pre-ratify - {e}")),
}
/* Perform the atomic finalize over the transactions. */
// Acquire the write lock on the process.
// Note: Due to the highly-sensitive nature of processing all `finalize` calls,
// we choose to acquire the write lock for the entire duration of this atomic batch.
let process = self.process.write();
// Initialize a list of the confirmed transactions.
let mut confirmed = Vec::with_capacity(num_transactions);
// Initialize a list of the aborted transactions.
let mut aborted = Vec::new();
// Initialize a list of the successful deployments.
let mut deployments = IndexSet::new();
// Initialize a counter for the confirmed transaction index.
let mut counter = 0u32;
// Initialize a list of created transition IDs.
let mut transition_ids: IndexSet<N::TransitionID> = IndexSet::new();
// Initialize a list of spent input IDs.
let mut input_ids: IndexSet<Field<N>> = IndexSet::new();
// Initialize a list of created output IDs.
let mut output_ids: IndexSet<Field<N>> = IndexSet::new();
// Initialize the list of created transition public keys.
let mut tpks: IndexSet<Group<N>> = IndexSet::new();
// Finalize the transactions.
'outer: for transaction in transactions {
// Ensure the number of confirmed transactions does not exceed the maximum.
// Upon reaching the maximum number of confirmed transactions, all remaining transactions are aborted.
if confirmed.len() >= Self::MAXIMUM_CONFIRMED_TRANSACTIONS {
// Store the aborted transaction.
aborted.push((transaction.clone(), "Exceeds block transaction limit".to_string()));
// Continue to the next transaction.
continue 'outer;
}
// Ensure that the transaction is not producing a duplicate transition.
for transition_id in transaction.transition_ids() {
// If the transition ID is already produced in this block or previous blocks, abort the transaction.
if transition_ids.contains(transition_id)
|| self.transition_store().contains_transition_id(transition_id).unwrap_or(true)
{
// Store the aborted transaction.
aborted.push((transaction.clone(), format!("Duplicate transition {transition_id}")));
// Continue to the next transaction.
continue 'outer;
}
}
// Ensure that the transaction is not double-spending an input.
for input_id in transaction.input_ids() {
// If the input ID is already spent in this block or previous blocks, abort the transaction.
if input_ids.contains(input_id)
|| self.transition_store().contains_input_id(input_id).unwrap_or(true)
{
// Store the aborted transaction.
aborted.push((transaction.clone(), format!("Double-spending input {input_id}")));
// Continue to the next transaction.
continue 'outer;
}
}
// Ensure that the transaction is not producing a duplicate output.
for output_id in transaction.output_ids() {
// If the output ID is already produced in this block or previous blocks, abort the transaction.
if output_ids.contains(output_id)
|| self.transition_store().contains_output_id(output_id).unwrap_or(true)
{
// Store the aborted transaction.
aborted.push((transaction.clone(), format!("Duplicate output {output_id}")));
// Continue to the next transaction.
continue 'outer;
}
}
// // Ensure that the transaction is not producing a duplicate transition public key.
// // Note that the tpk and tcm are corresponding, so a uniqueness check for just the tpk is sufficient.
for tpk in transaction.transition_public_keys() {
// If the transition public key is already produced in this block or previous blocks, abort the transaction.
if tpks.contains(tpk) || self.transition_store().contains_tpk(tpk).unwrap_or(true) {
// Store the aborted transaction.
aborted.push((transaction.clone(), format!("Duplicate transition public key {tpk}")));
// Continue to the next transaction.
continue 'outer;
}
}
// Process the transaction in an isolated atomic batch.
// - If the transaction succeeds, the finalize operations are stored.
// - If the transaction fails, the atomic batch is aborted and no finalize operations are stored.
let outcome = match transaction {
// The finalize operation here involves appending the 'stack',
// and adding the program to the finalize tree.
Transaction::Deploy(_, program_owner, deployment, fee) => {
// Define the closure for processing a rejected deployment.
let process_rejected_deployment =
|fee: &Fee<N>,
deployment: Deployment<N>|
-> Result<Result<ConfirmedTransaction<N>, String>> {
process
.finalize_fee(state, store, fee)
.and_then(|finalize| {
Transaction::from_fee(fee.clone()).map(|fee_tx| (fee_tx, finalize))
})
.map(|(fee_tx, finalize)| {
let rejected = Rejected::new_deployment(*program_owner, deployment);
ConfirmedTransaction::rejected_deploy(counter, fee_tx, rejected, finalize)
.map_err(|e| e.to_string())
})
};
// Check if the program has already been deployed in this block.
match deployments.contains(deployment.program_id()) {
// If the program has already been deployed, construct the rejected deploy transaction.
true => match process_rejected_deployment(fee, *deployment.clone()) {
Ok(result) => result,
Err(error) => {
// Note: On failure, skip this transaction, and continue speculation.
#[cfg(debug_assertions)]
eprintln!("Failed to finalize the fee in a rejected deploy - {error}");
// Store the aborted transaction.
aborted.push((transaction.clone(), error.to_string()));
// Continue to the next transaction.
continue 'outer;
}
},
// If the program has not yet been deployed, attempt to deploy it.
false => match process.finalize_deployment(state, store, deployment, fee) {
// Construct the accepted deploy transaction.
Ok((_, finalize)) => {
// Add the program id to the list of deployments.
deployments.insert(*deployment.program_id());
ConfirmedTransaction::accepted_deploy(counter, transaction.clone(), finalize)
.map_err(|e| e.to_string())
}
// Construct the rejected deploy transaction.
Err(_error) => match process_rejected_deployment(fee, *deployment.clone()) {
Ok(result) => result,
Err(error) => {
// Note: On failure, skip this transaction, and continue speculation.
#[cfg(debug_assertions)]
eprintln!("Failed to finalize the fee in a rejected deploy - {error}");
// Store the aborted transaction.
aborted.push((transaction.clone(), error.to_string()));
// Continue to the next transaction.
continue 'outer;
}
},
},
}
}
// The finalize operation here involves calling 'update_key_value',
// and update the respective leaves of the finalize tree.
Transaction::Execute(_, execution, fee) => {
match process.finalize_execution(state, store, execution, fee.as_ref()) {
// Construct the accepted execute transaction.
Ok(finalize) => {
ConfirmedTransaction::accepted_execute(counter, transaction.clone(), finalize)
.map_err(|e| e.to_string())
}
// Construct the rejected execute transaction.
Err(_error) => match fee {
// Finalize the fee, to ensure it is valid.
Some(fee) => {
match process.finalize_fee(state, store, fee).and_then(|finalize| {
Transaction::from_fee(fee.clone()).map(|fee_tx| (fee_tx, finalize))
}) {
Ok((fee_tx, finalize)) => {
// Construct the rejected execution.
let rejected = Rejected::new_execution(execution.clone());
// Construct the rejected execute transaction.
ConfirmedTransaction::rejected_execute(counter, fee_tx, rejected, finalize)
.map_err(|e| e.to_string())
}
Err(error) => {
// Note: On failure, skip this transaction, and continue speculation.
#[cfg(debug_assertions)]
eprintln!("Failed to finalize the fee in a rejected execute - {error}");
// Store the aborted transaction.
aborted.push((transaction.clone(), error.to_string()));
// Continue to the next transaction.
continue 'outer;
}
}
}
// This is a foundational bug - the caller is violating protocol rules.
// Note: This will abort the entire atomic batch.
None => Err("Rejected execute transaction has no fee".to_string()),
},
}
}
// There are no finalize operations here.
// Note: This will abort the entire atomic batch.
Transaction::Fee(..) => Err("Cannot speculate on a fee transaction".to_string()),
};
lap!(timer, "Speculated on transaction '{}'", transaction.id());
match outcome {
// If the transaction succeeded, store it and continue to the next transaction.
Ok(confirmed_transaction) => {
// Add the transition IDs to the set of produced transition IDs.
transition_ids.extend(confirmed_transaction.transaction().transition_ids());
// Add the input IDs to the set of spent input IDs.
input_ids.extend(confirmed_transaction.transaction().input_ids());
// Add the output IDs to the set of produced output IDs.
output_ids.extend(confirmed_transaction.transaction().output_ids());
// Add the transition public keys to the set of produced transition public keys.
tpks.extend(confirmed_transaction.transaction().transition_public_keys());
// Store the confirmed transaction.
confirmed.push(confirmed_transaction);
// Increment the transaction index counter.
counter = counter.saturating_add(1);
}
// If the transaction failed, abort the entire batch.
Err(error) => {
eprintln!("Critical bug in speculate: {error}\n\n{transaction}");
// Note: This will abort the entire atomic batch.
return Err(format!("Failed to speculate on transaction - {error}"));
}
}
}
// Ensure all transactions were processed.
if confirmed.len() + aborted.len() != num_transactions {
// Note: This will abort the entire atomic batch.
return Err("Not all transactions were processed in 'VM::atomic_speculate'".to_string());
}
/* Perform the ratifications after finalize. */
// Prepare the reward ratifications, if any.
let reward_ratifications = match coinbase_reward {
// If the coinbase reward is `None`, then there are no reward ratifications.
None => vec![],
// If the coinbase reward is `Some(coinbase_reward)`, then we must compute the reward ratifications.
Some(coinbase_reward) => {
// Calculate the transaction fees.
let Ok(transaction_fees) =
confirmed.iter().map(|tx| Ok(*tx.priority_fee_amount()?)).sum::<Result<u64>>()
else {
// Note: This will abort the entire atomic batch.
return Err("Failed to calculate the transaction fees during speculation".to_string());
};
// Compute the block reward.
let block_reward = ledger_block::block_reward(
N::STARTING_SUPPLY,
N::BLOCK_TIME,
coinbase_reward,
transaction_fees,
);
// Compute the puzzle reward.
let puzzle_reward = ledger_block::puzzle_reward(coinbase_reward);
// Output the reward ratifications.
vec![Ratify::BlockReward(block_reward), Ratify::PuzzleReward(puzzle_reward)]
}
};
// Update the post-ratifications iterator.
let post_ratifications = reward_ratifications.iter().chain(post_ratifications);
// Process the post-ratifications.
match Self::atomic_post_ratify(store, state, post_ratifications, solutions) {
// Store the finalize operations from the post-ratify.
Ok(operations) => ratified_finalize_operations.extend(operations),
// Note: This will abort the entire atomic batch.
Err(e) => return Err(format!("Failed to post-ratify - {e}")),
}
/* Construct the ratifications after speculation. */
let Ok(ratifications) =
Ratifications::try_from_iter(reward_ratifications.into_iter().chain(ratifications.into_iter()))
else {
// Note: This will abort the entire atomic batch.
return Err("Failed to construct the ratifications after speculation".to_string());
};
finish!(timer);
// On return, 'atomic_finalize!' will abort the batch, and return the ratifications,
// confirmed & aborted transactions, and finalize operations from pre-ratify and post-ratify.
Ok((ratifications, confirmed, aborted, ratified_finalize_operations))
})
}
/// Performs atomic finalization over a list of transactions.
///
/// Returns the finalize operations from pre-ratify and post-ratify.
#[inline]
fn atomic_finalize(
&self,
state: FinalizeGlobalState,
ratifications: &Ratifications<N>,
solutions: &Solutions<N>,
transactions: &Transactions<N>,
) -> Result<Vec<FinalizeOperation<N>>> {
// Acquire the atomic lock, which is needed to ensure this function is not called concurrently
// with other `atomic_finalize!` macro calls, which will cause a `bail!` to be triggered erroneously.
// Note: This lock must be held for the entire scope of the call to `atomic_finalize!`.
let _atomic_lock = self.atomic_lock.lock();
let timer = timer!("VM::atomic_finalize");
// Perform the finalize operation on the preset finalize mode.
atomic_finalize!(self.finalize_store(), FinalizeMode::RealRun, {
// Initialize an iterator for ratifications before finalize.
let pre_ratifications = ratifications.iter().filter(|r| match r {
Ratify::Genesis(_, _, _) => true,
Ratify::BlockReward(..) | Ratify::PuzzleReward(..) => false,
});
// Initialize an iterator for ratifications after finalize.
let post_ratifications = ratifications.iter().filter(|r| match r {
Ratify::Genesis(_, _, _) => false,
Ratify::BlockReward(..) | Ratify::PuzzleReward(..) => true,
});
// Initialize a list of finalize operations.
let mut ratified_finalize_operations = Vec::new();
// Retrieve the finalize store.
let store = self.finalize_store();
/* Perform the ratifications before finalize. */
match Self::atomic_pre_ratify(store, state, pre_ratifications) {
// Store the finalize operations from the post-ratify.
Ok(operations) => ratified_finalize_operations.extend(operations),
// Note: This will abort the entire atomic batch.
Err(e) => return Err(format!("Failed to pre-ratify - {e}")),
}
/* Perform the atomic finalize over the transactions. */
// Acquire the write lock on the process.
// Note: Due to the highly-sensitive nature of processing all `finalize` calls,
// we choose to acquire the write lock for the entire duration of this atomic batch.
let mut process = self.process.write();
// Initialize a list for the deployed stacks.
let mut stacks = Vec::new();
// Finalize the transactions.
for (index, transaction) in transactions.iter().enumerate() {
// Convert the transaction index to a u32.
// Note: On failure, this will abort the entire atomic batch.
let index = u32::try_from(index).map_err(|_| "Failed to convert transaction index".to_string())?;
// Ensure the index matches the expected index.
if index != transaction.index() {
// Note: This will abort the entire atomic batch.
return Err(format!("Mismatch in {} transaction index", transaction.variant()));
}
// Process the transaction in an isolated atomic batch.
// - If the transaction succeeds, the finalize operations are stored.
// - If the transaction fails, the atomic batch is aborted and no finalize operations are stored.
let outcome: Result<(), String> = match transaction {
ConfirmedTransaction::AcceptedDeploy(_, transaction, finalize) => {
// Extract the deployment and fee from the transaction.
let (deployment, fee) = match transaction {
Transaction::Deploy(_, _, deployment, fee) => (deployment, fee),
// Note: This will abort the entire atomic batch.
_ => return Err("Expected deploy transaction".to_string()),
};
// The finalize operation here involves appending the 'stack', and adding the program to the finalize tree.
match process.finalize_deployment(state, store, deployment, fee) {
// Ensure the finalize operations match the expected.
Ok((stack, finalize_operations)) => match finalize == &finalize_operations {
// Store the stack.
true => stacks.push(stack),
// Note: This will abort the entire atomic batch.
false => {
return Err(format!(
"Mismatch in finalize operations for an accepted deploy - (found: {finalize_operations:?}, expected: {finalize:?})"
));
}
},
// Note: This will abort the entire atomic batch.
Err(error) => {
return Err(format!("Failed to finalize an accepted deploy transaction - {error}"));
}
};
Ok(())
}
ConfirmedTransaction::AcceptedExecute(_, transaction, finalize) => {
// Extract the execution and fee from the transaction.
let (execution, fee) = match transaction {
Transaction::Execute(_, execution, fee) => (execution, fee),
// Note: This will abort the entire atomic batch.
_ => return Err("Expected execute transaction".to_string()),
};
// The finalize operation here involves calling 'update_key_value',
// and update the respective leaves of the finalize tree.
match process.finalize_execution(state, store, execution, fee.as_ref()) {
// Ensure the finalize operations match the expected.
Ok(finalize_operations) => {
if finalize != &finalize_operations {
// Note: This will abort the entire atomic batch.
return Err(format!(
"Mismatch in finalize operations for an accepted execute - (found: {finalize_operations:?}, expected: {finalize:?})"
));
}
}
// Note: This will abort the entire atomic batch.
Err(error) => {
return Err(format!("Failed to finalize an accepted execute transaction - {error}"));
}
}
Ok(())
}
ConfirmedTransaction::RejectedDeploy(_, Transaction::Fee(_, fee), rejected, finalize) => {
// Extract the rejected deployment.
let Some(deployment) = rejected.deployment() else {
// Note: This will abort the entire atomic batch.
return Err("Expected rejected deployment".to_string());
};
// Compute the expected deployment ID.
let Ok(expected_deployment_id) = deployment.to_deployment_id() else {
// Note: This will abort the entire atomic batch.
return Err("Failed to compute the deployment ID for a rejected deployment".to_string());
};
// Retrieve the candidate deployment ID.
let Ok(candidate_deployment_id) = fee.deployment_or_execution_id() else {
// Note: This will abort the entire atomic batch.
return Err("Failed to retrieve the deployment ID from the fee".to_string());
};
// Ensure this fee corresponds to the deployment.
if candidate_deployment_id != expected_deployment_id {
// Note: This will abort the entire atomic batch.
return Err("Mismatch in fee for a rejected deploy transaction".to_string());
}
// Lastly, finalize the fee.
match process.finalize_fee(state, store, fee) {
// Ensure the finalize operations match the expected.
Ok(finalize_operations) => {
if finalize != &finalize_operations {
// Note: This will abort the entire atomic batch.
return Err(format!(
"Mismatch in finalize operations for a rejected deploy - (found: {finalize_operations:?}, expected: {finalize:?})"
));
}
}
// Note: This will abort the entire atomic batch.
Err(_e) => {
return Err("Failed to finalize the fee in a rejected deploy transaction".to_string());
}
}
Ok(())
}
ConfirmedTransaction::RejectedExecute(_, Transaction::Fee(_, fee), rejected, finalize) => {
// Extract the rejected execution.
let Some(execution) = rejected.execution() else {
// Note: This will abort the entire atomic batch.
return Err("Expected rejected execution".to_string());
};
// Compute the expected execution ID.
let Ok(expected_execution_id) = execution.to_execution_id() else {
// Note: This will abort the entire atomic batch.
return Err("Failed to compute the execution ID for a rejected execution".to_string());
};
// Retrieve the candidate execution ID.
let Ok(candidate_execution_id) = fee.deployment_or_execution_id() else {
// Note: This will abort the entire atomic batch.
return Err("Failed to retrieve the execution ID from the fee".to_string());
};
// Ensure this fee corresponds to the execution.
if candidate_execution_id != expected_execution_id {
// Note: This will abort the entire atomic batch.
return Err("Mismatch in fee for a rejected execute transaction".to_string());
}
// Lastly, finalize the fee.
match process.finalize_fee(state, store, fee) {
// Ensure the finalize operations match the expected.
Ok(finalize_operations) => {
if finalize != &finalize_operations {
// Note: This will abort the entire atomic batch.
return Err(format!(
"Mismatch in finalize operations for a rejected execute - (found: {finalize_operations:?}, expected: {finalize:?})"
));
}
}
// Note: This will abort the entire atomic batch.
Err(_e) => {
return Err("Failed to finalize the fee in a rejected execute transaction".to_string());
}
}
Ok(())
}
// Note: This will abort the entire atomic batch.
_ => return Err("Invalid confirmed transaction type".to_string()),
};
lap!(timer, "Finalizing transaction {}", transaction.id());
match outcome {
// If the transaction succeeded to finalize, continue to the next transaction.
Ok(()) => (),
// If the transaction failed to finalize, abort and continue to the next transaction.
Err(error) => {
eprintln!("Critical bug in finalize: {error}\n\n{transaction}");
// Note: This will abort the entire atomic batch.
return Err(format!("Failed to finalize on transaction - {error}"));
}
}
}
/* Perform the ratifications after finalize. */
match Self::atomic_post_ratify(store, state, post_ratifications, solutions) {
// Store the finalize operations from the post-ratify.
Ok(operations) => ratified_finalize_operations.extend(operations),
// Note: This will abort the entire atomic batch.
Err(e) => return Err(format!("Failed to post-ratify - {e}")),
}
/* Start the commit process. */
// Commit all of the stacks to the process.
if !stacks.is_empty() {
stacks.into_iter().for_each(|stack| process.add_stack(stack))
}
finish!(timer); // <- Note: This timer does **not** include the time to write batch to DB.
Ok(ratified_finalize_operations)
})
}
/// Performs the pre-ratifications before finalizing transactions.
#[inline]
fn atomic_pre_ratify<'a>(
store: &FinalizeStore<N, C::FinalizeStorage>,
state: FinalizeGlobalState,
pre_ratifications: impl Iterator<Item = &'a Ratify<N>>,
) -> Result<Vec<FinalizeOperation<N>>> {
// Construct the program ID.
let program_id = ProgramID::from_str("credits.aleo")?;
// Construct the committee mapping name.
let committee_mapping = Identifier::from_str("committee")?;
// Construct the bonded mapping name.
let bonded_mapping = Identifier::from_str("bonded")?;
// Construct the account mapping name.
let account_mapping = Identifier::from_str("account")?;
// Construct the metadata mapping name.
let metadata_mapping = Identifier::from_str("metadata")?;
// Initialize a list of finalize operations.
let mut finalize_operations = Vec::new();
// Initialize a flag for the genesis ratification.
let mut is_genesis_ratified = false;
// Iterate over the ratifications.
for ratify in pre_ratifications {
match ratify {
Ratify::Genesis(committee, public_balances, bonded_balances) => {
// Ensure this is the genesis block.
ensure!(state.block_height() == 0, "Ratify::Genesis(..) expected a genesis block");
// Ensure the genesis committee round is 0.
ensure!(
committee.starting_round() == 0,
"Ratify::Genesis(..) expected a genesis committee round of 0"
);
// Ensure that the number of members in the committee does not exceed the maximum.
ensure!(
committee.members().len() <= Committee::<N>::MAX_COMMITTEE_SIZE as usize,
"Ratify::Genesis(..) exceeds the maximum number of committee members"
);
// Ensure that the number of delegators does not exceed the maximum.
ensure!(
bonded_balances.len().saturating_sub(committee.members().len()) <= MAX_DELEGATORS as usize,
"Ratify::Genesis(..) exceeds the maximum number of delegators"
);
// Ensure genesis has not been ratified yet.
ensure!(!is_genesis_ratified, "Ratify::Genesis(..) has already been ratified");
// TODO (howardwu): Consider whether to initialize the mappings here.
// Currently, this is breaking for test cases that use VM but do not insert the genesis block.
// // Initialize the store for 'credits.aleo'.
// let credits = Program::<N>::credits()?;
// for mapping in credits.mappings().values() {
// // Ensure that all mappings are initialized.
// if !store.contains_mapping_confirmed(credits.id(), mapping.name())? {
// // Initialize the mappings for 'credits.aleo'.
// finalize_operations.push(store.initialize_mapping(*credits.id(), *mapping.name())?);
// }
// }
// Calculate the stake per validator using `bonded_balances`.
let mut stake_per_validator = IndexMap::with_capacity(committee.members().len());
for (address, (validator_address, amount)) in bonded_balances.iter() {
// Check that the amount meets the minimum requirement, depending on whether the address is a validator.
if *address == *validator_address {
ensure!(
*amount >= MIN_VALIDATOR_STAKE,
"Ratify::Genesis(..) the validator {address} must stake at least {MIN_VALIDATOR_STAKE}",
);
} else {
ensure!(
*amount >= MIN_DELEGATOR_STAKE,
"Ratify::Genesis(..) the delegator {address} must stake at least {MIN_DELEGATOR_STAKE}",
);
// If the address is a delegator, check that the corresponding validator is open.
ensure!(
committee.is_committee_member_open(*validator_address),
"Ratify::Genesis(..) the delegator {address} is delegating to a closed validator {validator_address}",
);
}
// Accumulate the staked amount per validator.
let total = stake_per_validator.entry(validator_address).or_insert(0u64);
*total = total.saturating_add(*amount);
}
// Ensure the stake per validator matches the committee.
ensure!(
stake_per_validator.len() == committee.members().len(),
"Ratify::Genesis(..) the number of validators in the committee does not match the number of validators in the bonded balances",
);
// Check that `committee` is consistent with `stake_per_validator`.
for (validator_address, amount) in &stake_per_validator {
// Retrieve the expected validator stake from the committee.
let Some((expected_amount, _)) = committee.members().get(*validator_address) else {
bail!(
"Ratify::Genesis(..) found a validator in the bonded balances that is not in the committee"
)
};
// Ensure the staked amount matches the committee.
ensure!(
*expected_amount == *amount,
"Ratify::Genesis(..) inconsistent staked amount for validator {validator_address}",
);
}
// Ensure that the total stake matches the sum of the staked amounts.
ensure!(
committee.total_stake() == stake_per_validator.values().sum::<u64>(),
"Ratify::Genesis(..) incorrect total total stake for the committee"
);
// Construct the next committee map and next bonded map.
let (next_committee_map, next_bonded_map) =
to_next_commitee_map_and_bonded_map(committee, bonded_balances);
// Insert the next committee into storage.
store.committee_store().insert(state.block_height(), *(committee.clone()))?;
// Store the finalize operations for updating the committee and bonded mapping.
finalize_operations.extend(&[
// Replace the committee mapping in storage.
store.replace_mapping(program_id, committee_mapping, next_committee_map)?,
// Replace the bonded mapping in storage.
store.replace_mapping(program_id, bonded_mapping, next_bonded_map)?,
]);
// Update the number of validators.
finalize_operations.extend(&[
// Update the number of validators in the metadata mapping.
store.update_key_value(
program_id,
metadata_mapping,
Plaintext::from_str("aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc")?,
Value::from_str(&format!("{}u32", committee.num_members()))?,
)?,
]);
// Update the number of delegators.
finalize_operations.extend(&[
// Update the number of delegators in the metadata mapping.
store.update_key_value(
program_id,
metadata_mapping,
Plaintext::from_str("aleo1qgqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqanmpl0")?,
Value::from_str(&format!(
"{}u32",
bonded_balances.len().saturating_sub(committee.num_members())
))?,
)?,
]);
// Map the public balances into the appropriate format.
let public_balances = public_balances
.iter()
.map(|(address, amount)| {
(Plaintext::from(Literal::Address(*address)), Value::from(Literal::U64(U64::new(*amount))))
})
.collect::<Vec<_>>();
// Update the public balances.
finalize_operations.extend(&[
// Update the public balances in storage.
store.replace_mapping(program_id, account_mapping, public_balances)?,
]);
// Set the genesis ratification flag.
is_genesis_ratified = true;
}
Ratify::BlockReward(..) | Ratify::PuzzleReward(..) => continue,
}
}
// Return the finalize operations.
Ok(finalize_operations)
}
/// Performs the post-ratifications after finalizing transactions.
#[inline]
fn atomic_post_ratify<'a>(
store: &FinalizeStore<N, C::FinalizeStorage>,
state: FinalizeGlobalState,
post_ratifications: impl Iterator<Item = &'a Ratify<N>>,
solutions: &Solutions<N>,
) -> Result<Vec<FinalizeOperation<N>>> {
// Construct the program ID.
let program_id = ProgramID::from_str("credits.aleo")?;
// Construct the committee mapping name.
let committee_mapping = Identifier::from_str("committee")?;
// Construct the bonded mapping name.
let bonded_mapping = Identifier::from_str("bonded")?;
// Construct the account mapping name.
let account_mapping = Identifier::from_str("account")?;
// Initialize a list of finalize operations.
let mut finalize_operations = Vec::new();
// Initialize a flag for the block reward ratification.