-
Notifications
You must be signed in to change notification settings - Fork 992
/
Copy pathfinalize_block.rs
3958 lines (3666 loc) · 147 KB
/
finalize_block.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
//! Implementation of the `FinalizeBlock` ABCI++ method for the Shell
use std::collections::HashMap;
use data_encoding::HEXUPPER;
use namada::core::ledger::pgf::ADDRESS as pgf_address;
use namada::ledger::events::EventType;
use namada::ledger::gas::{GasMetering, TxGasMeter};
use namada::ledger::parameters::storage as params_storage;
use namada::ledger::pos::{namada_proof_of_stake, staking_token_address};
use namada::ledger::storage::EPOCH_SWITCH_BLOCKS_DELAY;
use namada::ledger::storage_api::token::credit_tokens;
use namada::ledger::storage_api::{pgf, StorageRead, StorageWrite};
use namada::ledger::{inflation, protocol, replay_protection};
use namada::proof_of_stake::{
delegator_rewards_products_handle, find_validator_by_raw_hash,
read_last_block_proposer_address, read_pos_params, read_total_stake,
read_validator_stake, rewards_accumulator_handle,
validator_commission_rate_handle, validator_rewards_products_handle,
write_last_block_proposer_address,
};
use namada::types::address::Address;
use namada::types::dec::Dec;
use namada::types::key::tm_raw_hash_to_string;
use namada::types::storage::{BlockHash, BlockResults, Epoch, Header};
use namada::types::token::Amount;
use namada::types::transaction::protocol::{
ethereum_tx_data_variants, ProtocolTxType,
};
use namada::types::vote_extensions::ethereum_events::MultiSignedEthEvent;
use super::governance::execute_governance_proposals;
use super::*;
use crate::facade::tendermint_proto::abci::{
Misbehavior as Evidence, VoteInfo,
};
use crate::node::ledger::shell::stats::InternalStats;
impl<D, H> Shell<D, H>
where
D: DB + for<'iter> DBIter<'iter> + Sync + 'static,
H: StorageHasher + Sync + 'static,
{
/// Updates the chain with new header, height, etc. Also keeps track
/// of epoch changes and applies associated updates to validator sets,
/// etc. as necessary.
///
/// Validate and apply decrypted transactions unless
/// [`Shell::process_proposal`] detected that they were not submitted in
/// correct order or more decrypted txs arrived than expected. In that
/// case, all decrypted transactions are not applied and must be
/// included in the next `Shell::prepare_proposal` call.
///
/// Incoming wrapper txs need no further validation. They
/// are added to the block.
///
/// Error codes:
/// 0: Ok
/// 1: Invalid tx
/// 2: Tx is invalidly signed
/// 3: Wasm runtime error
/// 4: Invalid order of decrypted txs
/// 5. More decrypted txs than expected
pub fn finalize_block(
&mut self,
req: shim::request::FinalizeBlock,
) -> Result<shim::response::FinalizeBlock> {
let mut response = shim::response::FinalizeBlock::default();
// Begin the new block and check if a new epoch has begun
let (height, new_epoch) =
self.update_state(req.header, req.hash, req.byzantine_validators);
let (current_epoch, _gas) = self.wl_storage.storage.get_current_epoch();
let update_for_tendermint = matches!(
self.wl_storage.storage.update_epoch_blocks_delay,
Some(EPOCH_SWITCH_BLOCKS_DELAY)
);
tracing::info!(
"Block height: {height}, epoch: {current_epoch}, is new epoch: \
{new_epoch}."
);
tracing::debug!(
"New epoch block delay for updating the Tendermint validator set: \
{:?}",
self.wl_storage.storage.update_epoch_blocks_delay
);
if new_epoch {
namada::ledger::storage::update_allowed_conversions(
&mut self.wl_storage,
)?;
execute_governance_proposals(self, &mut response)?;
// Copy the new_epoch + pipeline_len - 1 validator set into
// new_epoch + pipeline_len
let pos_params =
namada_proof_of_stake::read_pos_params(&self.wl_storage)?;
namada_proof_of_stake::copy_validator_sets_and_positions(
&mut self.wl_storage,
current_epoch,
current_epoch + pos_params.pipeline_len,
)?;
namada_proof_of_stake::store_total_consensus_stake(
&mut self.wl_storage,
current_epoch,
)?;
namada_proof_of_stake::purge_validator_sets_for_old_epoch(
&mut self.wl_storage,
current_epoch,
)?;
}
// Invariant: Has to be applied before `record_slashes_from_evidence`
// because it potentially needs to be able to read validator state from
// previous epoch and jailing validator removes the historical state
self.log_block_rewards(&req.votes, height, current_epoch, new_epoch)?;
if new_epoch {
self.apply_inflation(current_epoch)?;
}
// Invariant: This has to be applied after
// `copy_validator_sets_and_positions` and before `self.update_epoch`.
self.record_slashes_from_evidence();
// Invariant: This has to be applied after
// `copy_validator_sets_and_positions` if we're starting a new epoch
if new_epoch {
self.process_slashes();
}
let mut stats = InternalStats::default();
let native_block_proposer_address = {
let tm_raw_hash_string =
tm_raw_hash_to_string(req.proposer_address);
find_validator_by_raw_hash(&self.wl_storage, tm_raw_hash_string)
.unwrap()
.expect(
"Unable to find native validator address of block \
proposer from tendermint raw hash",
)
};
// Tracks the accepted transactions
self.wl_storage.storage.block.results = BlockResults::default();
for (tx_index, processed_tx) in req.txs.iter().enumerate() {
let tx = if let Ok(tx) = Tx::try_from(processed_tx.tx.as_ref()) {
tx
} else {
tracing::error!(
"FinalizeBlock received a tx that could not be \
deserialized to a Tx type. This is likely a protocol \
transaction."
);
continue;
};
// If [`process_proposal`] rejected a Tx due to invalid signature,
// emit an event here and move on to next tx.
if ErrorCodes::from_u32(processed_tx.result.code).unwrap()
== ErrorCodes::InvalidSig
{
let mut tx_event = match tx.header().tx_type {
TxType::Wrapper(_) | TxType::Protocol(_) => {
Event::new_tx_event(&tx, height.0)
}
_ => {
tracing::error!(
"Internal logic error: FinalizeBlock received a \
tx with an invalid signature error code that \
could not be deserialized to a WrapperTx / \
ProtocolTx type"
);
continue;
}
};
tx_event["code"] = processed_tx.result.code.to_string();
tx_event["info"] =
format!("Tx rejected: {}", &processed_tx.result.info);
tx_event["gas_used"] = "0".into();
response.events.push(tx_event);
continue;
}
if tx.validate_tx().is_err() {
tracing::error!(
"Internal logic error: FinalizeBlock received tx that \
could not be deserialized to a valid TxType"
);
continue;
};
let tx_header = tx.header();
// If [`process_proposal`] rejected a Tx, emit an event here and
// move on to next tx
if ErrorCodes::from_u32(processed_tx.result.code).unwrap()
!= ErrorCodes::Ok
{
let mut tx_event = Event::new_tx_event(&tx, height.0);
tx_event["code"] = processed_tx.result.code.to_string();
tx_event["info"] =
format!("Tx rejected: {}", &processed_tx.result.info);
tx_event["gas_used"] = "0".into();
response.events.push(tx_event);
// if the rejected tx was decrypted, remove it
// from the queue of txs to be processed and remove the hash
// from storage
if let TxType::Decrypted(_) = &tx_header.tx_type {
let tx_hash = self
.wl_storage
.storage
.tx_queue
.pop()
.expect("Missing wrapper tx in queue")
.tx
.clone()
.update_header(TxType::Raw)
.header_hash();
let tx_hash_key =
replay_protection::get_replay_protection_key(&tx_hash);
self.wl_storage
.delete(&tx_hash_key)
.expect("Error while deleting tx hash from storage");
}
#[cfg(not(any(feature = "abciplus", feature = "abcipp")))]
if let TxType::Wrapper(wrapper) = &tx_header.tx_type {
// Charge fee if wrapper transaction went out of gas or
// failed because of fees
let error_code =
ErrorCodes::from_u32(processed_tx.result.code).unwrap();
if (error_code == ErrorCodes::TxGasLimit)
| (error_code == ErrorCodes::FeeError)
{
let masp_transaction = wrapper
.unshield_section_hash
.map(|ref hash| {
tx.get_section(hash)
.map(|section| {
if let Section::MaspTx(transaction) =
section
{
Some(transaction.to_owned())
} else {
None
}
})
.flatten()
})
.flatten();
if let Err(msg) = protocol::charge_fee(
wrapper,
masp_transaction,
ShellParams::new(
TxGasMeter::new_from_sub_limit(u64::MAX),
&mut self.wl_storage,
&mut self.vp_wasm_cache,
&mut self.tx_wasm_cache,
),
Some(&native_block_proposer_address),
&mut BTreeSet::default(),
) {
self.wl_storage.write_log.drop_tx();
tracing::error!(
"Rejected wrapper tx {} could not pay fee: {}",
Hash::sha256(
tx::try_from(processed_tx.as_ref())
.unwrap()
),
msg
)
}
}
}
continue;
}
let (mut tx_event, tx_unsigned_hash, mut tx_gas_meter, wrapper) =
match &tx_header.tx_type {
TxType::Wrapper(wrapper) => {
stats.increment_wrapper_txs();
let tx_event = Event::new_tx_event(&tx, height.0);
let gas_meter = TxGasMeter::new(wrapper.gas_limit);
(tx_event, None, gas_meter, Some(tx.clone()))
}
TxType::Decrypted(inner) => {
// We remove the corresponding wrapper tx from the queue
let mut tx_in_queue = self
.wl_storage
.storage
.tx_queue
.pop()
.expect("Missing wrapper tx in queue");
let mut event = Event::new_tx_event(&tx, height.0);
match inner {
DecryptedTx::Decrypted => {
if let Some(code_sec) = tx
.get_section(tx.code_sechash())
.and_then(|x| Section::code_sec(x.as_ref()))
{
stats.increment_tx_type(
code_sec.code.hash().to_string(),
);
}
}
DecryptedTx::Undecryptable => {
tracing::info!(
"Tx with hash {} was un-decryptable",
tx_in_queue.tx.header_hash()
);
event["info"] =
"Transaction is invalid.".into();
event["log"] = "Transaction could not be \
decrypted."
.into();
event["code"] =
ErrorCodes::Undecryptable.into();
continue;
}
}
(
event,
Some(
tx_in_queue
.tx
.update_header(TxType::Raw)
.header_hash(),
),
TxGasMeter::new_from_sub_limit(tx_in_queue.gas),
None,
)
}
TxType::Raw => {
tracing::error!(
"Internal logic error: FinalizeBlock received a \
TxType::Raw transaction"
);
continue;
}
TxType::Protocol(protocol_tx) => match protocol_tx.tx {
ProtocolTxType::BridgePoolVext
| ProtocolTxType::BridgePool
| ProtocolTxType::ValSetUpdateVext
| ProtocolTxType::ValidatorSetUpdate => (
Event::new_tx_event(&tx, height.0),
None,
TxGasMeter::new_from_sub_limit(0.into()),
None,
),
ProtocolTxType::EthEventsVext => {
let ext =
ethereum_tx_data_variants::EthEventsVext::try_from(
&tx,
)
.unwrap();
if self
.mode
.get_validator_address()
.map(|validator| {
validator == &ext.data.validator_addr
})
.unwrap_or(false)
{
for event in ext.data.ethereum_events.iter() {
self.mode.dequeue_eth_event(event);
}
}
(
Event::new_tx_event(&tx, height.0),
None,
TxGasMeter::new_from_sub_limit(0.into()),
None,
)
}
ProtocolTxType::EthereumEvents => {
let digest =
ethereum_tx_data_variants::EthereumEvents::try_from(
&tx,
).unwrap();
if let Some(address) =
self.mode.get_validator_address().cloned()
{
let this_signer = &(
address,
self.wl_storage
.storage
.get_last_block_height(),
);
for MultiSignedEthEvent { event, signers } in
&digest.events
{
if signers.contains(this_signer) {
self.mode.dequeue_eth_event(event);
}
}
}
(
Event::new_tx_event(&tx, height.0),
None,
TxGasMeter::new_from_sub_limit(0.into()),
None,
)
}
ref protocol_tx_type => {
tracing::error!(
?protocol_tx_type,
"Internal logic error: FinalizeBlock received \
an unsupported TxType::Protocol transaction: \
{:?}",
protocol_tx
);
continue;
}
},
};
match protocol::dispatch_tx(
tx,
processed_tx.tx.as_ref(),
TxIndex(
tx_index
.try_into()
.expect("transaction index out of bounds"),
),
&mut tx_gas_meter,
&mut self.wl_storage,
&mut self.vp_wasm_cache,
&mut self.tx_wasm_cache,
Some(&native_block_proposer_address),
)
.map_err(Error::TxApply)
{
Ok(result) => {
if result.is_accepted() {
if let EventType::Accepted = tx_event.event_type {
// Wrapper transaction
tracing::trace!(
"Wrapper transaction {} was accepted",
tx_event["hash"]
);
self.wl_storage.storage.tx_queue.push(TxInQueue {
tx: wrapper.expect("Missing expected wrapper"),
gas: tx_gas_meter.get_available_gas(),
});
} else {
tracing::trace!(
"all VPs accepted transaction {} storage \
modification {:#?}",
tx_event["hash"],
result
);
stats.increment_successful_txs();
}
self.wl_storage.commit_tx();
if !tx_event.contains_key("code") {
tx_event["code"] = ErrorCodes::Ok.into();
self.wl_storage
.storage
.block
.results
.accept(tx_index);
}
for ibc_event in &result.ibc_events {
// Add the IBC event besides the tx_event
let mut event = Event::from(ibc_event.clone());
// Add the height for IBC event query
event["height"] = height.to_string();
response.events.push(event);
}
match serde_json::to_string(
&result.initialized_accounts,
) {
Ok(initialized_accounts) => {
tx_event["initialized_accounts"] =
initialized_accounts;
}
Err(err) => {
tracing::error!(
"Failed to serialize the initialized \
accounts: {}",
err
);
}
}
} else {
tracing::trace!(
"some VPs rejected transaction {} storage \
modification {:#?}",
tx_event["hash"],
result.vps_result.rejected_vps
);
stats.increment_rejected_txs();
self.wl_storage.drop_tx();
tx_event["code"] = ErrorCodes::InvalidTx.into();
}
tx_event["gas_used"] = result.gas_used.to_string();
tx_event["info"] = result.to_string();
}
Err(msg) => {
tracing::info!(
"Transaction {} failed with: {}",
tx_event["hash"],
msg
);
stats.increment_errored_txs();
self.wl_storage.drop_tx();
// If transaction type is Decrypted and failed because of
// out of gas, remove its hash from storage to allow
// rewrapping it
if let Some(hash) = tx_unsigned_hash {
if let Error::TxApply(protocol::Error::GasError(_)) =
msg
{
let tx_hash_key =
replay_protection::get_replay_protection_key(
&hash,
);
self.wl_storage.delete(&tx_hash_key).expect(
"Error while deleting tx hash key from storage",
);
}
}
tx_event["gas_used"] =
tx_gas_meter.get_tx_consumed_gas().to_string();
tx_event["info"] = msg.to_string();
if let EventType::Accepted = tx_event.event_type {
// If wrapper, invalid tx error code
tx_event["code"] = ErrorCodes::InvalidTx.into();
} else {
tx_event["code"] = ErrorCodes::WasmRuntimeError.into();
}
}
}
response.events.push(tx_event);
}
stats.set_tx_cache_size(
self.tx_wasm_cache.get_size(),
self.tx_wasm_cache.get_cache_size(),
);
stats.set_vp_cache_size(
self.vp_wasm_cache.get_size(),
self.vp_wasm_cache.get_cache_size(),
);
tracing::info!("{}", stats);
tracing::info!("{}", stats.format_tx_executed());
if update_for_tendermint {
self.update_epoch(&mut response);
// send the latest oracle configs. These may have changed due to
// governance.
self.update_eth_oracle();
}
write_last_block_proposer_address(
&mut self.wl_storage,
native_block_proposer_address,
)?;
self.event_log_mut().log_events(response.events.clone());
tracing::debug!("End finalize_block {height} of epoch {current_epoch}");
Ok(response)
}
/// Sets the metadata necessary for a new block, including
/// the hash, height, validator changes, and evidence of
/// byzantine behavior. Applies slashes if necessary.
/// Returns a bool indicating if a new epoch began and
/// the height of the new block.
fn update_state(
&mut self,
header: Header,
hash: BlockHash,
byzantine_validators: Vec<Evidence>,
) -> (BlockHeight, bool) {
let height = self.wl_storage.storage.get_last_block_height() + 1;
self.wl_storage
.storage
.begin_block(hash, height)
.expect("Beginning a block shouldn't fail");
let header_time = header.time;
self.wl_storage
.storage
.set_header(header)
.expect("Setting a header shouldn't fail");
self.byzantine_validators = byzantine_validators;
let new_epoch = self
.wl_storage
.update_epoch(height, header_time)
.expect("Must be able to update epoch");
(height, new_epoch)
}
/// If a new epoch begins, we update the response to include
/// changes to the validator sets and consensus parameters
fn update_epoch(&mut self, response: &mut shim::response::FinalizeBlock) {
// Apply validator set update
response.validator_updates = self
.get_abci_validator_updates(false)
.expect("Must be able to update validator set");
}
/// Calculate the new inflation rate, mint the new tokens to the PoS
/// account, then update the reward products of the validators. This is
/// executed while finalizing the first block of a new epoch and is applied
/// with respect to the previous epoch.
fn apply_inflation(&mut self, current_epoch: Epoch) -> Result<()> {
let last_epoch = current_epoch.prev();
// Get input values needed for the PD controller for PoS and MASP.
// Run the PD controllers to calculate new rates.
//
// MASP is included below just for some completeness.
let params = read_pos_params(&self.wl_storage)?;
// Read from Parameters storage
let epochs_per_year: u64 = self
.read_storage_key(¶ms_storage::get_epochs_per_year_key())
.expect("Epochs per year should exist in storage");
let pos_p_gain_nom: Dec = self
.read_storage_key(¶ms_storage::get_pos_gain_p_key())
.expect("PoS P-gain factor should exist in storage");
let pos_d_gain_nom: Dec = self
.read_storage_key(¶ms_storage::get_pos_gain_d_key())
.expect("PoS D-gain factor should exist in storage");
let pos_last_staked_ratio: Dec = self
.read_storage_key(¶ms_storage::get_staked_ratio_key())
.expect("PoS staked ratio should exist in storage");
let pos_last_inflation_amount: token::Amount = self
.read_storage_key(¶ms_storage::get_pos_inflation_amount_key())
.expect("PoS inflation amount should exist in storage");
// Read from PoS storage
let total_tokens = self
.read_storage_key(&token::minted_balance_key(
&staking_token_address(&self.wl_storage),
))
.expect("Total NAM balance should exist in storage");
let pos_locked_supply =
read_total_stake(&self.wl_storage, ¶ms, last_epoch)?;
let pos_locked_ratio_target = params.target_staked_ratio;
let pos_max_inflation_rate = params.max_inflation_rate;
// TODO: properly fetch these values (arbitrary for now)
let masp_locked_supply: Amount = Amount::default();
let masp_locked_ratio_target = Dec::new(5, 1).expect("Cannot fail");
let masp_locked_ratio_last = Dec::new(5, 1).expect("Cannot fail");
let masp_max_inflation_rate = Dec::new(2, 1).expect("Cannot fail");
let masp_last_inflation_rate = Dec::new(12, 2).expect("Cannot fail");
let masp_p_gain = Dec::new(1, 1).expect("Cannot fail");
let masp_d_gain = Dec::new(1, 1).expect("Cannot fail");
// Run rewards PD controller
let pos_controller = inflation::RewardsController {
locked_tokens: pos_locked_supply,
total_tokens,
locked_ratio_target: pos_locked_ratio_target,
locked_ratio_last: pos_last_staked_ratio,
max_reward_rate: pos_max_inflation_rate,
last_inflation_amount: pos_last_inflation_amount,
p_gain_nom: pos_p_gain_nom,
d_gain_nom: pos_d_gain_nom,
epochs_per_year,
};
let _masp_controller = inflation::RewardsController {
locked_tokens: masp_locked_supply,
total_tokens,
locked_ratio_target: masp_locked_ratio_target,
locked_ratio_last: masp_locked_ratio_last,
max_reward_rate: masp_max_inflation_rate,
last_inflation_amount: token::Amount::from(
masp_last_inflation_rate,
),
p_gain_nom: masp_p_gain,
d_gain_nom: masp_d_gain,
epochs_per_year,
};
// Run the rewards controllers
let inflation::ValsToUpdate {
locked_ratio,
inflation,
} = pos_controller.run();
// let new_masp_vals = _masp_controller.run();
// Get the number of blocks in the last epoch
let first_block_of_last_epoch = self
.wl_storage
.storage
.block
.pred_epochs
.first_block_heights[last_epoch.0 as usize]
.0;
let num_blocks_in_last_epoch = if first_block_of_last_epoch == 0 {
self.wl_storage.storage.block.height.0 - 1
} else {
self.wl_storage.storage.block.height.0 - first_block_of_last_epoch
};
// Read the rewards accumulator and calculate the new rewards products
// for the previous epoch
//
// TODO: think about changing the reward to Decimal
let mut reward_tokens_remaining = inflation;
let mut new_rewards_products: HashMap<Address, (Dec, Dec)> =
HashMap::new();
for acc in rewards_accumulator_handle().iter(&self.wl_storage)? {
let (address, value) = acc?;
// Get reward token amount for this validator
let fractional_claim = value / num_blocks_in_last_epoch;
let reward = fractional_claim * inflation;
// Get validator data at the last epoch
let stake = read_validator_stake(
&self.wl_storage,
¶ms,
&address,
last_epoch,
)?
.map(Dec::from)
.unwrap_or_default();
let last_rewards_product =
validator_rewards_products_handle(&address)
.get(&self.wl_storage, &last_epoch)?
.unwrap_or_else(Dec::one);
let last_delegation_product =
delegator_rewards_products_handle(&address)
.get(&self.wl_storage, &last_epoch)?
.unwrap_or_else(Dec::one);
let commission_rate = validator_commission_rate_handle(&address)
.get(&self.wl_storage, last_epoch, ¶ms)?
.expect("Should be able to find validator commission rate");
let new_product =
last_rewards_product * (Dec::one() + Dec::from(reward) / stake);
let new_delegation_product = last_delegation_product
* (Dec::one()
+ (Dec::one() - commission_rate) * Dec::from(reward)
/ stake);
new_rewards_products
.insert(address, (new_product, new_delegation_product));
reward_tokens_remaining -= reward;
}
for (
address,
(new_validator_reward_product, new_delegator_reward_product),
) in new_rewards_products
{
validator_rewards_products_handle(&address).insert(
&mut self.wl_storage,
last_epoch,
new_validator_reward_product,
)?;
delegator_rewards_products_handle(&address).insert(
&mut self.wl_storage,
last_epoch,
new_delegator_reward_product,
)?;
}
let staking_token = staking_token_address(&self.wl_storage);
// Mint tokens to the PoS account for the last epoch's inflation
let pos_reward_tokens = inflation - reward_tokens_remaining;
tracing::info!(
"Minting tokens for PoS rewards distribution into the PoS \
account. Amount: {}.",
pos_reward_tokens.to_string_native(),
);
credit_tokens(
&mut self.wl_storage,
&staking_token,
&address::POS,
pos_reward_tokens,
)?;
if reward_tokens_remaining > token::Amount::zero() {
let amount = Amount::from_uint(reward_tokens_remaining, 0).unwrap();
tracing::info!(
"Minting tokens remaining from PoS rewards distribution into \
the Governance account. Amount: {}.",
amount.to_string_native()
);
credit_tokens(
&mut self.wl_storage,
&staking_token,
&address::GOV,
amount,
)?;
}
// Write new rewards parameters that will be used for the inflation of
// the current new epoch
self.wl_storage
.write(¶ms_storage::get_pos_inflation_amount_key(), inflation)
.expect("unable to write new reward rate");
self.wl_storage
.write(¶ms_storage::get_staked_ratio_key(), locked_ratio)
.expect("unable to write new locked ratio");
// Delete the accumulators from storage
// TODO: refactor with https://github.com/anoma/namada/issues/1225
let addresses_to_drop: HashSet<Address> = rewards_accumulator_handle()
.iter(&self.wl_storage)?
.map(|a| a.unwrap().0)
.collect();
for address in addresses_to_drop.into_iter() {
rewards_accumulator_handle()
.remove(&mut self.wl_storage, &address)?;
}
// Pgf inflation
let pgf_parameters = pgf::get_parameters(&self.wl_storage)?;
let pgf_pd_rate =
pgf_parameters.pgf_inflation_rate / Dec::from(epochs_per_year);
let pgf_inflation = Dec::from(total_tokens) * pgf_pd_rate;
let pgf_stewards_pd_rate =
pgf_parameters.stewards_inflation_rate / Dec::from(epochs_per_year);
let pgf_steward_inflation =
Dec::from(total_tokens) * pgf_stewards_pd_rate;
let pgf_inflation_amount =
token::Amount::from(pgf_inflation + pgf_steward_inflation);
credit_tokens(
&mut self.wl_storage,
&staking_token,
&pgf_address,
pgf_inflation_amount,
)?;
tracing::info!(
"Minting {} tokens for PGF rewards distribution into the PGF \
account.",
pgf_inflation_amount.to_string_native()
);
let mut pgf_fundings = pgf::get_payments(&self.wl_storage)?;
// we want to pay first the oldest fundings
pgf_fundings.sort_by(|a, b| a.id.cmp(&b.id));
for funding in pgf_fundings {
if credit_tokens(
&mut self.wl_storage,
&staking_token,
&funding.detail.target,
funding.detail.amount,
)
.is_ok()
{
tracing::info!(
"Minted {} tokens for {} project.",
funding.detail.amount.to_string_native(),
&funding.detail.target,
);
} else {
tracing::warn!(
"Failed Minting {} tokens for {} project.",
funding.detail.amount.to_string_native(),
&funding.detail.target,
);
}
}
// Pgf steward inflation
let stewards = pgf::get_stewards(&self.wl_storage)?;
let pgf_steward_reward = match stewards.len() {
0 => Dec::zero(),
_ => pgf_steward_inflation
.trunc_div(&Dec::from(stewards.len()))
.unwrap_or_default(),
};
for steward in stewards {
for (address, percentage) in steward.reward_distribution {
let pgf_steward_reward = pgf_steward_reward
.checked_mul(&percentage)
.unwrap_or_default();
let reward_amount = token::Amount::from(pgf_steward_reward);
if credit_tokens(
&mut self.wl_storage,
&staking_token,
&address,
reward_amount,
)
.is_ok()
{
tracing::info!(
"Minting {} tokens for steward {}.",
reward_amount.to_string_native(),
address,
);
} else {
tracing::warn!(
"Failed minting {} tokens for steward {}.",
reward_amount.to_string_native(),
address,
);
}
}
}
Ok(())
}
// Process the proposer and votes in the block to assign their PoS rewards.
fn log_block_rewards(
&mut self,
votes: &[VoteInfo],
height: BlockHeight,
current_epoch: Epoch,
new_epoch: bool,
) -> Result<()> {
// Read the block proposer of the previously committed block in storage
// (n-1 if we are in the process of finalizing n right now).
match read_last_block_proposer_address(&self.wl_storage)? {
Some(proposer_address) => {
tracing::debug!(
"Found last block proposer: {proposer_address}"
);
let votes = pos_votes_from_abci(&self.wl_storage, votes);
namada_proof_of_stake::log_block_rewards(
&mut self.wl_storage,
if new_epoch {
current_epoch.prev()
} else {
current_epoch
},
&proposer_address,
votes,
)?;
}
None => {
if height > BlockHeight::default().next_height() {
tracing::error!(
"Can't find the last block proposer at height {height}"
);
} else {
tracing::debug!(
"No last block proposer at height {height}"
);
}
}
}
Ok(())
}
}
/// Convert ABCI vote info to PoS vote info. Any info which fails the conversion
/// will be skipped and errors logged.
///
/// # Panics
/// Panics if a validator's address cannot be converted to native address
/// (either due to storage read error or the address not being found) or
/// if the voting power cannot be converted to u64.
fn pos_votes_from_abci(
storage: &impl StorageRead,
votes: &[VoteInfo],
) -> Vec<namada_proof_of_stake::types::VoteInfo> {
votes
.iter()
.filter_map(
|VoteInfo {
validator,
signed_last_block,
}| {
if let Some(
crate::facade::tendermint_proto::abci::Validator {
address,
power,
},
) = validator
{
let tm_raw_hash_string = HEXUPPER.encode(address);
if *signed_last_block {
tracing::debug!(
"Looking up validator from Tendermint VoteInfo's \
raw hash {tm_raw_hash_string}"
);
// Look-up the native address
let validator_address = find_validator_by_raw_hash(
storage,
&tm_raw_hash_string,