-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathblockchain.rs
More file actions
1637 lines (1458 loc) · 63.9 KB
/
Copy pathblockchain.rs
File metadata and controls
1637 lines (1458 loc) · 63.9 KB
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
pub mod constants;
pub mod error;
pub mod fork_choice;
pub mod mempool;
pub mod payload;
mod smoke_test;
pub mod tracing;
pub mod vm;
use ::tracing::{debug, info, instrument, trace};
use constants::{MAX_INITCODE_SIZE, MAX_TRANSACTION_DATA_SIZE, POST_OSAKA_GAS_LIMIT_CAP};
use error::MempoolError;
use error::{ChainError, InvalidBlockError};
use ethrex_common::constants::{
EMPTY_TRIE_HASH, GAS_PER_BLOB, MAX_RLP_BLOCK_SIZE, MIN_BASE_FEE_PER_BLOB_GAS,
};
use ethrex_common::types::block_execution_witness::ExecutionWitness;
use ethrex_common::types::fee_config::FeeConfig;
use ethrex_common::types::requests::{EncodedRequests, Requests, compute_requests_hash};
use ethrex_common::types::{
AccountState, AccountUpdate, Block, BlockHash, BlockHeader, BlockNumber, ChainConfig, Code,
EIP4844Transaction, Receipt, Transaction, WrappedEIP4844Transaction, compute_receipts_root,
validate_block_header, validate_cancun_header_fields, validate_prague_header_fields,
validate_pre_cancun_header_fields,
};
use ethrex_common::types::{ELASTICITY_MULTIPLIER, P2PTransaction};
use ethrex_common::types::{Fork, MempoolTransaction};
use ethrex_common::{Address, H256, TrieLogger};
use ethrex_metrics::metrics;
use ethrex_rlp::decode::RLPDecode;
use ethrex_rlp::encode::RLPEncode;
use ethrex_storage::{
AccountUpdatesList, Store, UpdateBatch, error::StoreError, hash_address, hash_key,
};
use ethrex_trie::{Nibbles, Trie};
use ethrex_vm::backends::levm::db::DatabaseLogger;
use ethrex_vm::{BlockExecutionResult, DynVmDatabase, Evm, EvmError};
use mempool::Mempool;
use payload::PayloadOrTask;
use rustc_hash::FxHashMap;
use std::collections::hash_map::Entry;
use std::collections::{BTreeMap, HashMap};
use std::sync::{
Arc, Mutex, RwLock,
atomic::{AtomicBool, AtomicUsize, Ordering},
mpsc::{Receiver, channel},
};
use std::time::Instant;
use tokio::sync::Mutex as TokioMutex;
use tokio_util::sync::CancellationToken;
use vm::StoreVmDatabase;
#[cfg(feature = "metrics")]
use ethrex_metrics::metrics_blocks::METRICS_BLOCKS;
#[cfg(feature = "c-kzg")]
use ethrex_common::types::BlobsBundle;
const MAX_PAYLOADS: usize = 10;
const MAX_MEMPOOL_SIZE_DEFAULT: usize = 10_000;
type StoreUpdatesMap = FxHashMap<H256, (Result<Trie, StoreError>, FxHashMap<Nibbles, Vec<u8>>)>;
//TODO: Implement a struct Chain or BlockChain to encapsulate
//functionality and canonical chain state and config
#[derive(Debug, Clone, Default)]
pub enum BlockchainType {
#[default]
L1,
L2(L2Config),
}
#[derive(Debug, Clone, Default)]
pub struct L2Config {
/// We use a RwLock because the Watcher updates the L1 fee config periodically
pub fee_config: Arc<RwLock<FeeConfig>>,
}
#[derive(Debug)]
pub struct Blockchain {
storage: Store,
pub mempool: Mempool,
/// Whether the node's chain is in or out of sync with the current chain
/// This will be set to true once the initial sync has taken place and wont be set to false after
/// This does not reflect whether there is an ongoing sync process
is_synced: AtomicBool,
pub options: BlockchainOptions,
/// Mapping from a payload id to either a complete payload or a payload build task
/// We need to keep completed payloads around in case consensus requests them twice
pub payloads: Arc<TokioMutex<Vec<(u64, PayloadOrTask)>>>,
}
#[derive(Debug, Clone)]
pub struct BlockchainOptions {
pub max_mempool_size: usize,
/// Whether performance logs should be emitted
pub perf_logs_enabled: bool,
pub r#type: BlockchainType,
}
impl Default for BlockchainOptions {
fn default() -> Self {
Self {
max_mempool_size: MAX_MEMPOOL_SIZE_DEFAULT,
perf_logs_enabled: false,
r#type: BlockchainType::default(),
}
}
}
#[derive(Debug, Clone)]
pub struct BatchBlockProcessingFailure {
pub last_valid_hash: H256,
pub failed_block_hash: H256,
}
fn log_batch_progress(batch_size: u32, current_block: u32) {
let progress_needed = batch_size > 10;
const PERCENT_MARKS: [u32; 4] = [20, 40, 60, 80];
if progress_needed {
PERCENT_MARKS.iter().for_each(|mark| {
if (batch_size * mark) / 100 == current_block {
info!("[SYNCING] {mark}% of batch processed");
}
});
}
}
impl Blockchain {
pub fn new(store: Store, blockchain_opts: BlockchainOptions) -> Self {
Self {
storage: store,
mempool: Mempool::new(blockchain_opts.max_mempool_size),
is_synced: AtomicBool::new(false),
payloads: Arc::new(TokioMutex::new(Vec::new())),
options: blockchain_opts,
}
}
pub fn default_with_store(store: Store) -> Self {
Self {
storage: store,
mempool: Mempool::new(MAX_MEMPOOL_SIZE_DEFAULT),
is_synced: AtomicBool::new(false),
payloads: Arc::new(TokioMutex::new(Vec::new())),
options: BlockchainOptions::default(),
}
}
/// Executes a block withing a new vm instance and state
fn execute_block(
&self,
block: &Block,
) -> Result<(BlockExecutionResult, Vec<AccountUpdate>), ChainError> {
// Validate if it can be the new head and find the parent
let Ok(parent_header) = find_parent_header(&block.header, &self.storage) else {
// If the parent is not present, we store it as pending.
self.storage.add_pending_block(block.clone())?;
return Err(ChainError::ParentNotFound);
};
let chain_config = self.storage.get_chain_config();
// Validate the block pre-execution
validate_block(block, &parent_header, &chain_config, ELASTICITY_MULTIPLIER)?;
let vm_db = StoreVmDatabase::new(self.storage.clone(), parent_header);
let mut vm = self.new_evm(vm_db)?;
let execution_result = vm.execute_block(block)?;
let account_updates = vm.get_state_transitions()?;
// Validate execution went alright
validate_gas_used(&execution_result.receipts, &block.header)?;
validate_receipts_root(&block.header, &execution_result.receipts)?;
validate_requests_hash(&block.header, &chain_config, &execution_result.requests)?;
Ok((execution_result, account_updates))
}
/// Executes a block withing a new vm instance and state
#[instrument(level = "trace", name = "Execute Block", skip_all)]
fn execute_block_pipeline(
&self,
block: &Block,
) -> Result<
(
BlockExecutionResult,
AccountUpdatesList,
// FIXME: extract to stats struct
usize,
[Instant; 6],
),
ChainError,
> {
let start_instant = Instant::now();
// Validate if it can be the new head and find the parent
let Ok(parent_header) = find_parent_header(&block.header, &self.storage) else {
// If the parent is not present, we store it as pending.
self.storage.add_pending_block(block.clone())?;
return Err(ChainError::ParentNotFound);
};
let chain_config = self.storage.get_chain_config();
// Validate the block pre-execution
validate_block(block, &parent_header, &chain_config, ELASTICITY_MULTIPLIER)?;
let block_validated_instant = Instant::now();
let vm_db = StoreVmDatabase::new(self.storage.clone(), parent_header.clone());
let mut vm = self.new_evm(vm_db)?;
let exec_merkle_start = Instant::now();
let queue_length = AtomicUsize::new(0);
let queue_length_ref = &queue_length;
let mut max_queue_length = 0;
let (execution_result, account_updates_list) = std::thread::scope(|s| {
let (tx, rx) = channel();
let execution_handle = s.spawn(move || -> Result<_, ChainError> {
let execution_result = vm.execute_block_pipeline(block, tx, queue_length_ref)?;
// Validate execution went alright
validate_gas_used(&execution_result.receipts, &block.header)?;
validate_receipts_root(&block.header, &execution_result.receipts)?;
validate_requests_hash(&block.header, &chain_config, &execution_result.requests)?;
let exec_end_instant = Instant::now();
Ok((execution_result, exec_end_instant))
});
let merkleize_handle = s.spawn(move || -> Result<_, StoreError> {
let account_updates_list = self.handle_merkleization(
rx,
&parent_header,
queue_length_ref,
&mut max_queue_length,
)?;
let merkle_end_instant = Instant::now();
Ok((account_updates_list, merkle_end_instant))
});
(
execution_handle.join().unwrap_or_else(|_| {
Err(ChainError::Custom("execution thread panicked".to_string()))
}),
merkleize_handle.join().unwrap_or_else(|_| {
Err(StoreError::Custom(
"merklization thread panicked".to_string(),
))
}),
)
});
let (account_updates_list, merkle_end_instant) = account_updates_list?;
let (execution_result, exec_end_instant) = execution_result?;
let exec_merkle_end_instant = Instant::now();
Ok((
execution_result,
account_updates_list,
max_queue_length,
[
start_instant,
block_validated_instant,
exec_merkle_start,
exec_end_instant,
merkle_end_instant,
exec_merkle_end_instant,
],
))
}
#[instrument(level = "trace", name = "Trie update", skip_all)]
fn handle_merkleization(
&self,
rx: Receiver<Vec<AccountUpdate>>,
parent_header: &BlockHeader,
queue_length: &AtomicUsize,
max_queue_length: &mut usize,
) -> Result<AccountUpdatesList, StoreError> {
let mut state_trie = self
.storage
.state_trie(parent_header.hash())?
.ok_or(StoreError::MissingStore)?;
let mut state_trie_hash = H256::default();
let mut state_updates_map: FxHashMap<Nibbles, Vec<u8>> = Default::default();
let mut storage_updates_map: StoreUpdatesMap = Default::default();
let mut code_updates: FxHashMap<H256, Code> = Default::default();
let mut account_states: FxHashMap<H256, AccountState> = Default::default();
for updates in rx {
let current_length = queue_length.fetch_sub(1, Ordering::Acquire);
*max_queue_length = current_length.max(*max_queue_length);
state_trie_hash = Self::process_incoming_update_message(
&self.storage,
&mut state_trie,
updates,
&mut storage_updates_map,
parent_header,
&mut state_updates_map,
&mut code_updates,
&mut account_states,
)?;
}
let state_updates = state_updates_map.into_iter().collect();
let storage_updates = storage_updates_map
.into_iter()
.map(|(a, (_, s))| (a, s.into_iter().collect()))
.collect();
let code_updates = code_updates.into_iter().collect();
Ok(AccountUpdatesList {
state_trie_hash,
state_updates,
storage_updates,
code_updates,
})
}
/// Processes a batch of account updates, applying them to the state trie and storage tries,
/// and returns the new state root.
#[allow(clippy::too_many_arguments)]
fn process_incoming_update_message(
storage: &Store,
state_trie: &mut Trie,
updates: Vec<AccountUpdate>,
storage_updates_map: &mut StoreUpdatesMap,
parent_header: &BlockHeader,
state_updates_map: &mut FxHashMap<Nibbles, Vec<u8>>,
code_updates: &mut FxHashMap<H256, Code>,
account_states: &mut FxHashMap<H256, AccountState>,
) -> Result<H256, StoreError> {
trace!("Execute block pipeline: Received {} updates", updates.len());
// Apply the account updates over the last block's state and compute the new state root
for update in updates {
let hashed_address = hash_address(&update.address);
let hashed_address_h256 = H256::from_slice(&hashed_address);
trace!(
"Execute block pipeline: Update cycle for {}",
hex::encode(&hashed_address)
);
if update.removed {
// Remove account from trie
state_trie.remove(&hashed_address)?;
account_states.remove(&hashed_address_h256);
continue;
}
// Add or update AccountState in the trie
// Fetch current state or create a new state to be inserted
let account_state = match account_states.entry(hashed_address_h256) {
Entry::Occupied(occupied_entry) => {
trace!(
"Found account state in cache for {}",
hex::encode(&hashed_address)
);
occupied_entry.into_mut()
}
Entry::Vacant(vacant_entry) => {
let account_state = match state_trie.get(&hashed_address)? {
Some(encoded_state) => {
trace!(
"Found account state in trie for {}",
hex::encode(&hashed_address)
);
AccountState::decode(&encoded_state)?
}
None => {
trace!(
"Created account state in trie for {}",
hex::encode(&hashed_address)
);
AccountState::default()
}
};
vacant_entry.insert(account_state)
}
};
if update.removed_storage {
account_state.storage_root = *EMPTY_TRIE_HASH;
storage_updates_map.remove(&hashed_address_h256);
}
if let Some(info) = &update.info {
trace!(
nonce = info.nonce,
balance = hex::encode(info.balance.to_big_endian()),
code_hash = hex::encode(info.code_hash),
"With info"
);
account_state.nonce = info.nonce;
account_state.balance = info.balance;
account_state.code_hash = info.code_hash;
// Store updated code in DB
if let Some(code) = &update.code {
trace!("Updated code");
code_updates.insert(info.code_hash, code.clone());
}
}
// Store the added storage in the account's storage trie and compute its new root
if !update.added_storage.is_empty() {
trace!(count = update.added_storage.len(), "Update storages");
let (storage_trie, storage_updates_map) = storage_updates_map
.entry(hashed_address_h256)
.or_insert_with(|| {
(
storage.open_storage_trie(
hashed_address_h256,
account_state.storage_root,
parent_header.state_root,
),
Default::default(),
)
});
let Ok(storage_trie) = storage_trie else {
debug!(
"Failed to open storage trie for account {}",
hex::encode(&hashed_address)
);
return Err(StoreError::Custom("Error opening storage trie".to_string()));
};
for (storage_key, storage_value) in &update.added_storage {
let hashed_key = hash_key(storage_key);
if storage_value.is_zero() {
trace!(slot = hex::encode(&hashed_key), "Removing");
storage_trie.remove(&hashed_key)?;
} else {
trace!(slot = hex::encode(&hashed_key), "Inserting");
storage_trie.insert(hashed_key, storage_value.encode_to_vec())?;
}
}
trace!(
"Collecting storage changes for account {}",
hex::encode(&hashed_address)
);
let (storage_hash, storage_updates) =
storage_trie.collect_changes_since_last_hash();
trace!(
"Storage changes collected for account {}",
hex::encode(&hashed_address)
);
storage_updates_map.extend(storage_updates);
account_state.storage_root = storage_hash;
}
state_trie.insert(hashed_address, account_state.encode_to_vec())?;
}
let (state_trie_hash, state_updates) = state_trie.collect_changes_since_last_hash();
state_updates_map.extend(state_updates);
Ok(state_trie_hash)
}
/// Executes a block from a given vm instance an does not clear its state
fn execute_block_from_state(
&self,
parent_header: &BlockHeader,
block: &Block,
chain_config: &ChainConfig,
vm: &mut Evm,
) -> Result<BlockExecutionResult, ChainError> {
// Validate the block pre-execution
validate_block(block, parent_header, chain_config, ELASTICITY_MULTIPLIER)?;
let execution_result = vm.execute_block(block)?;
// Validate execution went alright
validate_gas_used(&execution_result.receipts, &block.header)?;
validate_receipts_root(&block.header, &execution_result.receipts)?;
validate_requests_hash(&block.header, chain_config, &execution_result.requests)?;
Ok(execution_result)
}
pub async fn generate_witness_for_blocks(
&self,
blocks: &[Block],
) -> Result<ExecutionWitness, ChainError> {
self.generate_witness_for_blocks_with_fee_configs(blocks, None)
.await
}
pub async fn generate_witness_for_blocks_with_fee_configs(
&self,
blocks: &[Block],
fee_configs: Option<&[FeeConfig]>,
) -> Result<ExecutionWitness, ChainError> {
let first_block_header = &blocks
.first()
.ok_or(ChainError::WitnessGeneration(
"Empty block batch".to_string(),
))?
.header;
// Later on, we need to access block hashes by number. To avoid needing
// to apply fork choice for each block, we cache them here.
// The clone is not redundant, the hash function modifies the original block.
#[allow(clippy::redundant_clone)]
let mut block_hashes_map: BTreeMap<u64, H256> = blocks
.iter()
.cloned()
.map(|block| (block.header.number, block.hash()))
.collect();
block_hashes_map.insert(
first_block_header.number.saturating_sub(1),
first_block_header.parent_hash,
);
// Get state at previous block
let trie = self
.storage
.state_trie(first_block_header.parent_hash)
.map_err(|_| ChainError::ParentStateNotFound)?
.ok_or(ChainError::ParentStateNotFound)?;
let (mut current_trie_witness, mut trie) = TrieLogger::open_trie(trie);
// For each block, a new TrieLogger will be opened, each containing the
// witness accessed during the block execution. We need to accumulate
// all the nodes accessed during the entire batch execution.
let mut accumulated_state_trie_witness = current_trie_witness
.lock()
.map_err(|_| {
ChainError::WitnessGeneration("Failed to lock state trie witness".to_string())
})?
.clone();
let mut touched_account_storage_slots = BTreeMap::new();
// This will become the state trie + storage trie
let mut used_trie_nodes = Vec::new();
// Store the root node in case the block is empty and the witness does not record any nodes
let root_node = trie.root_node().map_err(|_| {
ChainError::WitnessGeneration("Failed to get root state node".to_string())
})?;
let mut block_hashes = HashMap::new();
let mut codes = Vec::new();
for (i, block) in blocks.iter().enumerate() {
let parent_hash = block.header.parent_hash;
let parent_header = self
.storage
.get_block_header_by_hash(parent_hash)
.map_err(ChainError::StoreError)?
.ok_or(ChainError::ParentNotFound)?;
// This assumes that the user has the necessary state stored already,
// so if the user only has the state previous to the first block, it
// will fail in the second iteration of this for loop. To ensure this,
// doesn't fail, later in this function we store the new state after
// re-execution.
let vm_db: DynVmDatabase =
Box::new(StoreVmDatabase::new(self.storage.clone(), parent_header));
let logger = Arc::new(DatabaseLogger::new(Arc::new(Mutex::new(Box::new(vm_db)))));
let mut vm = match self.options.r#type {
BlockchainType::L1 => Evm::new_from_db_for_l1(logger.clone()),
BlockchainType::L2(_) => {
let l2_config = match fee_configs {
Some(fee_configs) => {
fee_configs.get(i).ok_or(ChainError::WitnessGeneration(
"FeeConfig not found for witness generation".to_string(),
))?
}
None => Err(ChainError::WitnessGeneration(
"L2Config not found for witness generation".to_string(),
))?,
};
Evm::new_from_db_for_l2(logger.clone(), *l2_config)
}
};
// Re-execute block with logger
let execution_result = vm.execute_block(block)?;
// Gather account updates
let account_updates = vm.get_state_transitions()?;
for account_update in &account_updates {
touched_account_storage_slots.insert(
account_update.address,
account_update
.added_storage
.keys()
.cloned()
.collect::<Vec<H256>>(),
);
}
// Get the used block hashes from the logger
let logger_block_hashes = logger
.block_hashes_accessed
.lock()
.map_err(|_e| {
ChainError::WitnessGeneration("Failed to get block hashes".to_string())
})?
.clone();
block_hashes.extend(logger_block_hashes);
// Access all the accounts needed for withdrawals
if let Some(withdrawals) = block.body.withdrawals.as_ref() {
for withdrawal in withdrawals {
trie.get(&hash_address(&withdrawal.address)).map_err(|_e| {
ChainError::Custom("Failed to access account from trie".to_string())
})?;
}
}
let mut used_storage_tries = HashMap::new();
// Access all the accounts from the initial trie
// Record all the storage nodes for the initial state
for (account, acc_keys) in logger
.state_accessed
.lock()
.map_err(|_e| {
ChainError::WitnessGeneration("Failed to execute with witness".to_string())
})?
.iter()
{
// Access the account from the state trie to record the nodes used to access it
trie.get(&hash_address(account)).map_err(|_e| {
ChainError::WitnessGeneration("Failed to access account from trie".to_string())
})?;
// Get storage trie at before updates
if !acc_keys.is_empty()
&& let Ok(Some(storage_trie)) = self.storage.storage_trie(parent_hash, *account)
{
let (storage_trie_witness, storage_trie) = TrieLogger::open_trie(storage_trie);
// Access all the keys
for storage_key in acc_keys {
let hashed_key = hash_key(storage_key);
storage_trie.get(&hashed_key).map_err(|_e| {
ChainError::WitnessGeneration(
"Failed to access storage key".to_string(),
)
})?;
}
// Store the tries to reuse when applying account updates
used_storage_tries.insert(*account, (storage_trie_witness, storage_trie));
}
}
// Store all the accessed evm bytecodes
for code_hash in logger
.code_accessed
.lock()
.map_err(|_e| {
ChainError::WitnessGeneration("Failed to gather used bytecodes".to_string())
})?
.iter()
{
let code = self
.storage
.get_account_code(*code_hash)
.map_err(|_e| {
ChainError::WitnessGeneration("Failed to get account code".to_string())
})?
.ok_or(ChainError::WitnessGeneration(
"Failed to get account code".to_string(),
))?;
codes.push(code.bytecode.to_vec());
}
// Apply account updates to the trie recording all the necessary nodes to do so
let (storage_tries_after_update, account_updates_list) = self
.storage
.apply_account_updates_from_trie_with_witness(
trie,
&account_updates,
used_storage_tries,
)
.await?;
// We cannot ensure that the users of this function have the necessary
// state stored, so in order for it to not assume anything, we update
// the storage with the new state after re-execution
self.store_block(block.clone(), account_updates_list, execution_result)?;
for (address, (witness, _storage_trie)) in storage_tries_after_update {
let mut witness = witness.lock().map_err(|_| {
ChainError::WitnessGeneration("Failed to lock storage trie witness".to_string())
})?;
let witness = std::mem::take(&mut *witness);
let witness = witness.into_iter().collect::<Vec<_>>();
used_trie_nodes.extend_from_slice(&witness);
touched_account_storage_slots.entry(address).or_default();
}
let (new_state_trie_witness, updated_trie) = TrieLogger::open_trie(
self.storage
.state_trie(
block_hashes_map
.get(&block.header.number)
.ok_or(ChainError::WitnessGeneration(
"Block hash not found for witness generation".to_string(),
))?
.to_owned(),
)
.map_err(|_| ChainError::ParentStateNotFound)?
.ok_or(ChainError::ParentStateNotFound)?,
);
// Use the updated state trie for the next block
trie = updated_trie;
for state_trie_witness in current_trie_witness
.lock()
.map_err(|_| {
ChainError::WitnessGeneration("Failed to lock state trie witness".to_string())
})?
.iter()
{
accumulated_state_trie_witness.insert(state_trie_witness.clone());
}
current_trie_witness = new_state_trie_witness;
}
used_trie_nodes
.extend_from_slice(&Vec::from_iter(accumulated_state_trie_witness.into_iter()));
// If the witness is empty at least try to store the root
if used_trie_nodes.is_empty()
&& let Some(root) = root_node
{
used_trie_nodes.push(root.encode_to_vec());
}
let mut needed_block_numbers = block_hashes.keys().collect::<Vec<_>>();
needed_block_numbers.sort();
// Last needed block header for the witness is the parent of the last block we need to execute
let last_needed_block_number = blocks
.last()
.ok_or(ChainError::WitnessGeneration("Empty batch".to_string()))?
.header
.number
.saturating_sub(1);
// The first block number we need is either the parent of the first block number or the earliest block number used by BLOCKHASH
let mut first_needed_block_number = first_block_header.number.saturating_sub(1);
if let Some(block_number_from_logger) = needed_block_numbers.first()
&& **block_number_from_logger < first_needed_block_number
{
first_needed_block_number = **block_number_from_logger;
}
let mut block_headers_bytes = Vec::new();
for block_number in first_needed_block_number..=last_needed_block_number {
let hash = block_hashes_map
.get(&block_number)
.ok_or(ChainError::WitnessGeneration(format!(
"Failed to get block {block_number} hash"
)))?;
let header = self.storage.get_block_header_by_hash(*hash)?.ok_or(
ChainError::WitnessGeneration(format!("Failed to get block {block_number} header")),
)?;
block_headers_bytes.push(header.encode_to_vec());
}
let chain_config = self.storage.get_chain_config();
let nodes = used_trie_nodes.into_iter().collect::<Vec<_>>();
let mut keys = Vec::new();
for (address, touched_storage_slots) in touched_account_storage_slots {
keys.push(address.as_bytes().to_vec());
for slot in touched_storage_slots.iter() {
keys.push(slot.as_bytes().to_vec());
}
}
Ok(ExecutionWitness {
codes,
block_headers_bytes,
first_block_number: first_block_header.number,
chain_config,
nodes,
keys,
})
}
pub fn store_block(
&self,
block: Block,
account_updates_list: AccountUpdatesList,
execution_result: BlockExecutionResult,
) -> Result<(), ChainError> {
// Check state root matches the one in block header
validate_state_root(&block.header, account_updates_list.state_trie_hash)?;
let update_batch = UpdateBatch {
account_updates: account_updates_list.state_updates,
storage_updates: account_updates_list.storage_updates,
receipts: vec![(block.hash(), execution_result.receipts)],
blocks: vec![block],
code_updates: account_updates_list.code_updates,
};
self.storage
.store_block_updates(update_batch)
.map_err(|e| e.into())
}
pub fn add_block(&self, block: Block) -> Result<(), ChainError> {
let since = Instant::now();
let (res, updates) = self.execute_block(&block)?;
let executed = Instant::now();
// Apply the account updates over the last block's state and compute the new state root
let account_updates_list = self
.storage
.apply_account_updates_batch(block.header.parent_hash, &updates)?
.ok_or(ChainError::ParentStateNotFound)?;
let (gas_used, gas_limit, block_number, transactions_count) = (
block.header.gas_used,
block.header.gas_limit,
block.header.number,
block.body.transactions.len(),
);
let merkleized = Instant::now();
let result = self.store_block(block, account_updates_list, res);
let stored = Instant::now();
if self.options.perf_logs_enabled {
Self::print_add_block_logs(
gas_used,
gas_limit,
block_number,
transactions_count,
since,
executed,
merkleized,
stored,
);
}
result
}
pub fn add_block_pipeline(&self, block: Block) -> Result<(), ChainError> {
let (res, account_updates_list, merkle_queue_length, instants) =
self.execute_block_pipeline(&block)?;
let (gas_used, gas_limit, block_number, transactions_count) = (
block.header.gas_used,
block.header.gas_limit,
block.header.number,
block.body.transactions.len(),
);
let result = self.store_block(block, account_updates_list, res);
let stored = Instant::now();
let instants = std::array::from_fn(move |i| {
if i < instants.len() {
instants[i]
} else {
stored
}
});
if self.options.perf_logs_enabled {
Self::print_add_block_pipeline_logs(
gas_used,
gas_limit,
block_number,
transactions_count,
merkle_queue_length,
instants,
);
}
result
}
#[allow(clippy::too_many_arguments)]
fn print_add_block_logs(
gas_used: u64,
gas_limit: u64,
block_number: u64,
transactions_count: usize,
since: Instant,
executed: Instant,
merkleized: Instant,
stored: Instant,
) {
let interval = stored.duration_since(since).as_millis() as f64;
if interval != 0f64 {
let as_gigas = gas_used as f64 / 10_f64.powf(9_f64);
let throughput = as_gigas / interval * 1000_f64;
metrics!(
METRICS_BLOCKS.set_block_number(block_number);
METRICS_BLOCKS.set_latest_gas_used(gas_used as f64);
METRICS_BLOCKS.set_latest_block_gas_limit(gas_limit as f64);
METRICS_BLOCKS.set_latest_gigagas(throughput);
METRICS_BLOCKS.set_execution_ms(executed.duration_since(since).as_millis() as i64);
METRICS_BLOCKS.set_merkle_ms(merkleized.duration_since(executed).as_millis() as i64);
METRICS_BLOCKS.set_store_ms(stored.duration_since(merkleized).as_millis() as i64);
METRICS_BLOCKS.set_transaction_count(transactions_count as i64);
);
let base_log = format!(
"[METRIC] BLOCK EXECUTION THROUGHPUT ({}): {:.3} Ggas/s TIME SPENT: {:.0} ms. Gas Used: {:.3} ({:.0}%), #Txs: {}.",
block_number,
throughput,
interval,
as_gigas,
(gas_used as f64 / gas_limit as f64) * 100.0,
transactions_count
);
fn percentage(init: Instant, end: Instant, total: f64) -> f64 {
(end.duration_since(init).as_millis() as f64 / total * 100.0).round()
}
let extra_log = if as_gigas > 0.0 {
format!(
" exec: {}% merkle: {}% store: {}%",
percentage(since, executed, interval),
percentage(executed, merkleized, interval),
percentage(merkleized, stored, interval)
)
} else {
"".to_string()
};
info!("{}{}", base_log, extra_log);
}
}
#[allow(clippy::too_many_arguments)]
fn print_add_block_pipeline_logs(
gas_used: u64,
gas_limit: u64,
block_number: u64,
transactions_count: usize,
merkle_queue_length: usize,
[
start_instant,
block_validated_instant,
exec_merkle_start,
exec_end_instant,
merkle_end_instant,
exec_merkle_end_instant,
stored_instant,
]: [Instant; 7],
) {
let interval = stored_instant.duration_since(start_instant).as_secs_f64();
if interval != 0f64 {
let as_gigas = gas_used as f64 * 1e-9;
let throughput = as_gigas / interval;
metrics!(
METRICS_BLOCKS.set_block_number(block_number);
METRICS_BLOCKS.set_latest_gas_used(gas_used as f64);
METRICS_BLOCKS.set_latest_block_gas_limit(gas_limit as f64);
METRICS_BLOCKS.set_latest_gigagas(throughput);
METRICS_BLOCKS.set_transaction_count(transactions_count as i64);
);
let base_log = format!(
"[METRIC] BLOCK EXECUTION THROUGHPUT ({}): {:.3} Ggas/s TIME SPENT: {:.0} ms. Gas Used: {:.3} ({:.0}%), #Txs: {}.",
block_number,
throughput,
interval * 1000.0,
as_gigas,
(gas_used as f64 / gas_limit as f64) * 100.0,
transactions_count
);
let percentage = move |init: Instant, end: Instant| {
(end.duration_since(init).as_secs_f64() / interval * 100.0).round()
};
let extra_log = if as_gigas > 0.0 {
format!(
" block validation: {}% exec+merkle: {}% (exec: {}% merkle: {}% max_queue_length: {merkle_queue_length}) store: {}%",
percentage(start_instant, block_validated_instant),
percentage(exec_merkle_start, exec_merkle_end_instant),
percentage(exec_merkle_start, exec_end_instant),
percentage(exec_merkle_start, merkle_end_instant),
percentage(merkle_end_instant, stored_instant),
)
} else {
"".to_string()
};
info!("{}{}", base_log, extra_log);
}
}
/// Adds multiple blocks in a batch.
///
/// If an error occurs, returns a tuple containing:
/// - The error type ([`ChainError`]).
/// - [`BatchProcessingFailure`] (if the error was caused by block processing).
///
/// Note: only the last block's state trie is stored in the db
pub async fn add_blocks_in_batch(
&self,
blocks: Vec<Block>,
cancellation_token: CancellationToken,
) -> Result<(), (ChainError, Option<BatchBlockProcessingFailure>)> {