forked from lambdaclass/era-test-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.rs
4699 lines (4235 loc) · 174 KB
/
node.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
//! In-memory node, that supports forking other networks.
use crate::{
bootloader_debug::{BootloaderDebug, BootloaderDebugTracer},
console_log::ConsoleLogHandler,
deps::InMemoryStorage,
filters::{EthFilters, FilterType, LogFilter},
fork::{ForkDetails, ForkSource, ForkStorage},
formatter,
observability::Observability,
system_contracts::{self, Options, SystemContracts},
utils::{
self, adjust_l1_gas_price_for_tx, bytecode_to_factory_dep, create_debug_output,
not_implemented, to_human_size, IntoBoxedFuture,
},
};
use clap::Parser;
use colored::Colorize;
use core::fmt::Display;
use futures::FutureExt;
use indexmap::IndexMap;
use itertools::Itertools;
use jsonrpc_core::BoxFuture;
use once_cell::sync::OnceCell;
use std::{
cmp::{self},
collections::{HashMap, HashSet},
str::FromStr,
sync::{Arc, RwLock},
};
use multivm::interface::{
ExecutionResult, L1BatchEnv, L2BlockEnv, SystemEnv, TxExecutionMode, VmExecutionMode,
VmExecutionResultAndLogs,
};
use multivm::vm_virtual_blocks::{
constants::{
BLOCK_GAS_LIMIT, BLOCK_OVERHEAD_PUBDATA, ETH_CALL_GAS_LIMIT, MAX_PUBDATA_PER_BLOCK,
},
utils::{
fee::derive_base_fee_and_gas_per_pubdata,
l2_blocks::load_last_l2_block,
overhead::{derive_overhead, OverheadCoeficients},
},
CallTracer, HistoryDisabled, Vm, VmTracer,
};
use zksync_basic_types::{
web3::{self, signing::keccak256},
AccountTreeId, Address, Bytes, L1BatchNumber, MiniblockNumber, H160, H256, U256, U64,
};
use zksync_contracts::BaseSystemContracts;
use zksync_core::api_server::web3::backend_jsonrpc::{
error::into_jsrpc_error, namespaces::eth::EthNamespaceT,
};
use zksync_state::{ReadStorage, StoragePtr, StorageView, WriteStorage};
use zksync_types::{
api::{Block, DebugCall, Log, TransactionReceipt, TransactionVariant},
block::legacy_miniblock_hash,
fee::Fee,
get_code_key, get_nonce_key,
l2::L2Tx,
l2::TransactionType,
transaction_request::TransactionRequest,
utils::{
decompose_full_nonce, nonces_to_full_nonce, storage_key_for_eth_balance,
storage_key_for_standard_token_balance,
},
vm_trace::Call,
PackedEthSignature, StorageKey, StorageLogQueryType, StorageValue, Transaction,
ACCOUNT_CODE_STORAGE_ADDRESS, EIP_712_TX_TYPE, L2_ETH_TOKEN_ADDRESS, MAX_GAS_PER_PUBDATA_BYTE,
MAX_L2_TX_GAS_LIMIT,
};
use zksync_utils::{
bytecode::{compress_bytecode, hash_bytecode},
h256_to_account_address, h256_to_u256, h256_to_u64, u256_to_h256,
};
use zksync_web3_decl::{
error::Web3Error,
types::{FeeHistory, Filter, FilterChanges},
};
/// Max possible size of an ABI encoded tx (in bytes).
pub const MAX_TX_SIZE: usize = 1_000_000;
/// Timestamp of the first block (if not running in fork mode).
pub const NON_FORK_FIRST_BLOCK_TIMESTAMP: u64 = 1_000;
/// Network ID we use for the test node.
pub const TEST_NODE_NETWORK_ID: u32 = 260;
/// L1 Gas Price.
pub const L1_GAS_PRICE: u64 = 50_000_000_000;
/// L2 Gas Price (0.25 gwei).
pub const L2_GAS_PRICE: u64 = 250_000_000;
/// L1 Gas Price Scale Factor for gas estimation.
pub const ESTIMATE_GAS_L1_GAS_PRICE_SCALE_FACTOR: f64 = 1.2;
/// The max possible number of gas that `eth_estimateGas` is allowed to overestimate.
pub const ESTIMATE_GAS_PUBLISH_BYTE_OVERHEAD: u32 = 100;
/// Acceptable gas overestimation limit.
pub const ESTIMATE_GAS_ACCEPTABLE_OVERESTIMATION: u32 = 1_000;
/// The factor by which to scale the gasLimit.
pub const ESTIMATE_GAS_SCALE_FACTOR: f32 = 1.3;
/// The maximum number of previous blocks to store the state for.
pub const MAX_PREVIOUS_STATES: u16 = 128;
/// The zks protocol version.
pub const PROTOCOL_VERSION: &str = "zks/1";
pub fn compute_hash(block_number: u64, tx_hash: H256) -> H256 {
let digest = [&block_number.to_be_bytes()[..], tx_hash.as_bytes()].concat();
H256(keccak256(&digest))
}
pub fn create_empty_block<TX>(block_number: u64, timestamp: u64, batch: u32) -> Block<TX> {
let hash = compute_hash(block_number, H256::zero());
Block {
hash,
number: U64::from(block_number),
timestamp: U256::from(timestamp),
l1_batch_number: Some(U64::from(batch)),
transactions: vec![],
gas_used: U256::from(0),
gas_limit: U256::from(BLOCK_GAS_LIMIT),
..Default::default()
}
}
/// Information about the executed transaction.
#[derive(Debug, Clone)]
pub struct TxExecutionInfo {
pub tx: L2Tx,
// Batch number where transaction was executed.
pub batch_number: u32,
pub miniblock_number: u64,
pub result: VmExecutionResultAndLogs,
}
#[derive(Debug, Default, clap::Parser, Clone, clap::ValueEnum, PartialEq, Eq)]
pub enum ShowCalls {
#[default]
None,
User,
System,
All,
}
impl FromStr for ShowCalls {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_ref() {
"none" => Ok(ShowCalls::None),
"user" => Ok(ShowCalls::User),
"system" => Ok(ShowCalls::System),
"all" => Ok(ShowCalls::All),
_ => Err(format!(
"Unknown ShowCalls value {} - expected one of none|user|system|all.",
s
)),
}
}
}
impl Display for ShowCalls {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "{:?}", self)
}
}
#[derive(Debug, Default, Parser, Clone, clap::ValueEnum, PartialEq, Eq)]
pub enum ShowStorageLogs {
#[default]
None,
Read,
Write,
All,
}
impl FromStr for ShowStorageLogs {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_ref() {
"none" => Ok(ShowStorageLogs::None),
"read" => Ok(ShowStorageLogs::Read),
"write" => Ok(ShowStorageLogs::Write),
"all" => Ok(ShowStorageLogs::All),
_ => Err(format!(
"Unknown ShowStorageLogs value {} - expected one of none|read|write|all.",
s
)),
}
}
}
impl Display for ShowStorageLogs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "{:?}", self)
}
}
#[derive(Debug, Default, Parser, Clone, clap::ValueEnum, PartialEq, Eq)]
pub enum ShowVMDetails {
#[default]
None,
All,
}
impl FromStr for ShowVMDetails {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_ref() {
"none" => Ok(ShowVMDetails::None),
"all" => Ok(ShowVMDetails::All),
_ => Err(format!(
"Unknown ShowVMDetails value {} - expected one of none|all.",
s
)),
}
}
}
impl Display for ShowVMDetails {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "{:?}", self)
}
}
#[derive(Debug, Default, Parser, Clone, clap::ValueEnum, PartialEq, Eq)]
pub enum ShowGasDetails {
#[default]
None,
All,
}
impl FromStr for ShowGasDetails {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_ref() {
"none" => Ok(ShowGasDetails::None),
"all" => Ok(ShowGasDetails::All),
_ => Err(format!(
"Unknown ShowGasDetails value {} - expected one of none|all.",
s
)),
}
}
}
impl Display for ShowGasDetails {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "{:?}", self)
}
}
#[derive(Debug, Clone)]
pub struct TransactionResult {
pub info: TxExecutionInfo,
pub receipt: TransactionReceipt,
pub debug: DebugCall,
}
impl TransactionResult {
/// Returns the debug information for the transaction.
/// If `only_top` is true - will only return the top level call.
pub fn debug_info(&self, only_top: bool) -> DebugCall {
let calls = if only_top {
vec![]
} else {
self.debug.calls.clone()
};
DebugCall {
calls,
..self.debug.clone()
}
}
}
/// Helper struct for InMemoryNode.
/// S - is the Source of the Fork.
#[derive(Clone)]
pub struct InMemoryNodeInner<S> {
/// The latest timestamp that was already generated.
/// Next block will be current_timestamp + 1
pub current_timestamp: u64,
/// The latest batch number that was already generated.
/// Next block will be current_batch + 1
pub current_batch: u32,
/// The latest miniblock number that was already generated.
/// Next transaction will go to the block current_miniblock + 1
pub current_miniblock: u64,
/// The latest miniblock hash.
pub current_miniblock_hash: H256,
pub l1_gas_price: u64,
// Map from transaction to details about the exeuction
pub tx_results: HashMap<H256, TransactionResult>,
// Map from block hash to information about the block.
pub blocks: HashMap<H256, Block<TransactionVariant>>,
// Map from block number to a block hash.
pub block_hashes: HashMap<u64, H256>,
// Map from filter_id to the eth filter
pub filters: EthFilters,
// Underlying storage
pub fork_storage: ForkStorage<S>,
// Debug level information.
pub show_calls: ShowCalls,
// Displays storage logs.
pub show_storage_logs: ShowStorageLogs,
// Displays VM details.
pub show_vm_details: ShowVMDetails,
// Gas details information.
pub show_gas_details: ShowGasDetails,
// If true - will contact openchain to resolve the ABI to function names.
pub resolve_hashes: bool,
pub console_log_handler: ConsoleLogHandler,
pub system_contracts: SystemContracts,
pub impersonated_accounts: HashSet<Address>,
pub rich_accounts: HashSet<H160>,
/// Keeps track of historical states indexed via block hash. Limited to [MAX_PREVIOUS_STATES].
pub previous_states: IndexMap<H256, HashMap<StorageKey, StorageValue>>,
/// An optional handle to the observability stack
pub observability: Option<Observability>,
}
type L2TxResult = (
HashMap<StorageKey, H256>,
VmExecutionResultAndLogs,
Vec<Call>,
Block<TransactionVariant>,
HashMap<U256, Vec<U256>>,
BlockContext,
);
impl<S: std::fmt::Debug + ForkSource> InMemoryNodeInner<S> {
pub fn create_l1_batch_env<ST: ReadStorage>(
&self,
storage: StoragePtr<ST>,
) -> (L1BatchEnv, BlockContext) {
let last_l2_block_hash = if let Some(last_l2_block) = load_last_l2_block(storage) {
last_l2_block.hash
} else {
// This is the scenario of either the first L2 block ever or
// the first block after the upgrade for support of L2 blocks.
legacy_miniblock_hash(MiniblockNumber(self.current_miniblock as u32))
};
let block_ctx = BlockContext::from_current(
self.current_batch,
self.current_miniblock,
self.current_timestamp,
);
let block_ctx = block_ctx.new_batch();
let batch_env = L1BatchEnv {
// TODO: set the previous batch hash properly (take from fork, when forking, and from local storage, when this is not the first block).
previous_batch_hash: None,
number: L1BatchNumber::from(block_ctx.batch),
timestamp: block_ctx.timestamp,
l1_gas_price: self.l1_gas_price,
fair_l2_gas_price: L2_GAS_PRICE,
fee_account: H160::zero(),
enforced_base_fee: None,
first_l2_block: L2BlockEnv {
// the 'current_miniblock' contains the block that was already produced.
// So the next one should be one higher.
number: block_ctx.miniblock as u32,
timestamp: block_ctx.timestamp,
prev_block_hash: last_l2_block_hash,
// This is only used during zksyncEra block timestamp/number transition.
// In case of starting a new network, it doesn't matter.
// In theory , when forking mainnet, we should match this value
// to the value that was set in the node at that time - but AFAIK
// we don't have any API for this - so this might result in slightly
// incorrect replays of transacions during the migration period, that
// depend on block number or timestamp.
max_virtual_blocks_to_create: 1,
},
};
(batch_env, block_ctx)
}
pub fn create_system_env(
&self,
base_system_contracts: BaseSystemContracts,
execution_mode: TxExecutionMode,
) -> SystemEnv {
SystemEnv {
zk_porter_available: false,
// TODO: when forking, we could consider taking the protocol version id from the fork itself.
version: zksync_types::ProtocolVersionId::latest(),
base_system_smart_contracts: base_system_contracts,
gas_limit: BLOCK_GAS_LIMIT,
execution_mode,
default_validation_computational_gas_limit: BLOCK_GAS_LIMIT,
chain_id: self.fork_storage.chain_id,
}
}
/// Estimates the gas required for a given call request.
///
/// # Arguments
///
/// * `req` - A `CallRequest` struct representing the call request to estimate gas for.
///
/// # Returns
///
/// A `Result` with a `Fee` representing the estimated gas related data.
pub fn estimate_gas_impl(
&self,
req: zksync_types::transaction_request::CallRequest,
) -> jsonrpc_core::Result<Fee> {
let mut request_with_gas_per_pubdata_overridden = req;
if let Some(ref mut eip712_meta) = request_with_gas_per_pubdata_overridden.eip712_meta {
if eip712_meta.gas_per_pubdata == U256::zero() {
eip712_meta.gas_per_pubdata = MAX_GAS_PER_PUBDATA_BYTE.into();
}
}
let is_eip712 = request_with_gas_per_pubdata_overridden
.eip712_meta
.is_some();
let mut l2_tx =
match L2Tx::from_request(request_with_gas_per_pubdata_overridden.into(), MAX_TX_SIZE) {
Ok(tx) => tx,
Err(e) => {
let error = Web3Error::SerializationError(e);
return Err(into_jsrpc_error(error));
}
};
let tx: Transaction = l2_tx.clone().into();
let fair_l2_gas_price = L2_GAS_PRICE;
// Calculate Adjusted L1 Price
let l1_gas_price = {
let current_l1_gas_price =
((self.l1_gas_price as f64) * ESTIMATE_GAS_L1_GAS_PRICE_SCALE_FACTOR) as u64;
// In order for execution to pass smoothly, we need to ensure that block's required gasPerPubdata will be
// <= to the one in the transaction itself.
adjust_l1_gas_price_for_tx(
current_l1_gas_price,
L2_GAS_PRICE,
tx.gas_per_pubdata_byte_limit(),
)
};
let (base_fee, gas_per_pubdata_byte) =
derive_base_fee_and_gas_per_pubdata(l1_gas_price, fair_l2_gas_price);
// Properly format signature
if l2_tx.common_data.signature.is_empty() {
l2_tx.common_data.signature = vec![0u8; 65];
l2_tx.common_data.signature[64] = 27;
}
// The user may not include the proper transaction type during the estimation of
// the gas fee. However, it is needed for the bootloader checks to pass properly.
if is_eip712 {
l2_tx.common_data.transaction_type = TransactionType::EIP712Transaction;
}
l2_tx.common_data.fee.gas_per_pubdata_limit = MAX_GAS_PER_PUBDATA_BYTE.into();
l2_tx.common_data.fee.max_fee_per_gas = base_fee.into();
l2_tx.common_data.fee.max_priority_fee_per_gas = base_fee.into();
let mut storage_view = StorageView::new(&self.fork_storage);
// Calculate gas_for_bytecodes_pubdata
let pubdata_for_factory_deps = l2_tx
.execute
.factory_deps
.as_deref()
.unwrap_or_default()
.iter()
.map(|bytecode| {
if storage_view.is_bytecode_known(&hash_bytecode(bytecode)) {
return 0;
}
let length = if let Ok(compressed) = compress_bytecode(bytecode) {
compressed.len()
} else {
bytecode.len()
};
length as u32 + ESTIMATE_GAS_PUBLISH_BYTE_OVERHEAD
})
.sum::<u32>();
if pubdata_for_factory_deps > MAX_PUBDATA_PER_BLOCK {
return Err(into_jsrpc_error(Web3Error::SubmitTransactionError(
"exceeds limit for published pubdata".into(),
Default::default(),
)));
}
let gas_for_bytecodes_pubdata: u32 =
pubdata_for_factory_deps * (gas_per_pubdata_byte as u32);
let storage = storage_view.to_rc_ptr();
let execution_mode = TxExecutionMode::EstimateFee;
let (mut batch_env, _) = self.create_l1_batch_env(storage.clone());
batch_env.l1_gas_price = l1_gas_price;
let system_env = self.create_system_env(
self.system_contracts.contracts_for_fee_estimate().clone(),
execution_mode,
);
// We are using binary search to find the minimal values of gas_limit under which the transaction succeeds
let mut lower_bound = 0;
let mut upper_bound = MAX_L2_TX_GAS_LIMIT as u32;
let mut attempt_count = 1;
tracing::trace!("Starting gas estimation loop");
while lower_bound + ESTIMATE_GAS_ACCEPTABLE_OVERESTIMATION < upper_bound {
let mid = (lower_bound + upper_bound) / 2;
tracing::trace!(
"Attempt {} (lower_bound: {}, upper_bound: {}, mid: {})",
attempt_count,
lower_bound,
upper_bound,
mid
);
let try_gas_limit = gas_for_bytecodes_pubdata + mid;
let estimate_gas_result = InMemoryNodeInner::estimate_gas_step(
l2_tx.clone(),
gas_per_pubdata_byte,
try_gas_limit,
l1_gas_price,
batch_env.clone(),
system_env.clone(),
&self.fork_storage,
);
if estimate_gas_result.result.is_failed() {
tracing::trace!("Attempt {} FAILED", attempt_count);
lower_bound = mid + 1;
} else {
tracing::trace!("Attempt {} SUCCEEDED", attempt_count);
upper_bound = mid;
}
attempt_count += 1;
}
tracing::trace!("Gas Estimation Values:");
tracing::trace!(" Final upper_bound: {}", upper_bound);
tracing::trace!(" ESTIMATE_GAS_SCALE_FACTOR: {}", ESTIMATE_GAS_SCALE_FACTOR);
tracing::trace!(" MAX_L2_TX_GAS_LIMIT: {}", MAX_L2_TX_GAS_LIMIT);
let tx_body_gas_limit = cmp::min(
MAX_L2_TX_GAS_LIMIT as u32,
(upper_bound as f32 * ESTIMATE_GAS_SCALE_FACTOR) as u32,
);
let suggested_gas_limit = tx_body_gas_limit + gas_for_bytecodes_pubdata;
let estimate_gas_result = InMemoryNodeInner::estimate_gas_step(
l2_tx.clone(),
gas_per_pubdata_byte,
suggested_gas_limit,
l1_gas_price,
batch_env,
system_env,
&self.fork_storage,
);
let coefficients = OverheadCoeficients::from_tx_type(EIP_712_TX_TYPE);
let overhead: u32 = derive_overhead(
suggested_gas_limit,
gas_per_pubdata_byte as u32,
tx.encoding_len(),
coefficients,
);
match estimate_gas_result.result {
ExecutionResult::Revert { output } => {
tracing::info!("{}", format!("Unable to estimate gas for the request with our suggested gas limit of {}. The transaction is most likely unexecutable. Breakdown of estimation:", suggested_gas_limit + overhead).red());
tracing::info!(
"{}",
format!(
"\tEstimated transaction body gas cost: {}",
tx_body_gas_limit
)
.red()
);
tracing::info!(
"{}",
format!("\tGas for pubdata: {}", gas_for_bytecodes_pubdata).red()
);
tracing::info!("{}", format!("\tOverhead: {}", overhead).red());
let message = output.to_string();
let pretty_message = format!(
"execution reverted{}{}",
if message.is_empty() { "" } else { ": " },
message
);
let data = output.encoded_data();
tracing::info!("{}", pretty_message.on_red());
Err(into_jsrpc_error(Web3Error::SubmitTransactionError(
pretty_message,
data,
)))
}
ExecutionResult::Halt { reason } => {
tracing::info!("{}", format!("Unable to estimate gas for the request with our suggested gas limit of {}. The transaction is most likely unexecutable. Breakdown of estimation:", suggested_gas_limit + overhead).red());
tracing::info!(
"{}",
format!(
"\tEstimated transaction body gas cost: {}",
tx_body_gas_limit
)
.red()
);
tracing::info!(
"{}",
format!("\tGas for pubdata: {}", gas_for_bytecodes_pubdata).red()
);
tracing::info!("{}", format!("\tOverhead: {}", overhead).red());
let message = reason.to_string();
let pretty_message = format!(
"execution reverted{}{}",
if message.is_empty() { "" } else { ": " },
message
);
tracing::info!("{}", pretty_message.on_red());
Err(into_jsrpc_error(Web3Error::SubmitTransactionError(
pretty_message,
vec![],
)))
}
ExecutionResult::Success { .. } => {
let full_gas_limit = match tx_body_gas_limit
.overflowing_add(gas_for_bytecodes_pubdata + overhead)
{
(value, false) => value,
(_, true) => {
tracing::info!("{}", "Overflow when calculating gas estimation. We've exceeded the block gas limit by summing the following values:".red());
tracing::info!(
"{}",
format!(
"\tEstimated transaction body gas cost: {}",
tx_body_gas_limit
)
.red()
);
tracing::info!(
"{}",
format!("\tGas for pubdata: {}", gas_for_bytecodes_pubdata).red()
);
tracing::info!("{}", format!("\tOverhead: {}", overhead).red());
return Err(into_jsrpc_error(Web3Error::SubmitTransactionError(
"exceeds block gas limit".into(),
Default::default(),
)));
}
};
tracing::trace!("Gas Estimation Results");
tracing::trace!(" tx_body_gas_limit: {}", tx_body_gas_limit);
tracing::trace!(" gas_for_bytecodes_pubdata: {}", gas_for_bytecodes_pubdata);
tracing::trace!(" overhead: {}", overhead);
tracing::trace!(" full_gas_limit: {}", full_gas_limit);
let fee = Fee {
max_fee_per_gas: base_fee.into(),
max_priority_fee_per_gas: 0u32.into(),
gas_limit: full_gas_limit.into(),
gas_per_pubdata_limit: gas_per_pubdata_byte.into(),
};
Ok(fee)
}
}
}
/// Runs fee estimation against a sandbox vm with the given gas_limit.
#[allow(clippy::too_many_arguments)]
fn estimate_gas_step(
mut l2_tx: L2Tx,
gas_per_pubdata_byte: u64,
tx_gas_limit: u32,
l1_gas_price: u64,
mut batch_env: L1BatchEnv,
system_env: SystemEnv,
fork_storage: &ForkStorage<S>,
) -> VmExecutionResultAndLogs {
let tx: Transaction = l2_tx.clone().into();
let l1_gas_price =
adjust_l1_gas_price_for_tx(l1_gas_price, L2_GAS_PRICE, tx.gas_per_pubdata_byte_limit());
let coefficients = OverheadCoeficients::from_tx_type(EIP_712_TX_TYPE);
// Set gas_limit for transaction
let gas_limit_with_overhead = tx_gas_limit
+ derive_overhead(
tx_gas_limit,
gas_per_pubdata_byte as u32,
tx.encoding_len(),
coefficients,
);
l2_tx.common_data.fee.gas_limit = gas_limit_with_overhead.into();
let storage = StorageView::new(fork_storage).to_rc_ptr();
// The nonce needs to be updated
let nonce = l2_tx.nonce();
let nonce_key = get_nonce_key(&l2_tx.initiator_account());
let full_nonce = storage.borrow_mut().read_value(&nonce_key);
let (_, deployment_nonce) = decompose_full_nonce(h256_to_u256(full_nonce));
let enforced_full_nonce = nonces_to_full_nonce(U256::from(nonce.0), deployment_nonce);
storage
.borrow_mut()
.set_value(nonce_key, u256_to_h256(enforced_full_nonce));
// We need to explicitly put enough balance into the account of the users
let payer = l2_tx.payer();
let balance_key = storage_key_for_eth_balance(&payer);
let mut current_balance = h256_to_u256(storage.borrow_mut().read_value(&balance_key));
let added_balance = l2_tx.common_data.fee.gas_limit * l2_tx.common_data.fee.max_fee_per_gas;
current_balance += added_balance;
storage
.borrow_mut()
.set_value(balance_key, u256_to_h256(current_balance));
batch_env.l1_gas_price = l1_gas_price;
let mut vm = Vm::new(batch_env, system_env, storage, HistoryDisabled);
let tx: Transaction = l2_tx.into();
vm.push_transaction(tx);
vm.execute(VmExecutionMode::OneTx)
}
/// Sets the `impersonated_account` field of the node.
/// This field is used to override the `tx.initiator_account` field of the transaction in the `run_l2_tx` method.
pub fn set_impersonated_account(&mut self, address: Address) -> bool {
self.impersonated_accounts.insert(address)
}
/// Clears the `impersonated_account` field of the node.
pub fn stop_impersonating_account(&mut self, address: Address) -> bool {
self.impersonated_accounts.remove(&address)
}
/// Archives the current state for later queries.
pub fn archive_state(&mut self) -> Result<(), String> {
if self.previous_states.len() > MAX_PREVIOUS_STATES as usize {
if let Some(entry) = self.previous_states.shift_remove_index(0) {
tracing::debug!("removing archived state for previous block {:#x}", entry.0);
}
}
tracing::debug!(
"archiving state for {:#x} #{}",
self.current_miniblock_hash,
self.current_miniblock
);
self.previous_states.insert(
self.current_miniblock_hash,
self.fork_storage
.inner
.read()
.map_err(|err| err.to_string())?
.raw_storage
.state
.clone(),
);
Ok(())
}
/// Creates a [Snapshot] of the current state of the node.
pub fn snapshot(&self) -> Result<Snapshot, String> {
let storage = self
.fork_storage
.inner
.read()
.map_err(|err| format!("failed acquiring read lock on storage: {:?}", err))?;
Ok(Snapshot {
current_timestamp: self.current_timestamp,
current_batch: self.current_batch,
current_miniblock: self.current_miniblock,
current_miniblock_hash: self.current_miniblock_hash,
l1_gas_price: self.l1_gas_price,
tx_results: self.tx_results.clone(),
blocks: self.blocks.clone(),
block_hashes: self.block_hashes.clone(),
filters: self.filters.clone(),
impersonated_accounts: self.impersonated_accounts.clone(),
rich_accounts: self.rich_accounts.clone(),
previous_states: self.previous_states.clone(),
raw_storage: storage.raw_storage.clone(),
value_read_cache: storage.value_read_cache.clone(),
factory_dep_cache: storage.factory_dep_cache.clone(),
})
}
/// Restores a previously created [Snapshot] of the node.
pub fn restore_snapshot(&mut self, snapshot: Snapshot) -> Result<(), String> {
let mut storage = self
.fork_storage
.inner
.write()
.map_err(|err| format!("failed acquiring write lock on storage: {:?}", err))?;
self.current_timestamp = snapshot.current_timestamp;
self.current_batch = snapshot.current_batch;
self.current_miniblock = snapshot.current_miniblock;
self.current_miniblock_hash = snapshot.current_miniblock_hash;
self.l1_gas_price = snapshot.l1_gas_price;
self.tx_results = snapshot.tx_results;
self.blocks = snapshot.blocks;
self.block_hashes = snapshot.block_hashes;
self.filters = snapshot.filters;
self.impersonated_accounts = snapshot.impersonated_accounts;
self.rich_accounts = snapshot.rich_accounts;
self.previous_states = snapshot.previous_states;
storage.raw_storage = snapshot.raw_storage;
storage.value_read_cache = snapshot.value_read_cache;
storage.factory_dep_cache = snapshot.factory_dep_cache;
Ok(())
}
}
/// Creates a restorable snapshot for the [InMemoryNodeInner]. The snapshot contains all the necessary
/// data required to restore the [InMemoryNodeInner] state to a previous point in time.
#[derive(Debug, Clone)]
pub struct Snapshot {
pub(crate) current_timestamp: u64,
pub(crate) current_batch: u32,
pub(crate) current_miniblock: u64,
pub(crate) current_miniblock_hash: H256,
pub(crate) l1_gas_price: u64,
pub(crate) tx_results: HashMap<H256, TransactionResult>,
pub(crate) blocks: HashMap<H256, Block<TransactionVariant>>,
pub(crate) block_hashes: HashMap<u64, H256>,
pub(crate) filters: EthFilters,
pub(crate) impersonated_accounts: HashSet<Address>,
pub(crate) rich_accounts: HashSet<H160>,
pub(crate) previous_states: IndexMap<H256, HashMap<StorageKey, StorageValue>>,
pub(crate) raw_storage: InMemoryStorage,
pub(crate) value_read_cache: HashMap<StorageKey, H256>,
pub(crate) factory_dep_cache: HashMap<H256, Option<Vec<u8>>>,
}
/// Defines the configuration parameters for the [InMemoryNode].
#[derive(Default, Debug, Clone)]
pub struct InMemoryNodeConfig {
pub show_calls: ShowCalls,
pub show_storage_logs: ShowStorageLogs,
pub show_vm_details: ShowVMDetails,
pub show_gas_details: ShowGasDetails,
pub resolve_hashes: bool,
pub system_contracts_options: system_contracts::Options,
}
/// In-memory node, that can be used for local & unit testing.
/// It also supports the option of forking testnet/mainnet.
/// All contents are removed when object is destroyed.
pub struct InMemoryNode<S> {
inner: Arc<RwLock<InMemoryNodeInner<S>>>,
}
fn contract_address_from_tx_result(execution_result: &VmExecutionResultAndLogs) -> Option<H160> {
for query in execution_result.logs.storage_logs.iter().rev() {
if query.log_type == StorageLogQueryType::InitialWrite
&& query.log_query.address == ACCOUNT_CODE_STORAGE_ADDRESS
{
return Some(h256_to_account_address(&u256_to_h256(query.log_query.key)));
}
}
None
}
impl<S: ForkSource + std::fmt::Debug> Default for InMemoryNode<S> {
fn default() -> Self {
InMemoryNode::new(None, None, InMemoryNodeConfig::default())
}
}
impl<S: ForkSource + std::fmt::Debug> InMemoryNode<S> {
pub fn new(
fork: Option<ForkDetails<S>>,
observability: Option<Observability>,
config: InMemoryNodeConfig,
) -> Self {
let inner = if let Some(f) = &fork {
let mut block_hashes = HashMap::<u64, H256>::new();
block_hashes.insert(f.l2_block.number.as_u64(), f.l2_block.hash);
let mut blocks = HashMap::<H256, Block<TransactionVariant>>::new();
blocks.insert(f.l2_block.hash, f.l2_block.clone());
InMemoryNodeInner {
current_timestamp: f.block_timestamp,
current_batch: f.l1_block.0,
current_miniblock: f.l2_miniblock,
current_miniblock_hash: f.l2_miniblock_hash,
l1_gas_price: f.l1_gas_price,
tx_results: Default::default(),
blocks,
block_hashes,
filters: Default::default(),
fork_storage: ForkStorage::new(fork, &config.system_contracts_options),
show_calls: config.show_calls,
show_storage_logs: config.show_storage_logs,
show_vm_details: config.show_vm_details,
show_gas_details: config.show_gas_details,
resolve_hashes: config.resolve_hashes,
console_log_handler: ConsoleLogHandler::default(),
system_contracts: SystemContracts::from_options(&config.system_contracts_options),
impersonated_accounts: Default::default(),
rich_accounts: HashSet::new(),
previous_states: Default::default(),
observability,
}
} else {
let mut block_hashes = HashMap::<u64, H256>::new();
block_hashes.insert(0, H256::zero());
let mut blocks = HashMap::<H256, Block<TransactionVariant>>::new();
blocks.insert(
H256::zero(),
create_empty_block(0, NON_FORK_FIRST_BLOCK_TIMESTAMP, 0),
);
InMemoryNodeInner {
current_timestamp: NON_FORK_FIRST_BLOCK_TIMESTAMP,
current_batch: 0,
current_miniblock: 0,
current_miniblock_hash: H256::zero(),
l1_gas_price: L1_GAS_PRICE,
tx_results: Default::default(),
blocks,
block_hashes,
filters: Default::default(),
fork_storage: ForkStorage::new(fork, &config.system_contracts_options),
show_calls: config.show_calls,
show_storage_logs: config.show_storage_logs,
show_vm_details: config.show_vm_details,
show_gas_details: config.show_gas_details,
resolve_hashes: config.resolve_hashes,
console_log_handler: ConsoleLogHandler::default(),
system_contracts: SystemContracts::from_options(&config.system_contracts_options),
impersonated_accounts: Default::default(),
rich_accounts: HashSet::new(),
previous_states: Default::default(),
observability,
}
};
InMemoryNode {
inner: Arc::new(RwLock::new(inner)),
}
}
pub fn get_inner(&self) -> Arc<RwLock<InMemoryNodeInner<S>>> {
self.inner.clone()
}
/// Applies multiple transactions - but still one per L1 batch.
pub fn apply_txs(&self, txs: Vec<L2Tx>) -> Result<(), String> {
tracing::info!("Running {:?} transactions (one per batch)", txs.len());
for tx in txs {
self.run_l2_tx(tx, TxExecutionMode::VerifyExecute)?;
}
Ok(())
}
/// Adds a lot of tokens to a given account.
pub fn set_rich_account(&self, address: H160) {
let key = storage_key_for_eth_balance(&address);
let mut inner = match self.inner.write() {
Ok(guard) => guard,
Err(e) => {
tracing::info!("Failed to acquire write lock: {}", e);
return;
}
};
let keys = {
let mut storage_view = StorageView::new(&inner.fork_storage);
storage_view.set_value(key, u256_to_h256(U256::from(10u128.pow(30))));
storage_view.modified_storage_keys().clone()
};
for (key, value) in keys.iter() {
inner.fork_storage.set_value(*key, *value);
}
inner.rich_accounts.insert(address);
}
/// Runs L2 'eth call' method - that doesn't commit to a block.
fn run_l2_call(&self, mut l2_tx: L2Tx) -> Result<ExecutionResult, String> {
let execution_mode = TxExecutionMode::EthCall;
let inner = self
.inner
.write()
.map_err(|e| format!("Failed to acquire write lock: {}", e))?;