-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1722 lines (1536 loc) · 61.4 KB
/
lib.rs
File metadata and controls
1722 lines (1536 loc) · 61.4 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
//! Reusable dev-node runner for Evolve applications.
//!
//! This module provides a complete dev-node implementation that includes:
//! - Block production with configurable intervals
//! - JSON-RPC server for Ethereum-compatible queries
//! - Chain indexing for block/transaction/receipt queries
//! - Persistent storage across restarts
pub mod cli;
pub mod config;
use std::fmt::Debug;
use std::net::SocketAddr;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use alloy_primitives::U256;
use borsh::{BorshDeserialize, BorshSerialize};
use commonware_runtime::tokio::{Config as TokioConfig, Context as TokioContext, Runner};
use commonware_runtime::{Runner as RunnerTrait, Spawner};
use evolve_chain_index::{
ChainStateProvider, ChainStateProviderConfig, PersistentChainIndex, StateQuerier,
StorageStateQuerier, DEFAULT_PROTOCOL_VERSION,
};
use evolve_core::encoding::Encodable;
use evolve_core::{AccountId, ReadonlyKV};
use evolve_eth_jsonrpc::{start_server_with_subscriptions, RpcServerConfig, SubscriptionManager};
use evolve_grpc::{GrpcServer, GrpcServerConfig};
use evolve_mempool::{new_shared_mempool, Mempool, MempoolTx, SharedMempool};
use evolve_rpc_types::SyncStatus;
use evolve_server::{
load_chain_state, save_chain_state, state_changes_to_operations, ChainState, DevConfig,
DevConsensus, CHAIN_STATE_KEY,
};
use evolve_server::{OnBlockArchive, StfExecutor};
use evolve_stf_traits::{AccountsCodeStorage, StateChange, Transaction};
use evolve_storage::types::BlockHash as ArchiveBlockHash;
use evolve_storage::{
BlockStorage, BlockStorageConfig, MockStorage, Operation, Storage, StorageConfig,
};
use evolve_tx_eth::TxContext;
use std::future::Future;
pub use cli::*;
pub use config::*;
/// Default data directory for persistent storage.
pub const DEFAULT_DATA_DIR: &str = "./data";
/// Default RPC server address.
pub const DEFAULT_RPC_ADDR: &str = "127.0.0.1:8545";
fn parse_env_u64(var: &str, default: u64) -> u64 {
std::env::var(var)
.ok()
.and_then(|v| v.parse::<u64>().ok())
.filter(|v| *v > 0)
.unwrap_or(default)
}
fn parse_env_usize(var: &str, default: usize) -> usize {
std::env::var(var)
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|v| *v > 0)
.unwrap_or(default)
}
fn configured_block_interval() -> Duration {
Duration::from_millis(parse_env_u64("EVOLVE_BLOCK_INTERVAL_MS", 1_000))
}
fn configured_max_txs_per_block() -> usize {
parse_env_usize("EVOLVE_MAX_TXS_PER_BLOCK", 1_000)
}
/// Convenience handles for a dev node wired with a mempool.
pub struct DevNodeMempoolHandles<Stf, S, Codes, Tx: MempoolTx> {
/// Dev consensus engine wired to mempool transactions.
pub dev: Arc<DevConsensus<Stf, S, Codes, Tx, evolve_server::NoopChainIndex>>,
/// Shared mempool instance.
pub mempool: SharedMempool<Mempool<Tx>>,
}
/// Build a dev consensus + mempool pair for testing and tools.
///
/// Generic over transaction type `Tx`. For ETH transactions, use `TxContext`.
pub fn build_dev_node_with_mempool<Stf, Codes, S, Tx>(
stf: Stf,
storage: S,
codes: Codes,
config: DevConfig,
) -> DevNodeMempoolHandles<Stf, S, Codes, Tx>
where
Tx: Transaction + MempoolTx + Encodable + Send + Sync + 'static,
S: ReadonlyKV + Storage + Clone + Send + Sync + 'static,
Codes: AccountsCodeStorage + Send + Sync + 'static,
Stf: StfExecutor<Tx, S, Codes> + Send + Sync + 'static,
{
let mempool: SharedMempool<Mempool<Tx>> = new_shared_mempool();
let dev = Arc::new(DevConsensus::with_mempool(
stf,
storage,
codes,
config,
mempool.clone(),
));
DevNodeMempoolHandles { dev, mempool }
}
/// Configuration for the dev node RPC server.
#[derive(Debug, Clone)]
pub struct RpcConfig {
/// Address to bind the HTTP server to.
pub http_addr: SocketAddr,
/// Chain ID for eth_chainId.
pub chain_id: u64,
/// Whether RPC is enabled.
pub enabled: bool,
/// Whether block indexing is enabled while producing blocks.
pub enable_block_indexing: bool,
/// Optional gRPC server address. When set, a gRPC server is started
/// alongside JSON-RPC, sharing the same state provider and subscriptions.
pub grpc_addr: Option<SocketAddr>,
/// Enable gzip compression for the gRPC server.
pub grpc_enable_gzip: bool,
/// Maximum gRPC request/response size in bytes.
pub grpc_max_message_size: usize,
/// Graceful shutdown timeout in seconds.
pub shutdown_timeout_secs: u64,
}
impl Default for RpcConfig {
fn default() -> Self {
Self {
http_addr: DEFAULT_RPC_ADDR.parse().unwrap(),
chain_id: 1,
enabled: true,
enable_block_indexing: true,
grpc_addr: None,
grpc_enable_gzip: true,
grpc_max_message_size: 4 * 1024 * 1024,
shutdown_timeout_secs: 10,
}
}
}
impl RpcConfig {
/// Create a disabled RPC config.
pub fn disabled() -> Self {
Self {
enabled: false,
..Default::default()
}
}
/// Set the HTTP address.
pub fn with_addr(mut self, addr: SocketAddr) -> Self {
self.http_addr = addr;
self
}
/// Set the chain ID.
pub fn with_chain_id(mut self, chain_id: u64) -> Self {
self.chain_id = chain_id;
self
}
/// Enable or disable block indexing while keeping RPC enabled.
pub fn with_block_indexing(mut self, enabled: bool) -> Self {
self.enable_block_indexing = enabled;
self
}
/// Enable the gRPC server on the given address.
pub fn with_grpc(mut self, addr: SocketAddr) -> Self {
self.grpc_addr = Some(addr);
self
}
/// Configure gRPC compression and message sizing.
pub fn with_grpc_settings(mut self, enable_gzip: bool, max_message_size: usize) -> Self {
self.grpc_enable_gzip = enable_gzip;
self.grpc_max_message_size = max_message_size;
self
}
/// Set the graceful shutdown timeout in seconds.
pub fn with_shutdown_timeout_secs(mut self, shutdown_timeout_secs: u64) -> Self {
self.shutdown_timeout_secs = shutdown_timeout_secs;
self
}
}
/// Result of a genesis run, including the state changes to commit.
pub struct GenesisOutput<G> {
/// Application-specific genesis result.
pub genesis_result: G,
/// State changes produced by genesis.
pub changes: Vec<StateChange>,
}
/// Trait for extracting the token account ID from a genesis result.
///
/// Implementing this trait on your genesis result type enables
/// `eth_getBalance` queries via the RPC server.
pub trait HasTokenAccountId {
fn token_account_id(&self) -> AccountId;
}
type RuntimeContext = TokioContext;
/// Build the block archive callback.
///
/// Creates a `BlockStorage` backed by the commonware archive and returns
/// an `OnBlockArchive` callback that writes each produced block into it.
///
/// # Panics
///
/// Panics if block storage initialization fails. Block archival is a required
/// subsystem — all produced blocks must be persisted.
async fn build_block_archive(context: TokioContext) -> OnBlockArchive {
let config = BlockStorageConfig::default();
let retention = config.retention_blocks;
let prune_interval = config.blocks_per_section;
let store = BlockStorage::new(context, config)
.await
.expect("failed to initialize block archive storage");
let (tx, mut rx) = tokio::sync::mpsc::channel::<(u64, ArchiveBlockHash, bytes::Bytes)>(64);
// Single consumer task ensures blocks are written in order.
tokio::spawn(async move {
let mut store = store;
while let Some((block_number, block_hash, block_bytes)) = rx.recv().await {
if let Err(e) = store.put_sync(block_number, block_hash, block_bytes).await {
tracing::warn!("Failed to archive block {}: {:?}", block_number, e);
}
// Prune old blocks at section boundaries to bound disk usage.
if retention > 0 && block_number > retention && block_number % prune_interval == 0 {
let min_block = block_number.saturating_sub(retention);
if let Err(e) = store.prune(min_block).await {
tracing::warn!(min_block, "Failed to prune block archive: {:?}", e);
}
}
}
});
tracing::info!(retention, "Block archive storage enabled");
Arc::new(move |block_number, block_hash, block_bytes| {
let hash_bytes = ArchiveBlockHash::new(block_hash.0);
if let Err(e) = tx.try_send((block_number, hash_bytes, block_bytes)) {
tracing::warn!(
"Block archive channel full or closed for block {}: {}",
block_number,
e
);
}
})
}
fn grpc_server_config(rpc_config: &RpcConfig, addr: SocketAddr) -> GrpcServerConfig {
GrpcServerConfig {
addr,
chain_id: rpc_config.chain_id,
enable_gzip: rpc_config.grpc_enable_gzip,
max_message_size: rpc_config.grpc_max_message_size,
}
}
fn shutdown_timeout(rpc_config: &RpcConfig) -> Duration {
Duration::from_secs(rpc_config.shutdown_timeout_secs)
}
#[derive(Clone, Copy)]
enum EthRunnerMode {
PersistentSidecars,
EphemeralSidecars,
}
impl EthRunnerMode {
fn enable_block_archive(self) -> bool {
matches!(self, Self::PersistentSidecars)
}
fn persistent_chain_index_path(self, data_dir: &Path) -> Option<std::path::PathBuf> {
matches!(self, Self::PersistentSidecars).then(|| data_dir.join("chain-index.sqlite"))
}
}
#[derive(Clone)]
struct EthRunnerConfig {
rpc: RpcConfig,
runner_mode: EthRunnerMode,
}
/// Run the dev node with default settings (RPC enabled).
pub fn run_dev_node<
Stf,
Codes,
Tx,
G,
S,
BuildGenesisStf,
BuildStf,
BuildCodes,
RunGenesis,
BuildStorage,
BuildStorageFut,
>(
data_dir: impl AsRef<Path>,
build_genesis_stf: BuildGenesisStf,
build_stf: BuildStf,
build_codes: BuildCodes,
run_genesis: RunGenesis,
build_storage: BuildStorage,
) where
Tx: Transaction + MempoolTx + Encodable + Send + Sync + 'static,
Codes: AccountsCodeStorage + Send + Sync + 'static,
S: ReadonlyKV + Storage + Clone + Send + Sync + 'static,
Stf: StfExecutor<Tx, S, Codes> + Send + Sync + 'static,
G: BorshSerialize
+ BorshDeserialize
+ Clone
+ Debug
+ HasTokenAccountId
+ Send
+ Sync
+ 'static,
BuildGenesisStf: Fn() -> Stf + Send + Sync + 'static,
BuildStf: Fn(&G) -> Stf + Send + Sync + 'static,
BuildCodes: Fn() -> Codes + Clone + Send + Sync + 'static,
RunGenesis: Fn(&Stf, &Codes, &S) -> Result<GenesisOutput<G>, Box<dyn std::error::Error + Send + Sync>>
+ Send
+ Sync
+ 'static,
BuildStorage: Fn(RuntimeContext, StorageConfig) -> BuildStorageFut + Send + Sync + 'static,
BuildStorageFut:
Future<Output = Result<S, Box<dyn std::error::Error + Send + Sync>>> + Send + 'static,
{
run_dev_node_with_rpc(
data_dir,
build_genesis_stf,
build_stf,
build_codes,
run_genesis,
build_storage,
RpcConfig::default(),
)
}
/// Run the dev node with custom RPC configuration.
pub fn run_dev_node_with_rpc<
Stf,
Codes,
Tx,
G,
S,
BuildGenesisStf,
BuildStf,
BuildCodes,
RunGenesis,
BuildStorage,
BuildStorageFut,
>(
data_dir: impl AsRef<Path>,
build_genesis_stf: BuildGenesisStf,
build_stf: BuildStf,
build_codes: BuildCodes,
run_genesis: RunGenesis,
build_storage: BuildStorage,
rpc_config: RpcConfig,
) where
Tx: Transaction + MempoolTx + Encodable + Send + Sync + 'static,
Codes: AccountsCodeStorage + Send + Sync + 'static,
S: ReadonlyKV + Storage + Clone + Send + Sync + 'static,
Stf: StfExecutor<Tx, S, Codes> + Send + Sync + 'static,
G: BorshSerialize
+ BorshDeserialize
+ Clone
+ Debug
+ HasTokenAccountId
+ Send
+ Sync
+ 'static,
BuildGenesisStf: Fn() -> Stf + Send + Sync + 'static,
BuildStf: Fn(&G) -> Stf + Send + Sync + 'static,
BuildCodes: Fn() -> Codes + Clone + Send + Sync + 'static,
RunGenesis: Fn(&Stf, &Codes, &S) -> Result<GenesisOutput<G>, Box<dyn std::error::Error + Send + Sync>>
+ Send
+ Sync
+ 'static,
BuildStorage: Fn(RuntimeContext, StorageConfig) -> BuildStorageFut + Send + Sync + 'static,
BuildStorageFut:
Future<Output = Result<S, Box<dyn std::error::Error + Send + Sync>>> + Send + 'static,
{
tracing::info!("=== Evolve Dev Node ===");
let data_dir = data_dir.as_ref();
std::fs::create_dir_all(data_dir).expect("failed to create data directory");
let storage_config = StorageConfig {
path: data_dir.to_path_buf(),
..Default::default()
};
let chain_index_db_path = data_dir.join("chain-index.sqlite");
let runtime_config = TokioConfig::default()
.with_storage_directory(data_dir)
.with_worker_threads(4); // More threads for RPC handling
let runner = Runner::new(runtime_config);
let build_genesis_stf = Arc::new(build_genesis_stf);
let build_stf = Arc::new(build_stf);
let build_codes = Arc::new(build_codes);
let run_genesis = Arc::new(run_genesis);
let build_storage = Arc::new(build_storage);
runner.start(move |context| {
let build_genesis_stf = Arc::clone(&build_genesis_stf);
let build_stf = Arc::clone(&build_stf);
let build_codes = Arc::clone(&build_codes);
let run_genesis = Arc::clone(&run_genesis);
let build_storage = Arc::clone(&build_storage);
let rpc_config = rpc_config.clone();
let chain_index_db_path = chain_index_db_path.clone();
async move {
// Clone context early since build_storage takes ownership
let context_for_shutdown = context.clone();
let context_for_archive = context.clone();
let storage = (build_storage)(context, storage_config)
.await
.expect("failed to create storage");
// Create account codes
let codes = build_codes();
let (genesis_result, initial_height) = match load_chain_state::<G, _>(&storage) {
Some(state) => {
tracing::info!("Resuming from existing state at height {}", state.height);
tracing::info!("Genesis state: {:?}", state.genesis_result);
(state.genesis_result, state.height)
}
None => {
tracing::info!("No existing state found, running genesis...");
let bootstrap_stf = (build_genesis_stf)();
let output =
(run_genesis)(&bootstrap_stf, &codes, &storage).expect("genesis failed");
commit_genesis(&storage, output.changes, &output.genesis_result)
.await
.expect("genesis commit failed");
tracing::info!("Genesis complete. Result: {:?}", output.genesis_result);
(output.genesis_result, 1)
}
};
// Build STF for normal execution
let stf = (build_stf)(&genesis_result);
// Create DevConsensus config
let block_interval = configured_block_interval();
let dev_config = DevConfig {
block_interval: Some(block_interval),
initial_height,
chain_id: rpc_config.chain_id,
..Default::default()
};
// Build block archive callback (always on)
let archive_cb = build_block_archive(context_for_archive).await;
// Set up RPC infrastructure if enabled
let rpc_handle = if rpc_config.enabled {
// Create chain index backed by SQLite
let chain_index = Arc::new(
PersistentChainIndex::new(&chain_index_db_path)
.expect("failed to open chain index database"),
);
// Initialize from existing data
if let Err(e) = chain_index.initialize() {
tracing::warn!("Failed to initialize chain index: {:?}", e);
}
// Create subscription manager for real-time events
let subscriptions = Arc::new(SubscriptionManager::new());
// Create state provider for RPC
let codes_for_rpc = Arc::new(build_codes());
let state_provider_config = ChainStateProviderConfig {
chain_id: rpc_config.chain_id,
protocol_version: DEFAULT_PROTOCOL_VERSION.to_string(),
gas_price: U256::ZERO,
sync_status: SyncStatus::NotSyncing(false),
};
let state_querier: Arc<dyn StateQuerier> = Arc::new(StorageStateQuerier::new(
storage.clone(),
genesis_result.token_account_id(),
));
let state_provider = ChainStateProvider::with_account_codes(
Arc::clone(&chain_index),
state_provider_config.clone(),
Arc::clone(&codes_for_rpc),
)
.with_state_querier(Arc::clone(&state_querier));
// Start JSON-RPC server
let server_config = RpcServerConfig {
http_addr: rpc_config.http_addr,
chain_id: rpc_config.chain_id,
};
tracing::info!("Starting JSON-RPC server on {}", rpc_config.http_addr);
let handle = start_server_with_subscriptions(
server_config,
state_provider,
Arc::clone(&subscriptions),
)
.await
.expect("failed to start RPC server");
let grpc_handle = if let Some(grpc_addr) = rpc_config.grpc_addr {
let grpc_state_provider = ChainStateProvider::with_account_codes(
Arc::clone(&chain_index),
state_provider_config,
codes_for_rpc,
)
.with_state_querier(state_querier);
let grpc_config = grpc_server_config(&rpc_config, grpc_addr);
tracing::info!("Starting gRPC server on {}", grpc_addr);
let grpc_server = GrpcServer::with_subscription_manager(
grpc_config,
grpc_state_provider,
Arc::clone(&subscriptions),
);
Some(tokio::spawn(async move {
if let Err(e) = grpc_server.serve().await {
tracing::error!("gRPC server error: {}", e);
}
}))
} else {
None
};
// Create DevConsensus with RPC support
let consensus = DevConsensus::with_rpc(
stf,
storage,
codes,
dev_config,
chain_index,
subscriptions,
)
.with_indexing_enabled(rpc_config.enable_block_indexing)
.with_block_archive(archive_cb);
let dev: Arc<DevConsensus<Stf, S, Codes, Tx, PersistentChainIndex>> =
Arc::new(consensus);
tracing::info!(
"Block interval: {:?}, starting at height {}",
block_interval,
initial_height
);
tracing::info!("Starting block production... (Ctrl+C to stop)");
// Run block production and Ctrl+C handling concurrently using Spawner pattern.
// When Ctrl+C is received, stop() triggers shutdown signal via context.stopped().
tokio::select! {
_ = dev.run_block_production(context_for_shutdown.clone()) => {
// Block production exited
}
_ = tokio::signal::ctrl_c() => {
tracing::info!("Received Ctrl+C, initiating graceful shutdown...");
context_for_shutdown
.stop(0, Some(shutdown_timeout(&rpc_config)))
.await
.expect("shutdown failed");
}
}
// Save chain state
let final_height = dev.height();
tracing::info!("Stopped at height: {}", final_height);
let chain_state = ChainState {
height: final_height,
genesis_result,
};
if let Err(e) = save_chain_state(dev.storage(), &chain_state).await {
tracing::error!("Failed to save chain state: {}", e);
} else {
tracing::info!("Saved chain state at height {}", final_height);
}
Some((handle, grpc_handle))
} else {
// No RPC - use simple DevConsensus
let consensus = DevConsensus::new(stf, storage, codes, dev_config)
.with_block_archive(archive_cb);
let dev: Arc<DevConsensus<Stf, S, Codes, Tx, evolve_server::NoopChainIndex>> =
Arc::new(consensus);
tracing::info!(
"Block interval: {:?}, starting at height {}",
block_interval,
initial_height
);
tracing::info!("Starting block production... (Ctrl+C to stop)");
// Run block production and Ctrl+C handling concurrently using Spawner pattern
tokio::select! {
_ = dev.run_block_production(context_for_shutdown.clone()) => {
// Block production exited
}
_ = tokio::signal::ctrl_c() => {
tracing::info!("Received Ctrl+C, initiating graceful shutdown...");
context_for_shutdown
.stop(0, Some(shutdown_timeout(&rpc_config)))
.await
.expect("shutdown failed");
}
}
let final_height = dev.height();
tracing::info!("Stopped at height: {}", final_height);
let chain_state = ChainState {
height: final_height,
genesis_result,
};
if let Err(e) = save_chain_state(dev.storage(), &chain_state).await {
tracing::error!("Failed to save chain state: {}", e);
} else {
tracing::info!("Saved chain state at height {}", final_height);
}
None
};
// Stop RPC server if running
if let Some((handle, grpc_handle)) = rpc_handle {
tracing::info!("Stopping RPC server...");
handle.stop().expect("failed to stop RPC server");
tracing::info!("RPC server stopped");
if let Some(grpc_handle) = grpc_handle {
tracing::info!("Stopping gRPC server...");
grpc_handle.abort();
tracing::info!("gRPC server stopped");
}
}
}
});
}
/// Run the dev node with RPC and mempool-enabled transaction ingestion.
///
/// Generic over transaction type `Tx`. For ETH transactions, use
/// `run_dev_node_with_rpc_and_mempool_eth` for convenience.
///
/// Note: When using a custom `Tx` type with RPC enabled, the RPC layer
/// will still use `TxContext` for `eth_sendRawTransaction`. For custom
/// transaction types, consider disabling RPC or providing a custom gateway.
pub fn run_dev_node_with_rpc_and_mempool<
Stf,
Codes,
Tx,
G,
S,
BuildGenesisStf,
BuildStf,
BuildCodes,
RunGenesis,
BuildStorage,
BuildStorageFut,
>(
data_dir: impl AsRef<Path>,
build_genesis_stf: BuildGenesisStf,
build_stf: BuildStf,
build_codes: BuildCodes,
run_genesis: RunGenesis,
build_storage: BuildStorage,
rpc_config: RpcConfig,
) where
Tx: Transaction + MempoolTx + Encodable + Send + Sync + 'static,
Codes: AccountsCodeStorage + Send + Sync + 'static,
S: ReadonlyKV + Storage + Clone + Send + Sync + 'static,
Stf: StfExecutor<Tx, S, Codes> + Send + Sync + 'static,
G: BorshSerialize + BorshDeserialize + Clone + Debug + Send + Sync + 'static,
BuildGenesisStf: Fn() -> Stf + Send + Sync + 'static,
BuildStf: Fn(&G) -> Stf + Send + Sync + 'static,
BuildCodes: Fn() -> Codes + Clone + Send + Sync + 'static,
RunGenesis: Fn(&Stf, &Codes, &S) -> Result<GenesisOutput<G>, Box<dyn std::error::Error + Send + Sync>>
+ Send
+ Sync
+ 'static,
BuildStorage: Fn(RuntimeContext, StorageConfig) -> BuildStorageFut + Send + Sync + 'static,
BuildStorageFut:
Future<Output = Result<S, Box<dyn std::error::Error + Send + Sync>>> + Send + 'static,
{
tracing::info!("=== Evolve Dev Node (mempool) ===");
let data_dir = data_dir.as_ref();
std::fs::create_dir_all(data_dir).expect("failed to create data directory");
let storage_config = StorageConfig {
path: data_dir.to_path_buf(),
..Default::default()
};
let runtime_config = TokioConfig::default()
.with_storage_directory(data_dir)
.with_worker_threads(4);
let runner = Runner::new(runtime_config);
let build_genesis_stf = Arc::new(build_genesis_stf);
let build_stf = Arc::new(build_stf);
let build_codes = Arc::new(build_codes);
let run_genesis = Arc::new(run_genesis);
let build_storage = Arc::new(build_storage);
runner.start(move |context| {
let build_genesis_stf = Arc::clone(&build_genesis_stf);
let build_stf = Arc::clone(&build_stf);
let build_codes = Arc::clone(&build_codes);
let run_genesis = Arc::clone(&run_genesis);
let build_storage = Arc::clone(&build_storage);
let rpc_config = rpc_config.clone();
async move {
let context_for_shutdown = context.clone();
let storage = (build_storage)(context, storage_config)
.await
.expect("failed to create storage");
let codes = build_codes();
let (genesis_result, initial_height) = match load_chain_state::<G, _>(&storage) {
Some(state) => {
tracing::info!("Resuming from existing state at height {}", state.height);
tracing::info!("Genesis state: {:?}", state.genesis_result);
(state.genesis_result, state.height)
}
None => {
tracing::info!("No existing state found, running genesis...");
let bootstrap_stf = (build_genesis_stf)();
let output =
(run_genesis)(&bootstrap_stf, &codes, &storage).expect("genesis failed");
commit_genesis(&storage, output.changes, &output.genesis_result)
.await
.expect("genesis commit failed");
tracing::info!("Genesis complete. Result: {:?}", output.genesis_result);
(output.genesis_result, 1)
}
};
let stf = (build_stf)(&genesis_result);
let block_interval = configured_block_interval();
let max_txs_per_block = configured_max_txs_per_block();
let dev_config = DevConfig {
block_interval: Some(block_interval),
initial_height,
chain_id: rpc_config.chain_id,
..Default::default()
};
let mempool: SharedMempool<Mempool<Tx>> = new_shared_mempool();
// Note: RPC with custom Tx types is not fully supported.
// The RPC layer requires TxContext for eth_sendRawTransaction.
// For custom Tx types, use run_dev_node_with_rpc_and_mempool_eth instead.
if rpc_config.enabled {
tracing::warn!(
"RPC enabled with generic Tx type. eth_sendRawTransaction will not work. \
Use run_dev_node_with_rpc_and_mempool_eth for ETH transactions with full RPC support."
);
}
let dev: Arc<DevConsensus<Stf, S, Codes, Tx, evolve_server::NoopChainIndex>> =
Arc::new(DevConsensus::with_mempool(stf, storage, codes, dev_config, mempool));
tracing::info!(
"Block interval: {:?}, max_txs_per_block: {}, starting at height {}",
block_interval,
max_txs_per_block,
initial_height
);
tracing::info!("Starting block production... (Ctrl+C to stop)");
tokio::select! {
_ = dev.run_block_production_with_mempool(context_for_shutdown.clone(), max_txs_per_block) => {
}
_ = tokio::signal::ctrl_c() => {
tracing::info!("Received Ctrl+C, initiating graceful shutdown...");
context_for_shutdown
.stop(0, Some(shutdown_timeout(&rpc_config)))
.await
.expect("shutdown failed");
}
}
let final_height = dev.height();
tracing::info!("Stopped at height: {}", final_height);
let chain_state = ChainState {
height: final_height,
genesis_result,
};
if let Err(e) = save_chain_state(dev.storage(), &chain_state).await {
tracing::error!("Failed to save chain state: {}", e);
} else {
tracing::info!("Saved chain state at height {}", final_height);
}
}
});
}
/// Run the dev node with RPC and mempool for ETH transactions (TxContext).
///
/// This is a convenience wrapper around `run_dev_node_with_rpc_and_mempool`
/// that uses `TxContext` as the transaction type and sets up the full
/// ETH JSON-RPC server with `eth_sendRawTransaction` support.
pub fn run_dev_node_with_rpc_and_mempool_eth<
Stf,
Codes,
G,
S,
BuildGenesisStf,
BuildStf,
BuildCodes,
RunGenesis,
BuildStorage,
BuildStorageFut,
>(
data_dir: impl AsRef<Path>,
build_genesis_stf: BuildGenesisStf,
build_stf: BuildStf,
build_codes: BuildCodes,
run_genesis: RunGenesis,
build_storage: BuildStorage,
rpc_config: RpcConfig,
) where
Codes: AccountsCodeStorage + Send + Sync + 'static,
S: ReadonlyKV + Storage + Clone + Send + Sync + 'static,
Stf: StfExecutor<TxContext, S, Codes> + Send + Sync + 'static,
G: BorshSerialize
+ BorshDeserialize
+ Clone
+ Debug
+ HasTokenAccountId
+ Send
+ Sync
+ 'static,
BuildGenesisStf: Fn() -> Stf + Send + Sync + 'static,
BuildStf: Fn(&G) -> Stf + Send + Sync + 'static,
BuildCodes: Fn() -> Codes + Clone + Send + Sync + 'static,
RunGenesis: Fn(&Stf, &Codes, &S) -> Result<GenesisOutput<G>, Box<dyn std::error::Error + Send + Sync>>
+ Send
+ Sync
+ 'static,
BuildStorage: Fn(RuntimeContext, StorageConfig) -> BuildStorageFut + Send + Sync + 'static,
BuildStorageFut:
Future<Output = Result<S, Box<dyn std::error::Error + Send + Sync>>> + Send + 'static,
{
run_dev_node_with_rpc_and_mempool_eth_impl(
data_dir,
build_genesis_stf,
build_stf,
build_codes,
run_genesis,
build_storage,
EthRunnerConfig {
rpc: rpc_config,
runner_mode: EthRunnerMode::PersistentSidecars,
},
)
}
fn run_dev_node_with_rpc_and_mempool_eth_impl<
Stf,
Codes,
G,
S,
BuildGenesisStf,
BuildStf,
BuildCodes,
RunGenesis,
BuildStorage,
BuildStorageFut,
>(
data_dir: impl AsRef<Path>,
build_genesis_stf: BuildGenesisStf,
build_stf: BuildStf,
build_codes: BuildCodes,
run_genesis: RunGenesis,
build_storage: BuildStorage,
runner_config: EthRunnerConfig,
) where
Codes: AccountsCodeStorage + Send + Sync + 'static,
S: ReadonlyKV + Storage + Clone + Send + Sync + 'static,
Stf: StfExecutor<TxContext, S, Codes> + Send + Sync + 'static,
G: BorshSerialize
+ BorshDeserialize
+ Clone
+ Debug
+ HasTokenAccountId
+ Send
+ Sync
+ 'static,
BuildGenesisStf: Fn() -> Stf + Send + Sync + 'static,
BuildStf: Fn(&G) -> Stf + Send + Sync + 'static,
BuildCodes: Fn() -> Codes + Clone + Send + Sync + 'static,
RunGenesis: Fn(&Stf, &Codes, &S) -> Result<GenesisOutput<G>, Box<dyn std::error::Error + Send + Sync>>
+ Send
+ Sync
+ 'static,
BuildStorage: Fn(RuntimeContext, StorageConfig) -> BuildStorageFut + Send + Sync + 'static,
BuildStorageFut:
Future<Output = Result<S, Box<dyn std::error::Error + Send + Sync>>> + Send + 'static,
{
tracing::info!("=== Evolve Dev Node (ETH mempool) ===");
let data_dir = data_dir.as_ref();
std::fs::create_dir_all(data_dir).expect("failed to create data directory");
let storage_config = StorageConfig {
path: data_dir.to_path_buf(),
..Default::default()
};
let chain_index_db_path = runner_config
.runner_mode
.persistent_chain_index_path(data_dir);
let runtime_config = TokioConfig::default()
.with_storage_directory(data_dir)
.with_worker_threads(4);
let runner = Runner::new(runtime_config);
let build_genesis_stf = Arc::new(build_genesis_stf);
let build_stf = Arc::new(build_stf);
let build_codes = Arc::new(build_codes);
let run_genesis = Arc::new(run_genesis);
let build_storage = Arc::new(build_storage);
runner.start(move |context| {
let build_genesis_stf = Arc::clone(&build_genesis_stf);
let build_stf = Arc::clone(&build_stf);
let build_codes = Arc::clone(&build_codes);
let run_genesis = Arc::clone(&run_genesis);
let build_storage = Arc::clone(&build_storage);
let rpc_config = runner_config.rpc.clone();
let chain_index_db_path = chain_index_db_path.clone();
let runner_mode = runner_config.runner_mode;
async move {
let context_for_shutdown = context.clone();
let context_for_archive = context.clone();
let storage = (build_storage)(context, storage_config)
.await
.expect("failed to create storage");
let codes = build_codes();
let (genesis_result, initial_height) = match load_chain_state::<G, _>(&storage) {
Some(state) => {
tracing::info!("Resuming from existing state at height {}", state.height);
tracing::info!("Genesis state: {:?}", state.genesis_result);
(state.genesis_result, state.height)
}
None => {
tracing::info!("No existing state found, running genesis...");
let bootstrap_stf = (build_genesis_stf)();
let output =
(run_genesis)(&bootstrap_stf, &codes, &storage).expect("genesis failed");
commit_genesis(&storage, output.changes, &output.genesis_result)
.await
.expect("genesis commit failed");
tracing::info!("Genesis complete. Result: {:?}", output.genesis_result);
(output.genesis_result, 1)
}
};
let stf = (build_stf)(&genesis_result);
let block_interval = configured_block_interval();
let max_txs_per_block = configured_max_txs_per_block();