-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.rs
More file actions
1619 lines (1418 loc) · 50.7 KB
/
cli.rs
File metadata and controls
1619 lines (1418 loc) · 50.7 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
#[cfg(not(feature = "l2"))]
use crate::helpers::get_block_numbers_in_cache_dir;
use crate::helpers::get_trie_nodes_with_dummies;
use bytes::Bytes;
use ethrex_l2_common::prover::ProofFormat;
use ethrex_l2_rpc::signer::{LocalSigner, Signer};
use ethrex_rlp::decode::RLPDecode;
use ethrex_trie::{EMPTY_TRIE_HASH, InMemoryTrieDB, Node};
use eyre::OptionExt;
use std::{
cmp::max,
collections::BTreeMap,
fmt::Display,
path::PathBuf,
sync::Arc,
time::{Duration, Instant},
};
use clap::{ArgGroup, Parser, Subcommand, ValueEnum};
use ethrex_blockchain::{
Blockchain,
fork_choice::apply_fork_choice,
payload::{BuildPayloadArgs, PayloadBuildResult, create_payload},
};
use ethrex_common::{
Address, H256,
types::{
AccountState, AccountUpdate, Block, Code, DEFAULT_BUILDER_GAS_CEIL, ELASTICITY_MULTIPLIER,
Receipt, block_execution_witness::GuestProgramState,
},
utils::keccak,
};
use ethrex_prover::backend::Backend;
#[cfg(not(feature = "l2"))]
use ethrex_rpc::types::block_identifier::BlockIdentifier;
use ethrex_rpc::{
EthClient,
debug::execution_witness::{RpcExecutionWitness, execution_witness_from_rpc_chain_config},
};
use ethrex_storage::hash_address;
use ethrex_storage::{EngineType, Store};
#[cfg(feature = "l2")]
use ethrex_storage_rollup::EngineTypeRollup;
use reqwest::Url;
#[cfg(feature = "l2")]
use std::path::Path;
#[cfg(not(feature = "l2"))]
use tracing::debug;
use tracing::info;
#[cfg(feature = "l2")]
use crate::fetcher::get_batchdata;
#[cfg(not(feature = "l2"))]
use crate::plot_composition::plot;
use crate::{cache::Cache, fetcher::get_blockdata, report::Report, tx_builder::TxBuilder};
use crate::{
run::{exec, prove, run_tx},
slack::try_send_report_to_slack,
};
use ethrex_config::networks::{
HOLESKY_CHAIN_ID, HOODI_CHAIN_ID, MAINNET_CHAIN_ID, Network, PublicNetwork, SEPOLIA_CHAIN_ID,
};
pub const VERSION_STRING: &str = env!("CARGO_PKG_VERSION");
#[derive(Parser)]
#[command(name="ethrex-replay", author, version=VERSION_STRING, about, long_about = None)]
pub struct EthrexReplayCLI {
#[command(subcommand)]
pub command: EthrexReplayCommand,
}
#[derive(Subcommand)]
pub enum EthrexReplayCommand {
#[cfg(not(feature = "l2"))]
#[command(about = "Replay a single block")]
Block(BlockOptions),
#[cfg(not(feature = "l2"))]
#[command(about = "Replay multiple blocks")]
Blocks(BlocksOptions),
#[cfg(not(feature = "l2"))]
#[command(about = "Plots the composition of a range of blocks.")]
BlockComposition {
#[arg(help = "Starting block. (Inclusive)")]
start: u64,
#[arg(help = "Ending block. (Inclusive)")]
end: u64,
#[arg(long, env = "RPC_URL", required = true)]
rpc_url: Url,
},
#[cfg(not(feature = "l2"))]
#[command(subcommand, about = "Replay a custom block or batch")]
Custom(CustomSubcommand),
#[cfg(not(feature = "l2"))]
#[command(about = "Generate binary input for ethrex guest")]
GenerateInput(GenerateInputOptions),
#[cfg(not(feature = "l2"))]
#[command(about = "Replay a single transaction")]
Transaction(TransactionOpts),
#[cfg(feature = "l2")]
#[command(subcommand, about = "L2 specific commands")]
L2(L2Subcommand),
}
#[cfg(feature = "l2")]
#[derive(Subcommand)]
pub enum L2Subcommand {
#[command(about = "Replay an L2 batch")]
Batch(BatchOptions),
#[command(about = "Replay an L2 block")]
Block(BlockOptions),
#[command(subcommand, about = "Replay a custom L2 block or batch")]
Custom(CustomSubcommand),
#[command(about = "Replay an L2 transaction")]
Transaction(TransactionOpts),
}
#[cfg(not(feature = "l2"))]
#[derive(Parser)]
pub enum CacheSubcommand {
#[command(about = "Cache a single block.")]
Block(BlockOptions),
#[command(about = "Cache multiple blocks.")]
Blocks(BlocksOptions),
}
#[derive(Parser)]
pub enum CustomSubcommand {
#[command(about = "Replay a single custom block")]
Block(CustomBlockOptions),
#[command(about = "Replay a single custom batch")]
Batch(CustomBatchOptions),
}
#[derive(Parser, Clone, Default)]
pub struct CommonOptions {
#[arg(long, value_enum, help_heading = "Replay Options")]
pub zkvm: Option<ZKVM>,
#[arg(long, value_enum, default_value_t = Resource::default(), help_heading = "Replay Options")]
pub resource: Resource,
#[arg(long, value_enum, default_value_t = Action::default(), help_heading = "Replay Options")]
pub action: Action,
#[arg(long = "proof", value_enum, default_value_t = ProofType::default(), help_heading = "Replay Options")]
pub proof_type: ProofType,
#[arg(
long,
short,
help = "Enable verbose logging",
help_heading = "Replay Options",
required = false
)]
pub verbose: bool,
}
#[derive(Parser, Clone)]
#[clap(group = ArgGroup::new("data_source").required(true))]
pub struct EthrexReplayOptions {
#[command(flatten)]
pub common: CommonOptions,
#[arg(long, group = "data_source", help_heading = "Replay Options")]
pub rpc_url: Option<Url>,
#[arg(
long,
group = "data_source",
help = "use cache as input instead of fetching from RPC",
help_heading = "Replay Options",
requires = "network",
conflicts_with = "cache_level"
)]
pub cached: bool,
#[arg(
long,
help = "Network to use for replay (i.e. mainnet, sepolia, hoodi). If not specified will fetch from RPC",
value_enum,
help_heading = "Replay Options"
)]
pub network: Option<Network>,
#[arg(
long,
help = "Directory to store and load cache files",
value_parser,
default_value = "./replay_cache",
help_heading = "Replay Options"
)]
pub cache_dir: PathBuf,
#[arg(
long,
default_value = "on",
help_heading = "Replay Options",
help = "Criteria to save a cache when fetching from RPC",
requires = "rpc_url"
)]
pub cache_level: CacheLevel,
#[arg(long, env = "SLACK_WEBHOOK_URL", help_heading = "Replay Options")]
pub slack_webhook_url: Option<Url>,
#[arg(
long,
help = "Execute with `Blockchain::add_block`, without using zkvm as backend",
help_heading = "Replay Options",
conflicts_with_all = ["zkvm", "proof_type"]
)]
pub no_zkvm: bool,
// CAUTION
// This flag is used to create a benchmark file that is used by our CI for
// updating benchmarks from https://docs.ethrex.xyz/benchmarks/.
// Do no remove it under any circumstances, unless you are refactoring how
// we do benchmarks in CI.
#[arg(
long,
help = "Generate a benchmark file named `bench_latest.json` with the latest execution rate in Mgas/s",
help_heading = "CI Options",
requires = "zkvm",
default_value_t = false
)]
pub bench: bool,
#[arg(
long,
default_value = "on",
help_heading = "Replay Options",
help = "Criteria to send notifications to Slack",
requires = "slack_webhook_url"
)]
pub notification_level: NotificationLevel,
}
#[derive(Clone, Debug, ValueEnum)]
pub enum ZKVM {
Jolt,
Nexus,
#[clap(name = "openvm")]
OpenVM,
Pico,
Risc0,
SP1,
Ziren,
Zisk,
}
impl Display for ZKVM {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
ZKVM::Jolt => "Jolt",
ZKVM::Nexus => "Nexus",
ZKVM::OpenVM => "OpenVM",
ZKVM::Pico => "Pico",
ZKVM::Risc0 => "RISC0",
ZKVM::SP1 => "SP1",
ZKVM::Ziren => "Ziren",
ZKVM::Zisk => "ZisK",
};
write!(f, "{s}")
}
}
#[derive(Clone, Debug, ValueEnum, Default)]
pub enum Resource {
#[default]
CPU,
GPU,
}
impl Display for Resource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Resource::CPU => "CPU",
Resource::GPU => "GPU",
};
write!(f, "{s}")
}
}
#[derive(Clone, Debug, ValueEnum, PartialEq, Eq, Default)]
pub enum Action {
#[default]
Execute,
Prove,
}
impl Display for Action {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Action::Execute => "Execute",
Action::Prove => "Prove",
};
write!(f, "{s}")
}
}
#[derive(Clone, Debug, ValueEnum, PartialEq, Eq, Default)]
pub enum ProofType {
#[default]
Compressed,
Groth16,
}
impl Display for ProofType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
ProofType::Compressed => "Compressed",
ProofType::Groth16 => "Groth16",
};
write!(f, "{s}")
}
}
impl From<ProofType> for ProofFormat {
fn from(value: ProofType) -> Self {
match value {
ProofType::Compressed => ProofFormat::Compressed,
ProofType::Groth16 => ProofFormat::Groth16,
}
}
}
#[derive(ValueEnum, Clone, Debug, PartialEq, Eq, Default)]
pub enum CacheLevel {
Failed,
Off,
#[default]
On,
}
#[derive(ValueEnum, Clone, Debug, PartialEq, Eq, Default)]
pub enum NotificationLevel {
#[default]
Failed,
Off,
On,
}
#[derive(Parser, Clone)]
pub struct BlockOptions {
#[arg(
help = "Block to use. Uses the latest if not specified.",
help_heading = "Command Options"
)]
pub block: Option<u64>,
#[command(flatten)]
pub opts: EthrexReplayOptions,
}
#[cfg(not(feature = "l2"))]
#[derive(Parser)]
#[command(group(ArgGroup::new("block_list").required(true).multiple(true).args(["blocks", "from", "endless", "cached"])))]
pub struct BlocksOptions {
#[arg(help = "List of blocks to execute.", num_args = 1.., value_delimiter = ',', conflicts_with_all = ["from", "to"], help_heading = "Command Options")]
blocks: Vec<u64>,
#[arg(
long,
help = "Starting block. (Inclusive)",
help_heading = "Command Options"
)]
from: Option<u64>,
#[arg(
long,
help = "Ending block. (Inclusive)",
requires = "from",
help_heading = "Command Options"
)]
to: Option<u64>,
#[arg(
long,
help = "Run blocks endlessly, starting from the specified block or the latest if not specified.",
help_heading = "Replay Options",
conflicts_with_all = ["blocks", "to", "cached"]
)]
pub endless: bool,
#[arg(
long,
help = "Only fetch Ethereum proofs blocks (i.e., no L2 blocks).",
help_heading = "Replay Options",
conflicts_with = "blocks"
)]
pub only_eth_proofs_blocks: bool,
#[command(flatten)]
opts: EthrexReplayOptions,
}
#[derive(Parser)]
pub struct TransactionOpts {
#[arg(help = "Transaction hash.", help_heading = "Command Options")]
tx_hash: H256,
#[arg(
long,
help = "Block number containing the transaction. Necessary in cached mode.",
help_heading = "Command Options"
)]
pub block_number: Option<u64>,
#[command(flatten)]
opts: EthrexReplayOptions,
}
#[cfg(feature = "l2")]
#[derive(Parser)]
pub struct BatchOptions {
#[arg(long, help = "Batch number to use.", help_heading = "Command Options")]
batch: u64,
#[command(flatten)]
opts: EthrexReplayOptions,
}
#[derive(Parser)]
pub struct CustomBlockOptions {
#[command(flatten)]
pub common: CommonOptions,
#[arg(
long,
help = "Number of transactions to include in the block.",
help_heading = "Command Options",
requires = "tx"
)]
pub n_txs: Option<u64>,
#[arg(
long,
help = "Kind of transactions to include in the block.",
help_heading = "Command Options",
requires = "n_txs"
)]
pub tx: Option<TxVariant>,
}
#[derive(Parser)]
pub struct CustomBatchOptions {
#[arg(
long,
help = "Number of blocks to include in the batch.",
help_heading = "Command Options"
)]
n_blocks: u64,
#[command(flatten)]
block_opts: CustomBlockOptions,
}
#[derive(ValueEnum, Clone, Debug, PartialEq, Eq, Default)]
pub enum TxVariant {
#[default]
ETHTransfer,
ERC20Transfer,
}
#[derive(Parser)]
#[command(group(ArgGroup::new("block_list").required(true).multiple(true).args(["block", "blocks", "from"])))]
pub struct GenerateInputOptions {
#[arg(
long,
conflicts_with_all = ["blocks", "from", "to"],
help = "Block to generate input for",
help_heading = "Command Options"
)]
block: Option<u64>,
#[arg(long, help = "List of blocks to execute.", num_args = 1.., value_delimiter = ',', conflicts_with_all = ["block", "from", "to"], help_heading = "Command Options")]
blocks: Vec<u64>,
#[arg(
long,
conflicts_with_all = ["blocks", "block"],
help = "Starting block. (Inclusive)",
help_heading = "Command Options"
)]
from: Option<u64>,
#[arg(
long,
conflicts_with_all = ["blocks", "block"],
help = "Ending block. (Inclusive)",
requires = "from",
help_heading = "Command Options"
)]
to: Option<u64>,
#[arg(
long,
help = "Directory to store the generated input",
value_parser,
default_value = "./generated_inputs",
help_heading = "Replay Options"
)]
output_dir: PathBuf,
#[arg(
long,
help = "RPC provider to fetch data from",
help_heading = "Replay Options"
)]
rpc_url: Url,
}
impl EthrexReplayCommand {
pub async fn run(self) -> eyre::Result<()> {
match self {
#[cfg(not(feature = "l2"))]
Self::Block(block_opts) => replay_block(block_opts.clone()).await?,
#[cfg(not(feature = "l2"))]
Self::Blocks(BlocksOptions {
mut blocks,
from,
to,
endless,
only_eth_proofs_blocks,
opts,
}) => {
// Necessary checks for running cached blocks only.
if opts.cached && blocks.is_empty() {
if from.is_none() && to.is_none() {
let network = opts.network.clone().unwrap(); // enforced by clap
let dir = opts.cache_dir.clone();
info!("Running all {} blocks inside `{}`", network, dir.display());
// In order not to repeat code, this just fills the blocks variable so that they are run afterwards.
blocks = get_block_numbers_in_cache_dir(&dir, &network)?;
info!("Found {} cached blocks: {:?}", blocks.len(), blocks);
} else if from.is_none() ^ to.is_none() {
return Err(eyre::Error::msg(
"Either both `from` and `to` must be specified, or neither.",
));
}
}
// Case ethrex-replay blocks n,...,m
if !blocks.is_empty() {
blocks.sort();
for block in blocks.clone() {
info!(
"{} block: {block}",
if opts.common.action == Action::Execute {
"Executing"
} else {
"Proving"
}
);
Box::pin(async {
Self::Block(BlockOptions {
block: Some(block),
opts: opts.clone(),
})
.run()
.await
})
.await?;
}
return Ok(());
}
// It will only be used in case from or to weren't specified or in endless mode. We can unwrap as cached mode won't reach those places.
let maybe_rpc = opts.rpc_url.as_ref();
let from = match from {
// Case --from is set
// * --endless and --to cannot be set together (constraint by clap).
// * If --endless is set, we start from --from and keep checking for new blocks
// * If --to is set, we run from --from to --to and stop
Some(from) => from,
// Case --from is not set
// * If we reach this point, --endless must be set (constraint by clap)
None => {
fetch_latest_block_number(
maybe_rpc.unwrap().clone(),
only_eth_proofs_blocks,
)
.await?
}
};
let to = match to {
// Case --to is set
// * If we reach this point, --from must be set and --endless is not set (constraint by clap)
Some(to) => to,
// Case --to is not set
// * If we reach this point, --from or --endless must be set (constraint by clap)
None => {
fetch_latest_block_number(
maybe_rpc.unwrap().clone(),
only_eth_proofs_blocks,
)
.await?
}
};
if from > to {
return Err(eyre::Error::msg(
"starting point can't be greater than ending point",
));
}
let mut block_to_replay = from;
let mut last_block_to_replay = to;
while block_to_replay <= last_block_to_replay {
if only_eth_proofs_blocks && block_to_replay % 100 != 0 {
block_to_replay += 1;
// Case --endless is set, we want to update the `to` so
// we can keep checking for new blocks
if endless && block_to_replay > last_block_to_replay {
last_block_to_replay = fetch_latest_block_number(
maybe_rpc.unwrap().clone(),
only_eth_proofs_blocks,
)
.await?;
tokio::time::sleep(Duration::from_secs(1)).await;
}
continue;
}
Box::pin(async {
Self::Block(BlockOptions {
block: Some(block_to_replay),
opts: opts.clone(),
})
.run()
.await
})
.await?;
block_to_replay += 1;
// Case --endless is set, we want to update the `to` so
// we can keep checking for new blocks
while endless && block_to_replay > last_block_to_replay {
last_block_to_replay = fetch_latest_block_number(
maybe_rpc.unwrap().clone(),
only_eth_proofs_blocks,
)
.await?;
tokio::time::sleep(Duration::from_secs(1)).await;
}
}
}
#[cfg(not(feature = "l2"))]
Self::Custom(CustomSubcommand::Block(block_opts)) => {
Box::pin(async move {
Self::Custom(CustomSubcommand::Batch(CustomBatchOptions {
n_blocks: 1,
block_opts,
}))
.run()
.await
})
.await?;
}
#[cfg(not(feature = "l2"))]
Self::Custom(CustomSubcommand::Batch(CustomBatchOptions {
n_blocks,
block_opts,
})) => {
let opts = EthrexReplayOptions {
rpc_url: Some(Url::parse("http://localhost:8545")?),
cached: false,
no_zkvm: false,
cache_level: CacheLevel::default(),
common: block_opts.common.clone(),
slack_webhook_url: None,
bench: false,
cache_dir: PathBuf::from("./replay_cache"),
network: None,
notification_level: NotificationLevel::default(),
};
replay_custom_l1_blocks(max(1, n_blocks), block_opts, opts).await?;
}
#[cfg(not(feature = "l2"))]
Self::Transaction(opts) => replay_transaction(opts).await?,
#[cfg(not(feature = "l2"))]
Self::BlockComposition {
start,
end,
rpc_url,
} => {
if start >= end {
return Err(eyre::Error::msg(
"starting point can't be greater than ending point",
));
}
let eth_client = EthClient::new(rpc_url)?;
info!(
"Fetching blocks from RPC: {start} to {end} ({} blocks)",
end - start + 1
);
let mut blocks = vec![];
for block_number in start..=end {
debug!("Fetching block {block_number}");
let rpc_block = eth_client
.get_block_by_number(BlockIdentifier::Number(block_number), true)
.await?;
let block = rpc_block
.try_into()
.map_err(|e| eyre::eyre!("Failed to convert rpc block to block: {}", e))?;
blocks.push(block);
}
plot(&blocks).await?;
}
#[cfg(not(feature = "l2"))]
Self::GenerateInput(GenerateInputOptions {
block,
blocks,
from,
to,
output_dir,
rpc_url,
}) => {
let opts = EthrexReplayOptions {
common: CommonOptions::default(),
rpc_url: Some(rpc_url.clone()),
cached: false,
network: None,
cache_dir: PathBuf::from("./replay_cache"),
cache_level: CacheLevel::Off,
slack_webhook_url: None,
no_zkvm: false,
bench: false,
notification_level: NotificationLevel::Off,
};
if !output_dir.exists() {
std::fs::create_dir_all(&output_dir)?;
}
let blocks_to_process: Vec<u64> = if !blocks.is_empty() {
blocks
} else if let Some(block) = block {
vec![block]
} else {
let from = from.ok_or_else(|| {
eyre::eyre!("Either block, blocks, or from must be specified")
})?;
let to = match to {
Some(to) => to,
None => fetch_latest_block_number(rpc_url.clone(), false).await?,
};
(from..=to).collect()
};
for block in &blocks_to_process {
let (cache, network) = get_blockdata(opts.clone(), Some(*block)).await?;
let program_input = crate::run::get_l1_input(cache)?;
let serialized_program_input =
rkyv::to_bytes::<rkyv::rancor::Error>(&program_input)?;
let input_output_path =
output_dir.join(format!("ethrex_{network}_{block}_input.bin"));
std::fs::write(input_output_path, serialized_program_input.as_slice())?;
}
if blocks_to_process.len() == 1 {
info!(
"Generated input for block {} in directory {}",
blocks_to_process[0],
output_dir.display()
);
} else {
info!(
"Generated inputs for {} blocks in directory {}",
blocks_to_process.len(),
output_dir.display()
);
}
}
#[cfg(feature = "l2")]
Self::L2(L2Subcommand::Transaction(TransactionOpts {
tx_hash,
opts,
block_number,
})) => {
replay_transaction(TransactionOpts {
tx_hash,
opts,
block_number,
})
.await?
}
#[cfg(feature = "l2")]
Self::L2(L2Subcommand::Batch(BatchOptions { batch, opts })) => {
if opts.cached {
unimplemented!("cached mode is not implemented yet");
}
let (eth_client, network) = setup_rpc(&opts).await?;
let cache = get_batchdata(eth_client, network, batch, opts.cache_dir).await?;
let backend = backend(&opts.common.zkvm)?;
let execution_result = exec(backend, cache.clone()).await;
let proving_result = match opts.common.action {
Action::Execute => None,
Action::Prove => Some(prove(backend, opts.common.proof_type, cache).await),
};
println!("Batch {batch} execution result: {execution_result:?}");
if let Some(proving_result) = proving_result {
println!("Batch {batch} proving result: {proving_result:?}");
}
}
#[cfg(feature = "l2")]
Self::L2(L2Subcommand::Block(block_opts)) => replay_block(block_opts).await?,
#[cfg(feature = "l2")]
Self::L2(L2Subcommand::Custom(CustomSubcommand::Block(block_opts))) => {
Box::pin(async move {
Self::L2(L2Subcommand::Custom(CustomSubcommand::Batch(
CustomBatchOptions {
n_blocks: 1,
block_opts,
},
)))
.run()
.await
})
.await?
}
#[cfg(feature = "l2")]
Self::L2(L2Subcommand::Custom(CustomSubcommand::Batch(CustomBatchOptions {
n_blocks,
block_opts,
}))) => {
let opts = EthrexReplayOptions {
common: block_opts.common.clone(),
rpc_url: Some(Url::parse("http://localhost:8545")?),
cached: false,
no_zkvm: false,
cache_level: CacheLevel::default(),
slack_webhook_url: None,
bench: false,
cache_dir: PathBuf::from("./replay_cache"),
network: None,
notification_level: NotificationLevel::default(),
};
replay_custom_l2_blocks(max(1, n_blocks), opts).await?;
}
}
Ok(())
}
}
pub async fn setup_rpc(opts: &EthrexReplayOptions) -> eyre::Result<(EthClient, Network)> {
let eth_client = EthClient::new(opts.rpc_url.as_ref().unwrap().clone())?;
let chain_id = eth_client.get_chain_id().await?.as_u64();
let network = network_from_chain_id(chain_id);
Ok((eth_client, network))
}
async fn replay_no_zkvm(cache: Cache, opts: &EthrexReplayOptions) -> eyre::Result<Duration> {
let b = backend(&opts.common.zkvm)?;
if !matches!(b, Backend::Exec) {
eyre::bail!("Tried to execute without zkVM but backend was set to {b:?}");
}
if opts.common.action == Action::Prove {
eyre::bail!("Proving not enabled without backend");
}
if cache.blocks.len() > 1 {
eyre::bail!("Cache for L1 witness should contain only one block.");
}
let start = Instant::now();
info!("Preparing Storage for execution without zkVM");
let chain_config = cache.get_chain_config()?;
let block = cache.blocks[0].clone();
let witness = execution_witness_from_rpc_chain_config(
cache.witness.clone(),
chain_config,
cache.get_first_block_number()?,
)?;
let network = &cache.network;
let guest_program = GuestProgramState::try_from(witness.clone())?;
// This will contain all code hashes with the corresponding bytecode
// For the code hashes that we don't have we'll fill it with <CodeHash, Bytes::new()>
let mut all_codes_hashed = guest_program.codes_hashed.clone();
let mut store = Store::new("nothing", EngineType::InMemory)?;
// - Set up state trie nodes
let state_root = guest_program.parent_block_header.state_root;
let all_nodes: BTreeMap<H256, Node> = cache
.witness
.state
.iter()
.filter_map(|b| {
if b.as_ref() == [0x80] {
return None;
} // skip nulls
let h = keccak(b);
Some(Node::decode(b).map(|node| (h, node)))
})
.collect::<Result<_, _>>()?;
let state_trie = InMemoryTrieDB::from_nodes(state_root, &all_nodes)?;
let state_trie_nodes = get_trie_nodes_with_dummies(state_trie);
let trie = store.open_direct_state_trie(*EMPTY_TRIE_HASH)?;
trie.db().put_batch(state_trie_nodes)?;
// - Set up all storage tries for all addresses in the execution witness
let addresses: Vec<Address> = witness
.keys
.iter()
.filter(|k| k.len() == Address::len_bytes())
.map(|k| Address::from_slice(k))
.collect();
for address in &addresses {
let hashed_address = hash_address(address);
// Account state may not be in the state trie
let Some(account_state_rlp) = guest_program.state_trie.get(&hashed_address)? else {
continue;
};
let account_state = AccountState::decode(&account_state_rlp)?;
// If code hash of account isn't present insert empty code so that if not found the execution doesn't break.
let code_hash = account_state.code_hash;
all_codes_hashed.entry(code_hash).or_insert(Code::default());
let storage_root = account_state.storage_root;
let Ok(storage_trie) = InMemoryTrieDB::from_nodes(storage_root, &all_nodes) else {
continue;
};
let storage_trie_nodes = get_trie_nodes_with_dummies(storage_trie);
// If there isn't any storage trie node we don't need to write anything
if storage_trie_nodes.is_empty() {
continue;
}
let storage_trie_nodes = vec![(H256::from_slice(&hashed_address), storage_trie_nodes)];
store
.write_storage_trie_nodes_batch(storage_trie_nodes)
.await?;
}
store.chain_config = chain_config;
// Add codes to DB
for (code_hash, mut code) in all_codes_hashed {
code.hash = code_hash;
store.add_account_code(code).await?;
}
// Add block headers to DB
for (_n, header) in guest_program.block_headers.clone() {
store.add_block_header(header.hash(), header).await?;
}
let blockchain = Blockchain::default_with_store(store);
info!("Storage preparation finished in {:.2?}", start.elapsed());
info!("Executing block {} on {}", block.header.number, network);
let start_time = Instant::now();
blockchain.add_block(block)?;
let duration = start_time.elapsed();
info!("add_block execution time: {:.2?}", duration);
Ok(duration)
}
async fn replay_transaction(tx_opts: TransactionOpts) -> eyre::Result<()> {
let tx_hash = tx_opts.tx_hash;
if tx_opts.opts.cached && tx_opts.block_number.is_none() {
return Err(eyre::Error::msg(
"In cached mode, --block-number must be specified for transaction replay",
));
}
let cache = get_blockdata(tx_opts.opts, tx_opts.block_number).await?.0;
let (receipt, transitions) = run_tx(cache, tx_hash).await?;
print_receipt(receipt);
for transition in transitions {
print_transition(transition);
}
Ok(())
}