-
Notifications
You must be signed in to change notification settings - Fork 992
/
Copy pathmod.rs
3010 lines (2767 loc) · 109 KB
/
mod.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
//! The ledger shell connects the ABCI++ interface with the Namada ledger app.
//!
//! Any changes applied before [`Shell::finalize_block`] might have to be
//! reverted, so any changes applied in the methods [`Shell::prepare_proposal`]
//! and [`Shell::process_proposal`] must be also reverted
//! (unless we can simply overwrite them in the next block).
//! More info in <https://github.com/anoma/namada/issues/362>.
pub mod block_alloc;
mod finalize_block;
mod init_chain;
pub use init_chain::InitChainValidation;
use namada_apps_lib::config::NodeLocalConfig;
use namada_sdk::state::StateRead;
use namada_vm::wasm::run::check_tx_allowed;
pub mod prepare_proposal;
use namada_sdk::ibc;
use namada_sdk::state::State;
pub mod process_proposal;
pub(super) mod queries;
mod snapshots;
mod stats;
#[cfg(any(test, feature = "testing"))]
#[allow(dead_code)]
pub mod testing;
mod vote_extensions;
use std::cell::RefCell;
use std::collections::BTreeSet;
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
#[allow(unused_imports)]
use std::rc::Rc;
use namada_apps_lib::wallet::{self, ValidatorData, ValidatorKeys};
use namada_sdk::address::Address;
use namada_sdk::borsh::{BorshDeserialize, BorshSerializeExt};
use namada_sdk::chain::{BlockHeight, ChainId};
use namada_sdk::eth_bridge::protocol::validation::bridge_pool_roots::validate_bp_roots_vext;
use namada_sdk::eth_bridge::protocol::validation::ethereum_events::validate_eth_events_vext;
use namada_sdk::eth_bridge::protocol::validation::validator_set_update::validate_valset_upd_vext;
use namada_sdk::eth_bridge::{EthBridgeQueries, EthereumOracleConfig};
use namada_sdk::ethereum_events::EthereumEvent;
use namada_sdk::events::log::EventLog;
use namada_sdk::gas::{Gas, TxGasMeter};
use namada_sdk::hash::Hash;
use namada_sdk::key::*;
use namada_sdk::migrations::ScheduledMigration;
use namada_sdk::parameters::{get_gas_scale, validate_tx_bytes};
use namada_sdk::proof_of_stake::storage::read_pos_params;
use namada_sdk::proof_of_stake::types::{
ConsensusValidator, ValidatorSetUpdate,
};
use namada_sdk::state::tx_queue::ExpiredTx;
use namada_sdk::state::{
DBIter, FullAccessState, Sha256Hasher, StorageHasher, StorageRead,
TempWlState, WlState, DB, EPOCH_SWITCH_BLOCKS_DELAY,
};
use namada_sdk::storage::{Key, TxIndex};
use namada_sdk::tendermint::AppHash;
use namada_sdk::time::DateTimeUtc;
pub use namada_sdk::tx::data::ResultCode;
use namada_sdk::tx::data::{TxType, WrapperTx};
use namada_sdk::tx::{Section, Tx};
use namada_sdk::{
eth_bridge, governance, hints, migrations, parameters, proof_of_stake,
token,
};
use namada_vm::wasm::{TxCache, VpCache};
use namada_vm::{WasmCacheAccess, WasmCacheRwAccess};
use namada_vote_ext::EthereumTxData;
use thiserror::Error;
use tokio::sync::mpsc::{Receiver, UnboundedSender};
use super::ethereum_oracle::{self as oracle, last_processed_block};
use crate::config::{self, genesis, TendermintMode, ValidatorLocalConfig};
use crate::protocol::ShellParams;
use crate::shims::abcipp_shim_types::shim;
use crate::shims::abcipp_shim_types::shim::response::TxResult;
use crate::shims::abcipp_shim_types::shim::TakeSnapshot;
use crate::tendermint::abci::{request, response};
use crate::tendermint::{self, validator};
use crate::tendermint_proto::crypto::public_key;
use crate::{protocol, storage, tendermint_node};
fn key_to_tendermint(
pk: &common::PublicKey,
) -> std::result::Result<public_key::Sum, ParsePublicKeyError> {
match pk {
common::PublicKey::Ed25519(_) => ed25519::PublicKey::try_from_pk(pk)
.map(|pk| public_key::Sum::Ed25519(pk.serialize_to_vec())),
common::PublicKey::Secp256k1(_) => {
secp256k1::PublicKey::try_from_pk(pk)
.map(|pk| public_key::Sum::Secp256k1(pk.serialize_to_vec()))
}
}
}
#[derive(Error, Debug)]
pub enum Error {
#[error("Error removing the DB data: {0}")]
RemoveDB(std::io::Error),
#[error("chain ID mismatch: {0}")]
ChainId(String),
#[error("Error decoding a transaction from bytes: {0}")]
TxDecoding(namada_sdk::tx::DecodeError),
#[error("Error trying to apply a transaction: {0}")]
TxApply(protocol::Error),
#[error("{0}")]
Tendermint(tendermint_node::Error),
#[error("{0}")]
Ethereum(super::ethereum_oracle::Error),
#[error("Server error: {0}")]
TowerServer(String),
#[error("{0}")]
Broadcaster(tokio::sync::mpsc::error::TryRecvError),
#[error("Error executing proposal {0}: {1}")]
BadProposal(u64, String),
#[error("Error reading wasm: {0:?}")]
ReadingWasm(#[from] eyre::Error),
#[error("Error loading wasm: {0}")]
LoadingWasm(String),
#[error("Error reading from or writing to storage: {0}")]
Storage(#[from] namada_sdk::state::Error),
#[error("Transaction replay attempt: {0}")]
ReplayAttempt(String),
#[error("Error with snapshots: {0}")]
Snapshot(std::io::Error),
#[error(
"Received a finalize request for a block that was rejected by process \
proposal"
)]
RejectedBlockProposal,
#[error("Received an invalid block proposal")]
InvalidBlockProposal,
}
impl From<Error> for TxResult {
fn from(err: Error) -> Self {
TxResult {
code: 1,
info: err.to_string(),
}
}
}
pub type ShellResult<T> = std::result::Result<T, Error>;
pub fn reset(config: config::Ledger) -> ShellResult<()> {
// simply nuke the DB files
let db_path = &config.db_dir();
match std::fs::remove_dir_all(db_path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
res => res.map_err(Error::RemoveDB)?,
};
// reset Tendermint state
tendermint_node::reset(config.cometbft_dir()).map_err(Error::Tendermint)?;
Ok(())
}
pub fn rollback(config: config::Ledger) -> ShellResult<()> {
// Rollback Tendermint state
tracing::info!("Rollback Tendermint state");
let tendermint_block_height =
tendermint_node::rollback(config.cometbft_dir())
.map_err(Error::Tendermint)?;
// Rollback Namada state
let db_path = config.shell.db_dir(&config.chain_id);
let mut db = storage::PersistentDB::open(db_path, None);
tracing::info!("Rollback Namada state");
db.rollback(tendermint_block_height)
.map_err(|e| Error::Storage(namada_sdk::state::Error::new(e)))
}
#[derive(Debug)]
#[allow(dead_code, clippy::large_enum_variant)]
pub(super) enum ShellMode {
Validator {
data: ValidatorData,
broadcast_sender: UnboundedSender<Vec<u8>>,
eth_oracle: Option<EthereumOracleChannels>,
validator_local_config: Option<ValidatorLocalConfig>,
local_config: Option<NodeLocalConfig>,
},
Full {
local_config: Option<NodeLocalConfig>,
},
Seed,
}
/// A channel for pulling events from the Ethereum oracle
/// and queueing them up for inclusion in vote extensions
#[derive(Debug)]
pub(super) struct EthereumReceiver {
channel: Receiver<EthereumEvent>,
queue: BTreeSet<EthereumEvent>,
}
impl EthereumReceiver {
/// Create a new [`EthereumReceiver`] from a channel connected
/// to an Ethereum oracle
pub fn new(channel: Receiver<EthereumEvent>) -> Self {
Self {
channel,
queue: BTreeSet::new(),
}
}
/// Pull Ethereum events from the oracle and queue them to
/// be voted on.
///
/// Since vote extensions require ordering of Ethereum
/// events, we do that here. We also de-duplicate events.
/// Events may be filtered out of the queue with a provided
/// predicate.
pub fn fill_queue<F>(&mut self, mut keep_event: F)
where
F: FnMut(&EthereumEvent) -> bool,
{
let mut new_events: usize = 0;
let mut filtered_events: usize = 0;
while let Ok(eth_event) = self.channel.try_recv() {
if keep_event(ð_event) && self.queue.insert(eth_event) {
new_events =
new_events.checked_add(1).expect("Cannot overflow");
} else {
filtered_events =
filtered_events.checked_add(1).expect("Cannot overflow");
}
}
if new_events
.checked_add(filtered_events)
.expect("Cannot overflow")
> 0
{
tracing::info!(
new_events,
filtered_events,
"received Ethereum events"
);
}
}
/// Get a copy of the queue
pub fn get_events(&self) -> Vec<EthereumEvent> {
self.queue.iter().cloned().collect()
}
/// Remove the given [`EthereumEvent`] from the queue, if present.
///
/// **INVARIANT:** This method preserves the sorting and de-duplication
/// of events in the queue.
pub fn remove_event(&mut self, event: &EthereumEvent) {
self.queue.remove(event);
}
}
impl ShellMode {
/// Get the validator address if ledger is in validator mode
pub fn get_validator_address(&self) -> Option<&Address> {
match &self {
ShellMode::Validator { data, .. } => Some(&data.address),
_ => None,
}
}
/// Remove an Ethereum event from the internal queue
pub fn dequeue_eth_event(&mut self, event: &EthereumEvent) {
if let ShellMode::Validator {
eth_oracle:
Some(EthereumOracleChannels {
ethereum_receiver, ..
}),
..
} = self
{
ethereum_receiver.remove_event(event);
}
}
/// Get the protocol keypair for this validator.
pub fn get_protocol_key(&self) -> Option<&common::SecretKey> {
match self {
ShellMode::Validator {
data:
ValidatorData {
keys:
ValidatorKeys {
protocol_keypair, ..
},
..
},
..
} => Some(protocol_keypair),
_ => None,
}
}
/// Get the Ethereum bridge keypair for this validator.
#[cfg_attr(not(test), allow(dead_code))]
pub fn get_eth_bridge_keypair(&self) -> Option<&common::SecretKey> {
match self {
ShellMode::Validator {
data:
ValidatorData {
keys:
ValidatorKeys {
eth_bridge_keypair, ..
},
..
},
..
} => Some(eth_bridge_keypair),
_ => None,
}
}
/// If this node is a validator, broadcast a tx
/// to the mempool using the broadcaster subprocess
pub fn broadcast(&self, data: Vec<u8>) {
if let Self::Validator {
broadcast_sender, ..
} = self
{
broadcast_sender
.send(data)
.expect("The broadcaster should be running for a validator");
}
}
}
#[derive(Clone, Debug, Default)]
pub enum MempoolTxType {
/// A transaction that has not been validated by this node before
#[default]
NewTransaction,
/// A transaction that has been validated at some previous level that may
/// need to be validated again
RecheckTransaction,
}
#[derive(Debug)]
pub struct SnapshotSync {
pub next_chunk: u64,
pub height: BlockHeight,
pub expected: Vec<Hash>,
pub strikes: u64,
pub snapshot: std::fs::File,
}
#[derive(Debug)]
pub struct Shell<D = storage::PersistentDB, H = Sha256Hasher>
where
D: DB + for<'iter> DBIter<'iter> + Sync + 'static,
H: StorageHasher + Sync + 'static,
{
/// The id of the current chain
pub chain_id: ChainId,
/// The persistent storage with write log
pub state: FullAccessState<D, H>,
/// Path to the base directory with DB data and configs
#[allow(dead_code)]
pub(crate) base_dir: PathBuf,
/// Path to the WASM directory for files used in the genesis block.
pub(super) wasm_dir: PathBuf,
/// Information about the running shell instance
pub(crate) mode: ShellMode,
/// VP WASM compilation cache
pub vp_wasm_cache: VpCache<WasmCacheRwAccess>,
/// Tx WASM compilation cache
pub tx_wasm_cache: TxCache<WasmCacheRwAccess>,
/// Taken from config `storage_read_past_height_limit`. When set, will
/// limit the how many block heights in the past can the storage be
/// queried for reading values.
storage_read_past_height_limit: Option<u64>,
/// Log of events emitted by `FinalizeBlock` ABCI calls.
event_log: EventLog,
/// A migration that can be scheduled at a given block height
pub scheduled_migration: Option<ScheduledMigration<D::Migrator>>,
/// When set, indicates after how many blocks a new snapshot
/// will be taken (counting from the first block)
pub blocks_between_snapshots: Option<NonZeroU64>,
/// Data for a node downloading and apply snapshots as part of
/// the fast sync protocol.
pub syncing: Option<SnapshotSync>,
}
/// Storage key filter to store the diffs into the storage. Return `false` for
/// keys whose diffs shouldn't be stored.
pub fn is_key_diff_storable(key: &namada_sdk::storage::Key) -> bool {
!(token::storage_key::is_masp_key(key)
&& *key != token::storage_key::masp_convert_anchor_key()
&& *key != token::storage_key::masp_token_map_key()
&& *key != token::storage_key::masp_assets_hash_key()
&& !token::storage_key::is_masp_commitment_anchor_key(key)
|| ibc::storage::is_ibc_counter_key(key)
|| proof_of_stake::storage_key::is_delegation_targets_key(key))
}
/// Channels for communicating with an Ethereum oracle.
#[derive(Debug)]
pub struct EthereumOracleChannels {
ethereum_receiver: EthereumReceiver,
control_sender: oracle::control::Sender,
last_processed_block_receiver: last_processed_block::Receiver,
}
impl EthereumOracleChannels {
pub fn new(
events_receiver: Receiver<EthereumEvent>,
control_sender: oracle::control::Sender,
last_processed_block_receiver: last_processed_block::Receiver,
) -> Self {
Self {
ethereum_receiver: EthereumReceiver::new(events_receiver),
control_sender,
last_processed_block_receiver,
}
}
}
impl Shell<crate::storage::PersistentDB, Sha256Hasher> {
/// Restore the database with data fetched from the State Sync protocol.
pub fn restore_database_from_state_sync(&mut self) {
let Some(syncing) = self.syncing.as_mut() else {
return;
};
let db_block_cache_size_bytes = {
let config = crate::config::Config::load(
&self.base_dir,
&self.chain_id,
None,
);
config.ledger.shell.block_cache_bytes.unwrap_or_else(|| {
use sysinfo::{RefreshKind, System, SystemExt};
let sys = System::new_with_specifics(
RefreshKind::new().with_memory(),
);
let available_memory_bytes = sys.available_memory();
available_memory_bytes / 3
})
};
let db_cache = rocksdb::Cache::new_lru_cache(
usize::try_from(db_block_cache_size_bytes).expect(
"`db_block_cache_size_bytes` must not exceed `usize::MAX`",
),
);
self.state
.db_mut()
.restore_from((&db_cache, &mut syncing.snapshot))
.expect("Failed to restore state from snapshot");
// rebuild the in-memory state
self.state.load_last_state();
}
}
impl<D, H> Shell<D, H>
where
D: DB + for<'iter> DBIter<'iter> + Sync + 'static,
H: StorageHasher + Sync + 'static,
{
/// Create a new shell from a path to a database and a chain id. Looks
/// up the database with this data and tries to load the last state.
#[allow(clippy::too_many_arguments)]
pub fn new(
config: config::Ledger,
wasm_dir: PathBuf,
broadcast_sender: UnboundedSender<Vec<u8>>,
eth_oracle: Option<EthereumOracleChannels>,
db_cache: Option<&D::Cache>,
scheduled_migration: Option<ScheduledMigration<D::Migrator>>,
vp_wasm_compilation_cache: u64,
tx_wasm_compilation_cache: u64,
) -> Self {
let chain_id = config.chain_id;
let db_path = config.shell.db_dir(&chain_id);
let base_dir = config.shell.base_dir;
let mode = config.shell.tendermint_mode;
let storage_read_past_height_limit =
config.shell.storage_read_past_height_limit;
if !Path::new(&base_dir).is_dir() {
std::fs::create_dir(&base_dir)
.expect("Creating directory for Namada should not fail");
}
// For tests, fuzzing and benches use hard-coded native token addr ...
#[cfg(any(test, fuzzing, feature = "benches"))]
let native_token = {
let chain_dir = base_dir.join(chain_id.as_str());
// Use genesis file only if it exists
if chain_dir
.join(genesis::templates::TOKENS_FILE_NAME)
.exists()
{
genesis::chain::Finalized::read_native_token(&chain_dir)
.expect("Missing genesis files")
} else {
namada_sdk::address::testing::nam()
}
};
// ... Otherwise, look it up from the genesis file
#[cfg(not(any(test, fuzzing, feature = "benches")))]
let native_token = {
let chain_dir = base_dir.join(chain_id.as_str());
genesis::chain::Finalized::read_native_token(&chain_dir)
.expect("Missing genesis files")
};
// load last state from storage
let state = FullAccessState::open(
db_path,
db_cache,
chain_id.clone(),
native_token,
config.shell.storage_read_past_height_limit,
is_key_diff_storable,
);
let vp_wasm_cache_dir =
base_dir.join(chain_id.as_str()).join("vp_wasm_cache");
let tx_wasm_cache_dir =
base_dir.join(chain_id.as_str()).join("tx_wasm_cache");
// load in keys and address from wallet if mode is set to `Validator`
let mode = match mode {
TendermintMode::Validator => {
#[cfg(not(any(test, fuzzing)))]
{
let wallet_path = &base_dir.join(chain_id.as_str());
tracing::debug!(
"Loading wallet from {}",
wallet_path.to_string_lossy()
);
let mut wallet = wallet::load(wallet_path)
.expect("Validator node must have a wallet");
let validator_local_config_path =
wallet_path.join("validator_local_config.toml");
let local_config_path =
wallet_path.join("local_config.toml");
let validator_local_config: Option<ValidatorLocalConfig> =
if Path::is_file(&validator_local_config_path) {
Some(
toml::from_slice(
&std::fs::read(validator_local_config_path)
.unwrap(),
)
.unwrap(),
)
} else {
None
};
let local_config: Option<NodeLocalConfig> =
if Path::is_file(&local_config_path) {
Some(
toml::from_slice(
&std::fs::read(local_config_path).unwrap(),
)
.unwrap(),
)
} else {
None
};
wallet
.take_validator_data()
.map(|data| ShellMode::Validator {
data,
broadcast_sender,
eth_oracle,
validator_local_config,
local_config,
})
.expect(
"Validator data should have been stored in the \
wallet",
)
}
#[cfg(any(test, fuzzing))]
{
let (protocol_keypair, eth_bridge_keypair) =
wallet::defaults::validator_keys();
ShellMode::Validator {
data: ValidatorData {
address: wallet::defaults::validator_address(),
keys: ValidatorKeys {
protocol_keypair,
eth_bridge_keypair,
},
},
broadcast_sender,
eth_oracle,
validator_local_config: None,
local_config: None,
}
}
}
TendermintMode::Full => {
#[cfg(not(test))]
{
let local_config_path = &base_dir
.join(chain_id.as_str())
.join("local_config.toml");
let local_config: Option<NodeLocalConfig> =
if Path::is_file(local_config_path) {
Some(
toml::from_slice(
&std::fs::read(local_config_path).unwrap(),
)
.unwrap(),
)
} else {
None
};
ShellMode::Full { local_config }
}
#[cfg(test)]
{
ShellMode::Full { local_config: None }
}
}
TendermintMode::Seed => ShellMode::Seed,
};
if let Some(schedule_migration) = scheduled_migration.as_ref() {
#[allow(clippy::disallowed_methods)]
let current = state.get_block_height().unwrap_or_default();
if schedule_migration.height < current {
panic!(
"Cannot schedule a migration earlier than the latest \
block height({})",
current
);
}
}
let mut shell = Self {
chain_id,
state,
base_dir,
wasm_dir,
mode,
vp_wasm_cache: VpCache::new(
vp_wasm_cache_dir,
usize::try_from(vp_wasm_compilation_cache).expect(
"`vp_wasm_compilation_cache` must not exceed `usize::MAX`",
),
),
tx_wasm_cache: TxCache::new(
tx_wasm_cache_dir,
usize::try_from(tx_wasm_compilation_cache).expect(
"`tx_wasm_compilation_cache` must not exceed `usize::MAX`",
),
),
storage_read_past_height_limit,
// TODO(namada#3237): config event log params
event_log: EventLog::default(),
scheduled_migration,
blocks_between_snapshots: config.shell.blocks_between_snapshots,
syncing: None,
};
shell.update_eth_oracle(&Default::default());
shell
}
/// Return a reference to the [`EventLog`].
#[inline]
pub fn event_log(&self) -> &EventLog {
&self.event_log
}
/// Return a mutable reference to the [`EventLog`].
#[inline]
pub fn event_log_mut(&mut self) -> &mut EventLog {
&mut self.event_log
}
/// Load the Merkle root hash and the height of the last committed block, if
/// any. This is returned when ABCI sends an `info` request.
pub fn last_state(&self) -> response::Info {
if crate::migrating_state().is_some() {
// When migrating state, return a height of 0, such
// that CometBFT calls InitChain and subsequently
// updates the apphash in its state.
return response::Info {
last_block_height: 0u32.into(),
..response::Info::default()
};
}
let mut response = response::Info {
last_block_height: tendermint::block::Height::from(0_u32),
..Default::default()
};
let result = self.state.in_mem().get_state();
match result {
Some((root, height)) => {
tracing::info!(
"Last state root hash: {}, height: {}",
root,
height
);
response.last_block_app_hash =
AppHash::try_from(root.0.to_vec())
.expect("expected a valid app hash");
response.last_block_height =
height.try_into().expect("Invalid block height");
}
None => {
tracing::info!(
"No state could be found, chain is not initialized"
);
}
};
response
}
/// Read the value for a storage key dropping any error
pub fn read_storage_key<T>(&self, key: &Key) -> Option<T>
where
T: Clone + BorshDeserialize,
{
let result = self.state.db_read(key);
match result {
Ok((bytes, _gas)) => match bytes {
Some(bytes) => match T::try_from_slice(&bytes) {
Ok(value) => Some(value),
Err(_) => None,
},
None => None,
},
Err(_) => None,
}
}
/// Read the bytes for a storage key dropping any error
pub fn read_storage_key_bytes(&self, key: &Key) -> Option<Vec<u8>> {
let result = self.state.db_read(key);
match result {
Ok((bytes, _gas)) => bytes,
Err(_) => None,
}
}
/// Get the next epoch for which we can request validator set changed
pub fn get_validator_set_update_epoch(
&self,
current_epoch: namada_sdk::chain::Epoch,
) -> namada_sdk::chain::Epoch {
if let Some(delay) = self.state.in_mem().update_epoch_blocks_delay {
if delay == EPOCH_SWITCH_BLOCKS_DELAY {
// If we're about to update validator sets for the
// upcoming epoch, we can still remove the validator
current_epoch.next()
} else {
// If we're waiting to switch to a new epoch, it's too
// late to update validator sets
// on the next epoch, so we need to
// wait for the one after.
current_epoch.next().next()
}
} else {
current_epoch.next()
}
}
/// Commit a block. Persist the application state and return the Merkle root
/// hash.
pub fn commit(&mut self) -> shim::Response {
self.bump_last_processed_eth_block();
self.state
.commit_block()
.expect("Encountered a storage error while committing a block");
let committed_height = self.state.in_mem().get_last_block_height();
migrations::commit(
self.state.db(),
committed_height,
&mut self.scheduled_migration,
);
let merkle_root = self.state.in_mem().merkle_root();
tracing::info!(
"Committed block hash: {merkle_root}, height: {committed_height}",
);
self.broadcast_queued_txs();
let take_snapshot = self.check_snapshot_required();
shim::Response::Commit(
response::Commit {
// NB: by passing 0, we forbid CometBFT from deleting
// data pertaining to past blocks
retain_height: tendermint::block::Height::from(0_u32),
// NB: current application hash
data: merkle_root.0.to_vec().into(),
},
take_snapshot,
)
}
/// Check if we have reached a block height at which we should take a
/// snapshot
fn check_snapshot_required(&self) -> TakeSnapshot {
let committed_height = self.state.in_mem().get_last_block_height();
let take_snapshot = match self.blocks_between_snapshots {
Some(b) => committed_height.0 % b == 0,
_ => false,
};
if take_snapshot {
self.state
.db()
.path()
.map(|p| (p, self.state.in_mem().get_last_block_height()))
.into()
} else {
TakeSnapshot::No
}
}
/// Updates the Ethereum oracle's last processed block.
#[inline]
fn bump_last_processed_eth_block(&mut self) {
if let ShellMode::Validator {
eth_oracle: Some(eth_oracle),
..
} = &self.mode
{
// update the oracle's last processed eth block
let last_processed_block = eth_oracle
.last_processed_block_receiver
.borrow()
.as_ref()
.cloned();
if let Some(eth_height) = last_processed_block {
tracing::info!(
"Ethereum oracle's most recently processed Ethereum block \
is {}",
eth_height
);
self.state.in_mem_mut().ethereum_height = Some(eth_height);
}
}
}
/// Empties all the ledger's queues of transactions to be broadcasted
/// via CometBFT's P2P network.
#[inline]
fn broadcast_queued_txs(&mut self) {
if let ShellMode::Validator { .. } = &self.mode {
self.broadcast_protocol_txs();
self.broadcast_expired_txs();
}
}
/// Broadcast any pending protocol transactions.
fn broadcast_protocol_txs(&mut self) {
use crate::shell::vote_extensions::iter_protocol_txs;
let ext = self.craft_extension();
let protocol_key = self
.mode
.get_protocol_key()
.expect("Validators should have protocol keys");
let protocol_txs = iter_protocol_txs(ext).map(|protocol_tx| {
protocol_tx
.sign(protocol_key, self.chain_id.clone())
.to_bytes()
});
for tx in protocol_txs {
self.mode.broadcast(tx);
}
}
/// Broadcast any expired transactions.
fn broadcast_expired_txs(&mut self) {
let eth_events = {
let mut events: Vec<_> = self
.state
.in_mem_mut()
.expired_txs_queue
.drain()
.map(|expired_tx| match expired_tx {
ExpiredTx::EthereumEvent(event) => event,
})
.collect();
events.sort();
events
};
if hints::likely(eth_events.is_empty()) {
// more often than not, there won't by any expired
// Ethereum events to retransmit
return;
}
if let Some(vote_extension) = self.sign_ethereum_events(eth_events) {
let protocol_key = self
.mode
.get_protocol_key()
.expect("Validators should have protocol keys");
let signed_tx = EthereumTxData::EthEventsVext(
namada_vote_ext::ethereum_events::SignedVext(vote_extension),
)
.sign(protocol_key, self.chain_id.clone())
.to_bytes();
self.mode.broadcast(signed_tx);
}
}
/// If a handle to an Ethereum oracle was provided to the [`Shell`], attempt
/// to send it an updated configuration, using a configuration
/// based on Ethereum bridge parameters in blockchain storage.
///
/// This method must be safe to call even before ABCI `InitChain` has been
/// called (i.e. when storage is empty), as we may want to do this check
/// every time the shell starts up (including the first time ever at which
/// time storage will be empty).
///
/// This method is also called during `FinalizeBlock` to update the oracle
/// if relevant storage changes have occurred. This includes deactivating
/// and reactivating the bridge.
fn update_eth_oracle(&mut self, changed_keys: &BTreeSet<Key>) {
if let ShellMode::Validator {
eth_oracle: Some(EthereumOracleChannels { control_sender, .. }),
..
} = &mut self.mode
{
// We *always* expect a value describing the status of the Ethereum
// bridge to be present under [`eth_bridge::storage::active_key`],
// once a chain has been initialized. We need to explicitly check if
// this key is present here because we may be starting up the shell
// for the first time ever, in which case the chain hasn't been
// initialized yet.
let has_key = self
.state
.has_key(ð_bridge::storage::active_key())
.expect(
"We should always be able to check whether a key exists \
in storage or not",
);
if !has_key {
tracing::debug!(
"Not starting oracle yet as storage has not been \
initialized"
);
return;
}
let Some(config) = EthereumOracleConfig::read(&self.state) else {
tracing::debug!(
"Not starting oracle as the Ethereum bridge config \
couldn't be found in storage"
);
return;
};
let active = if !self.state.ethbridge_queries().is_bridge_active() {
if !changed_keys.contains(ð_bridge::storage::active_key()) {
tracing::debug!(
"Not starting oracle as the Ethereum bridge is \
disabled"
);
return;
} else {
tracing::debug!(
"Disabling oracle as the bridge has been disabled"
);
false
}
} else {
true
};
let start_block = self
.state
.in_mem()
.ethereum_height
.clone()
.unwrap_or(config.eth_start_height);
tracing::info!(
?start_block,
"Found Ethereum height from which the Ethereum oracle should \
be updated"
);
let config = eth_bridge::oracle::config::Config {
min_confirmations: config.min_confirmations.into(),