-
Notifications
You must be signed in to change notification settings - Fork 992
/
Copy pathmod.rs
2367 lines (2202 loc) · 84.2 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>.
mod block_space_alloc;
mod finalize_block;
mod governance;
mod init_chain;
mod prepare_proposal;
mod process_proposal;
pub(super) mod queries;
mod stats;
mod vote_extensions;
use std::collections::{BTreeSet, HashSet};
use std::convert::{TryFrom, TryInto};
use std::mem;
use std::path::{Path, PathBuf};
#[allow(unused_imports)]
use std::rc::Rc;
use borsh::{BorshDeserialize, BorshSerialize};
use namada::core::ledger::eth_bridge;
use namada::ledger::eth_bridge::{EthBridgeQueries, EthereumBridgeConfig};
use namada::ledger::events::log::EventLog;
use namada::ledger::events::Event;
use namada::ledger::gas::BlockGasMeter;
use namada::ledger::pos::namada_proof_of_stake::types::{
ConsensusValidator, ValidatorSetUpdate,
};
use namada::ledger::protocol::ShellParams;
use namada::ledger::storage::write_log::WriteLog;
use namada::ledger::storage::{
DBIter, Sha256Hasher, Storage, StorageHasher, TempWlStorage, WlStorage, DB,
EPOCH_SWITCH_BLOCKS_DELAY,
};
use namada::ledger::storage_api::{self, StorageRead, StorageWrite};
use namada::ledger::{pos, protocol, replay_protection};
use namada::proof_of_stake::{self, process_slashes, read_pos_params, slash};
use namada::proto::{self, Section, Tx};
use namada::types::address::{masp, masp_tx_key, Address};
use namada::types::chain::ChainId;
use namada::types::ethereum_events::EthereumEvent;
use namada::types::internal::TxInQueue;
use namada::types::key::*;
use namada::types::storage::{BlockHeight, Key, TxIndex};
use namada::types::time::DateTimeUtc;
use namada::types::token::{self};
#[cfg(not(feature = "mainnet"))]
use namada::types::transaction::MIN_FEE;
use namada::types::transaction::{
hash_tx, verify_decrypted_correctly, AffineCurve, DecryptedTx,
EllipticCurve, PairingEngine, TxType,
};
use namada::types::{address, hash};
use namada::vm::wasm::{TxCache, VpCache};
use namada::vm::WasmCacheRwAccess;
use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::{FromPrimitive, ToPrimitive};
use thiserror::Error;
use tokio::sync::mpsc::{Receiver, UnboundedSender};
use super::ethereum_oracle::{self as oracle, last_processed_block};
use crate::config;
use crate::config::{genesis, TendermintMode};
use crate::facade::tendermint_proto::abci::{
Misbehavior as Evidence, MisbehaviorType as EvidenceType, ValidatorUpdate,
};
use crate::facade::tendermint_proto::crypto::public_key;
use crate::facade::tendermint_proto::google::protobuf::Timestamp;
use crate::facade::tower_abci::{request, response};
use crate::node::ledger::shims::abcipp_shim_types::shim;
use crate::node::ledger::shims::abcipp_shim_types::shim::response::TxResult;
use crate::node::ledger::{storage, tendermint_node};
#[cfg(feature = "dev")]
use crate::wallet;
#[allow(unused_imports)]
use crate::wallet::{ValidatorData, ValidatorKeys};
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.try_to_vec().unwrap())),
common::PublicKey::Secp256k1(_) => {
secp256k1::PublicKey::try_from_pk(pk)
.map(|pk| public_key::Sum::Secp256k1(pk.try_to_vec().unwrap()))
}
}
}
#[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(proto::Error),
#[error("Error trying to apply a transaction: {0}")]
TxApply(protocol::Error),
#[error("Gas limit exceeding while applying transactions in block")]
GasOverflow,
#[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}")]
StorageApi(#[from] storage_api::Error),
#[error("Transaction replay attempt: {0}")]
ReplayAttempt(String),
}
impl From<Error> for TxResult {
fn from(err: Error) -> Self {
TxResult {
code: 1,
info: err.to_string(),
}
}
}
/// The different error codes that the ledger may
/// send back to a client indicating the status
/// of their submitted tx
#[derive(Debug, Copy, Clone, FromPrimitive, ToPrimitive, PartialEq)]
pub enum ErrorCodes {
Ok = 0,
InvalidDecryptedChainId = 1,
ExpiredDecryptedTx = 2,
WasmRuntimeError = 3,
InvalidTx = 4,
InvalidSig = 5,
InvalidOrder = 6,
ExtraTxs = 7,
Undecryptable = 8,
AllocationError = 9,
ReplayTx = 10,
InvalidChainId = 11,
ExpiredTx = 12,
InvalidVoteExtension = 13,
}
impl ErrorCodes {
/// Checks if the given [`ErrorCodes`] value is a protocol level error,
/// that can be recovered from at the finalize block stage.
pub const fn is_recoverable(&self) -> bool {
use ErrorCodes::*;
// NOTE: pattern match on all `ErrorCodes` variants, in order
// to catch potential bugs when adding new codes
match self {
Ok
| InvalidDecryptedChainId
| ExpiredDecryptedTx
| WasmRuntimeError => true,
InvalidTx | InvalidSig | InvalidOrder | ExtraTxs
| Undecryptable | AllocationError | ReplayTx | InvalidChainId
| ExpiredTx | InvalidVoteExtension => false,
}
}
}
impl From<ErrorCodes> for u32 {
fn from(code: ErrorCodes) -> u32 {
code.to_u32().unwrap()
}
}
impl From<ErrorCodes> for String {
fn from(code: ErrorCodes) -> String {
u32::from(code).to_string()
}
}
pub type Result<T> = std::result::Result<T, Error>;
pub fn reset(config: config::Ledger) -> Result<()> {
// 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) -> Result<()> {
// 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::StorageApi(storage_api::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>,
},
Full,
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 messages from the channel and add to queue
/// Since vote extensions require ordering of ethereum
/// events, we do that here. We also de-duplicate events
pub fn fill_queue(&mut self) {
let mut new_events = 0;
while let Ok(eth_event) = self.channel.try_recv() {
if self.queue.insert(eth_event) {
new_events += 1;
};
}
if new_events > 0 {
tracing::info!(n = new_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
#[cfg_attr(feature = "abcipp", allow(dead_code))]
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 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
#[allow(dead_code)]
chain_id: ChainId,
/// The persistent storage with write log
pub(super) wl_storage: WlStorage<D, H>,
/// Gas meter for the current block
gas_meter: BlockGasMeter,
/// Byzantine validators given from ABCI++ `prepare_proposal` are stored in
/// this field. They will be slashed when we finalize the block.
byzantine_validators: Vec<Evidence>,
/// Path to the base directory with DB data and configs
#[allow(dead_code)]
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
#[allow(dead_code)]
mode: ShellMode,
/// VP WASM compilation cache
pub(super) vp_wasm_cache: VpCache<WasmCacheRwAccess>,
/// Tx WASM compilation cache
pub(super) 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>,
/// Proposal execution tracking
pub proposal_data: HashSet<u64>,
/// Log of events emitted by `FinalizeBlock` ABCI calls.
event_log: EventLog,
}
/// 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<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>,
vp_wasm_compilation_cache: u64,
tx_wasm_compilation_cache: u64,
native_token: Address,
) -> 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");
}
// load last state from storage
let mut storage = Storage::open(
db_path,
chain_id.clone(),
native_token,
db_cache,
config.shell.storage_read_past_height_limit,
);
storage
.load_last_state()
.map_err(|e| {
tracing::error!("Cannot load the last state from the DB {}", e);
})
.expect("PersistentStorage cannot be initialized");
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(feature = "dev"))]
{
let wallet_path = &base_dir.join(chain_id.as_str());
let genesis_path =
&base_dir.join(format!("{}.toml", chain_id.as_str()));
tracing::debug!(
"{}",
wallet_path.as_path().to_str().unwrap()
);
let mut wallet = crate::wallet::load_or_new_from_genesis(
wallet_path,
genesis::genesis_config::open_genesis_config(
genesis_path,
)
.unwrap(),
);
wallet
.take_validator_data()
.map(|data| ShellMode::Validator {
data: data.clone(),
broadcast_sender,
eth_oracle,
})
.expect(
"Validator data should have been stored in the \
wallet",
)
}
#[cfg(feature = "dev")]
{
let (protocol_keypair, eth_bridge_keypair, dkg_keypair) =
wallet::defaults::validator_keys();
ShellMode::Validator {
data: wallet::ValidatorData {
address: wallet::defaults::validator_address(),
keys: wallet::ValidatorKeys {
protocol_keypair,
eth_bridge_keypair,
dkg_keypair: Some(dkg_keypair),
},
},
broadcast_sender,
eth_oracle,
}
}
}
TendermintMode::Full => ShellMode::Full,
TendermintMode::Seed => ShellMode::Seed,
};
let wl_storage = WlStorage {
storage,
write_log: WriteLog::default(),
};
let mut shell = Self {
chain_id,
wl_storage,
gas_meter: BlockGasMeter::default(),
byzantine_validators: vec![],
base_dir,
wasm_dir,
mode,
vp_wasm_cache: VpCache::new(
vp_wasm_cache_dir,
vp_wasm_compilation_cache as usize,
),
tx_wasm_cache: TxCache::new(
tx_wasm_cache_dir,
tx_wasm_compilation_cache as usize,
),
storage_read_past_height_limit,
proposal_data: HashSet::new(),
// TODO: config event log params
event_log: EventLog::default(),
};
shell.update_eth_oracle();
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
}
/// Iterate over the wrapper txs in order
#[allow(dead_code)]
fn iter_tx_queue(&mut self) -> impl Iterator<Item = &TxInQueue> {
self.wl_storage.storage.tx_queue.iter()
}
/// 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(&mut self) -> response::Info {
let mut response = response::Info::default();
let result = self.wl_storage.storage.get_state();
match result {
Some((root, height)) => {
tracing::info!(
"Last state root hash: {}, height: {}",
root,
height
);
response.last_block_app_hash = root.0.to_vec();
response.last_block_height =
height.try_into().expect("Invalid block height");
}
None => {
tracing::info!(
"No state could be found, chain is not initialized"
);
}
};
response
}
/// Takes the optional tendermint timestamp of the block: if it's Some than
/// converts it to a [`DateTimeUtc`], otherwise retrieve from self the
/// time of the last block committed
pub fn get_block_timestamp(
&self,
tendermint_block_time: Option<Timestamp>,
) -> DateTimeUtc {
if let Some(t) = tendermint_block_time {
if let Ok(t) = t.try_into() {
return t;
}
}
// Default to last committed block time
self.wl_storage
.storage
.get_last_block_timestamp()
.expect("Failed to retrieve last block timestamp")
}
/// 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.wl_storage.storage.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.wl_storage.storage.read(key);
match result {
Ok((bytes, _gas)) => bytes,
Err(_) => None,
}
}
/// Apply PoS slashes from the evidence
fn record_slashes_from_evidence(&mut self) {
if !self.byzantine_validators.is_empty() {
let byzantine_validators =
mem::take(&mut self.byzantine_validators);
// TODO: resolve this unwrap() better
let pos_params = read_pos_params(&self.wl_storage).unwrap();
let current_epoch = self.wl_storage.storage.block.epoch;
for evidence in byzantine_validators {
// dbg!(&evidence);
tracing::info!("Processing evidence {evidence:?}.");
let evidence_height = match u64::try_from(evidence.height) {
Ok(height) => height,
Err(err) => {
tracing::error!(
"Unexpected evidence block height {}",
err
);
continue;
}
};
let evidence_epoch = match self
.wl_storage
.storage
.block
.pred_epochs
.get_epoch(BlockHeight(evidence_height))
{
Some(epoch) => epoch,
None => {
tracing::error!(
"Couldn't find epoch for evidence block height {}",
evidence_height
);
continue;
}
};
// Disregard evidences that should have already been processed
// at this time
if evidence_epoch + pos_params.slash_processing_epoch_offset()
- pos_params.cubic_slashing_window_length
<= current_epoch
{
tracing::info!(
"Skipping outdated evidence from epoch \
{evidence_epoch}"
);
continue;
}
let slash_type = match EvidenceType::from_i32(evidence.r#type) {
Some(r#type) => match r#type {
EvidenceType::DuplicateVote => {
pos::types::SlashType::DuplicateVote
}
EvidenceType::LightClientAttack => {
pos::types::SlashType::LightClientAttack
}
EvidenceType::Unknown => {
tracing::error!(
"Unknown evidence: {:#?}",
evidence
);
continue;
}
},
None => {
tracing::error!(
"Unexpected evidence type {}",
evidence.r#type
);
continue;
}
};
let validator_raw_hash = match evidence.validator {
Some(validator) => tm_raw_hash_to_string(validator.address),
None => {
tracing::error!(
"Evidence without a validator {:#?}",
evidence
);
continue;
}
};
let validator =
match proof_of_stake::find_validator_by_raw_hash(
&self.wl_storage,
&validator_raw_hash,
)
.expect("Must be able to read storage")
{
Some(validator) => validator,
None => {
tracing::error!(
"Cannot find validator's address from raw \
hash {}",
validator_raw_hash
);
continue;
}
};
// Check if we're gonna switch to a new epoch after a delay
let validator_set_update_epoch = if let Some(delay) =
self.wl_storage.storage.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()
};
tracing::info!(
"Slashing {} for {} in epoch {}, block height {} (current \
epoch = {}, validator set update epoch = \
{validator_set_update_epoch})",
validator,
slash_type,
evidence_epoch,
evidence_height,
current_epoch
);
if let Err(err) = slash(
&mut self.wl_storage,
&pos_params,
current_epoch,
evidence_epoch,
evidence_height,
slash_type,
&validator,
validator_set_update_epoch,
) {
tracing::error!("Error in slashing: {}", err);
}
}
}
}
/// Process and apply slashes that have already been recorded for the
/// current epoch
fn process_slashes(&mut self) {
let current_epoch = self.wl_storage.storage.block.epoch;
if let Err(err) = process_slashes(&mut self.wl_storage, current_epoch) {
tracing::error!(
"Error while processing slashes queued for epoch {}: {}",
current_epoch,
err
);
}
}
/// Commit a block. Persist the application state and return the Merkle root
/// hash.
pub fn commit(&mut self) -> response::Commit {
let mut response = response::Commit::default();
// commit block's data from write log and store the in DB
self.wl_storage.commit_block().unwrap_or_else(|e| {
tracing::error!(
"Encountered a storage error while committing a block {:?}",
e
)
});
// NOTE: the oracle isn't started through governance votes, so we don't
// check to see if we need to start it after epoch transitions
let root = self.wl_storage.storage.merkle_root();
tracing::info!(
"Committed block hash: {}, height: {}",
root,
self.wl_storage.storage.get_last_block_height(),
);
response.data = root.0.to_vec();
if let ShellMode::Validator {
eth_oracle: Some(eth_oracle),
..
} = &self.mode
{
let last_processed_block = eth_oracle
.last_processed_block_receiver
.borrow()
.as_ref()
.cloned();
match last_processed_block {
Some(eth_height) => {
tracing::info!(
"Ethereum oracle's most recently processed Ethereum \
block is {}",
eth_height
);
self.wl_storage.storage.ethereum_height = Some(eth_height);
}
None => tracing::info!(
"Ethereum oracle has not yet fully processed any Ethereum \
blocks"
),
}
}
#[cfg(not(feature = "abcipp"))]
{
use crate::node::ledger::shell::vote_extensions::iter_protocol_txs;
if let ShellMode::Validator { .. } = &self.mode {
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);
}
}
}
response
}
/// Checks that neither the wrapper nor the inner transaction have already
/// been applied. Requires a [`TempWlStorage`] to perform the check during
/// block construction and validation
pub fn replay_protection_checks(
&self,
wrapper: &Tx,
tx_bytes: &[u8],
temp_wl_storage: &mut TempWlStorage<D, H>,
) -> Result<()> {
let inner_tx_hash =
wrapper.clone().update_header(TxType::Raw).header_hash();
let inner_hash_key = replay_protection::get_tx_hash_key(&inner_tx_hash);
if temp_wl_storage
.has_key(&inner_hash_key)
.expect("Error while checking inner tx hash key in storage")
{
return Err(Error::ReplayAttempt(format!(
"Inner transaction hash {} already in storage",
&inner_tx_hash,
)));
}
// Write inner hash to WAL
temp_wl_storage
.write(&inner_hash_key, ())
.expect("Couldn't write inner transaction hash to write log");
let tx =
Tx::try_from(tx_bytes).expect("Deserialization shouldn't fail");
let wrapper_hash = tx.header_hash();
let wrapper_hash_key =
replay_protection::get_tx_hash_key(&wrapper_hash);
if temp_wl_storage
.has_key(&wrapper_hash_key)
.expect("Error while checking wrapper tx hash key in storage")
{
return Err(Error::ReplayAttempt(format!(
"Wrapper transaction hash {} already in storage",
wrapper_hash
)));
}
// Write wrapper hash to WAL
temp_wl_storage
.write(&wrapper_hash_key, ())
.expect("Couldn't write wrapper tx hash to write log");
Ok(())
}
/// If a handle to an Ethereum oracle was provided to the [`Shell`], attempt
/// to send it an updated configuration, using an initial 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).
fn update_eth_oracle(&mut self) {
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
.wl_storage
.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::info!(
"Not starting oracle yet as storage has not been \
initialized"
);
return;
}
if !self.wl_storage.ethbridge_queries().is_bridge_active() {
tracing::info!(
"Not starting oracle as the Ethereum bridge is disabled"
);
return;
}
let Some(config) = EthereumBridgeConfig::read(&self.wl_storage) else {
tracing::info!(
"Not starting oracle as the Ethereum bridge config couldn't be found in storage"
);
return;
};
let start_block = self
.wl_storage
.storage
.ethereum_height
.clone()
.unwrap_or_else(|| {
self.wl_storage
.read(ð_bridge::storage::eth_start_height_key())
.expect(
"Failed to read Ethereum start height from storage",
)
.expect(
"The Ethereum start height should be in storage",
)
});
tracing::info!(
?start_block,
"Found Ethereum height from which the Ethereum oracle should \
start"
);
let config = namada::eth_bridge::oracle::config::Config {
min_confirmations: config.min_confirmations.into(),
bridge_contract: config.contracts.bridge.address,
governance_contract: config.contracts.governance.address,
start_block,
};
tracing::info!(
?config,
"Starting the Ethereum oracle using values from block storage"