-
Notifications
You must be signed in to change notification settings - Fork 624
/
lib.rs
2517 lines (2356 loc) · 101 KB
/
lib.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
use std::cmp::max;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
use config::total_prepaid_send_fees;
use tracing::debug;
use near_chain_configs::Genesis;
pub use near_crypto;
use near_crypto::PublicKey;
pub use near_primitives;
use near_primitives::contract::ContractCode;
use near_primitives::profile::ProfileDataV3;
pub use near_primitives::runtime::apply_state::ApplyState;
use near_primitives::runtime::fees::RuntimeFeesConfig;
use near_primitives::runtime::migration_data::{MigrationData, MigrationFlags};
use near_primitives::sandbox::state_patch::SandboxStatePatch;
use near_primitives::transaction::ExecutionMetadata;
use near_primitives::version::{
is_implicit_account_creation_enabled, ProtocolFeature, ProtocolVersion,
};
use near_primitives::{
account::Account,
checked_feature,
errors::{ActionError, ActionErrorKind, RuntimeError, TxExecutionError},
hash::CryptoHash,
receipt::{
ActionReceipt, DataReceipt, DelayedReceiptIndices, Receipt, ReceiptEnum, ReceivedData,
},
state_record::StateRecord,
transaction::{
Action, ExecutionOutcome, ExecutionOutcomeWithId, ExecutionStatus, LogEntry,
SignedTransaction,
},
trie_key::TrieKey,
types::{
validator_stake::ValidatorStake, AccountId, Balance, EpochInfoProvider, Gas,
RawStateChangesWithTrieKey, ShardId, StateChangeCause, StateRoot,
},
utils::{
create_action_hash, create_receipt_id_from_receipt, create_receipt_id_from_transaction,
},
};
use near_store::{
get, get_account, get_postponed_receipt, get_received_data, remove_postponed_receipt, set,
set_account, set_postponed_receipt, set_received_data, PartialStorage, ShardTries,
StorageError, Trie, TrieChanges, TrieUpdate,
};
use near_store::{set_access_key, set_code};
use near_vm_logic::types::PromiseResult;
use near_vm_logic::{ActionCosts, ReturnData};
pub use near_vm_runner::with_ext_cost_counter;
use crate::actions::*;
use crate::balance_checker::check_balance;
use crate::config::{
exec_fee, safe_add_balance, safe_add_gas, safe_gas_to_balance, total_deposit,
total_prepaid_exec_fees, total_prepaid_gas, RuntimeConfig,
};
use crate::genesis::{GenesisStateApplier, StorageComputer};
use crate::prefetch::TriePrefetcher;
use crate::verifier::{check_storage_stake, validate_receipt, StorageStakingError};
pub use crate::verifier::{validate_transaction, verify_and_charge_transaction};
mod actions;
pub mod adapter;
mod balance_checker;
pub mod config;
pub mod ext;
mod genesis;
mod metrics;
mod prefetch;
pub mod state_viewer;
mod verifier;
const EXPECT_ACCOUNT_EXISTS: &str = "account exists, checked above";
/// Contains information to update validators accounts at the first block of a new epoch.
#[derive(Debug)]
pub struct ValidatorAccountsUpdate {
/// Maximum stake across last 3 epochs.
pub stake_info: HashMap<AccountId, Balance>,
/// Rewards to distribute to validators.
pub validator_rewards: HashMap<AccountId, Balance>,
/// Stake proposals from the last chunk.
pub last_proposals: HashMap<AccountId, Balance>,
/// The ID of the protocol treasury account if it belongs to the current shard.
pub protocol_treasury_account_id: Option<AccountId>,
/// Accounts to slash and the slashed amount (None means everything)
pub slashing_info: HashMap<AccountId, Option<Balance>>,
}
#[derive(Debug)]
pub struct VerificationResult {
/// The amount gas that was burnt to convert the transaction into a receipt and send it.
pub gas_burnt: Gas,
/// The remaining amount of gas in the receipt.
pub gas_remaining: Gas,
/// The gas price at which the gas was purchased in the receipt.
pub receipt_gas_price: Balance,
/// The balance that was burnt to convert the transaction into a receipt and send it.
pub burnt_amount: Balance,
}
#[derive(Debug, Default)]
pub struct ApplyStats {
pub tx_burnt_amount: Balance,
pub slashed_burnt_amount: Balance,
pub other_burnt_amount: Balance,
/// This is a negative amount. This amount was not charged from the account that issued
/// the transaction. It's likely due to the delayed queue of the receipts.
pub gas_deficit_amount: Balance,
}
pub struct ApplyResult {
pub state_root: StateRoot,
pub trie_changes: TrieChanges,
pub validator_proposals: Vec<ValidatorStake>,
pub outgoing_receipts: Vec<Receipt>,
pub outcomes: Vec<ExecutionOutcomeWithId>,
pub state_changes: Vec<RawStateChangesWithTrieKey>,
pub stats: ApplyStats,
pub processed_delayed_receipts: Vec<Receipt>,
pub proof: Option<PartialStorage>,
}
#[derive(Debug)]
pub struct ActionResult {
pub gas_burnt: Gas,
pub gas_burnt_for_function_call: Gas,
pub gas_used: Gas,
pub result: Result<ReturnData, ActionError>,
pub logs: Vec<LogEntry>,
pub new_receipts: Vec<Receipt>,
pub validator_proposals: Vec<ValidatorStake>,
pub profile: ProfileDataV3,
}
impl ActionResult {
pub fn merge(&mut self, mut next_result: ActionResult) -> Result<(), RuntimeError> {
assert!(next_result.gas_burnt_for_function_call <= next_result.gas_burnt);
assert!(
next_result.gas_burnt <= next_result.gas_used,
"Gas burnt {} <= Gas used {}",
next_result.gas_burnt,
next_result.gas_used
);
self.gas_burnt = safe_add_gas(self.gas_burnt, next_result.gas_burnt)?;
self.gas_burnt_for_function_call = safe_add_gas(
self.gas_burnt_for_function_call,
next_result.gas_burnt_for_function_call,
)?;
self.gas_used = safe_add_gas(self.gas_used, next_result.gas_used)?;
self.profile.merge(&next_result.profile);
self.result = next_result.result;
self.logs.append(&mut next_result.logs);
if let Ok(ReturnData::ReceiptIndex(ref mut receipt_index)) = self.result {
// Shifting local receipt index to be global receipt index.
*receipt_index += self.new_receipts.len() as u64;
}
if self.result.is_ok() {
self.new_receipts.append(&mut next_result.new_receipts);
self.validator_proposals.append(&mut next_result.validator_proposals);
} else {
self.new_receipts.clear();
self.validator_proposals.clear();
}
Ok(())
}
}
impl Default for ActionResult {
fn default() -> Self {
Self {
gas_burnt: 0,
gas_burnt_for_function_call: 0,
gas_used: 0,
result: Ok(ReturnData::None),
logs: vec![],
new_receipts: vec![],
validator_proposals: vec![],
profile: Default::default(),
}
}
}
pub struct Runtime {}
impl Runtime {
pub fn new() -> Self {
Self {}
}
fn print_log(log: &[LogEntry]) {
if log.is_empty() {
return;
}
let log_str = log.iter().fold(String::new(), |acc, s| {
if acc.is_empty() {
s.to_string()
} else {
acc + "\n" + s
}
});
debug!(target: "runtime", "{}", log_str);
}
/// Takes one signed transaction, verifies it and converts it to a receipt. Add this receipt
/// either to the new local receipts if the signer is the same as receiver or to the new
/// outgoing receipts.
/// When transaction is converted to a receipt, the account is charged for the full value of
/// the generated receipt.
/// In case of successful verification (expected for valid chunks), returns the receipt and
/// `ExecutionOutcomeWithId` for the transaction.
/// In case of an error, returns either `InvalidTxError` if the transaction verification failed
/// or a `StorageError` wrapped into `RuntimeError`.
fn process_transaction(
&self,
state_update: &mut TrieUpdate,
apply_state: &ApplyState,
signed_transaction: &SignedTransaction,
stats: &mut ApplyStats,
) -> Result<(Receipt, ExecutionOutcomeWithId), RuntimeError> {
let _span = tracing::debug_span!(target: "runtime", "process_transaction", tx_hash = %signed_transaction.get_hash()).entered();
metrics::TRANSACTION_PROCESSED_TOTAL.inc();
match verify_and_charge_transaction(
&apply_state.config,
state_update,
apply_state.gas_price,
signed_transaction,
true,
Some(apply_state.block_height),
apply_state.current_protocol_version,
) {
Ok(verification_result) => {
metrics::TRANSACTION_PROCESSED_SUCCESSFULLY_TOTAL.inc();
state_update.commit(StateChangeCause::TransactionProcessing {
tx_hash: signed_transaction.get_hash(),
});
let transaction = &signed_transaction.transaction;
let receipt_id = create_receipt_id_from_transaction(
apply_state.current_protocol_version,
signed_transaction,
&apply_state.prev_block_hash,
&apply_state.block_hash,
);
let receipt = Receipt {
predecessor_id: transaction.signer_id.clone(),
receiver_id: transaction.receiver_id.clone(),
receipt_id,
receipt: ReceiptEnum::Action(ActionReceipt {
signer_id: transaction.signer_id.clone(),
signer_public_key: transaction.public_key.clone(),
gas_price: verification_result.receipt_gas_price,
output_data_receivers: vec![],
input_data_ids: vec![],
actions: transaction.actions.clone(),
}),
};
stats.tx_burnt_amount =
safe_add_balance(stats.tx_burnt_amount, verification_result.burnt_amount)?;
let outcome = ExecutionOutcomeWithId {
id: signed_transaction.get_hash(),
outcome: ExecutionOutcome {
status: ExecutionStatus::SuccessReceiptId(receipt.receipt_id),
logs: vec![],
receipt_ids: vec![receipt.receipt_id],
gas_burnt: verification_result.gas_burnt,
tokens_burnt: verification_result.burnt_amount,
executor_id: transaction.signer_id.clone(),
// TODO: profile data is only counted in apply_action, which only happened at process_receipt
// VerificationResult needs updates to incorporate profile data to support profile data of txns
metadata: ExecutionMetadata::V1,
},
};
Ok((receipt, outcome))
}
Err(e) => {
metrics::TRANSACTION_PROCESSED_FAILED_TOTAL.inc();
state_update.rollback();
Err(e)
}
}
}
fn apply_action(
&self,
action: &Action,
state_update: &mut TrieUpdate,
apply_state: &ApplyState,
account: &mut Option<Account>,
actor_id: &mut AccountId,
receipt: &Receipt,
action_receipt: &ActionReceipt,
promise_results: &[PromiseResult],
action_hash: &CryptoHash,
action_index: usize,
actions: &[Action],
epoch_info_provider: &dyn EpochInfoProvider,
) -> Result<ActionResult, RuntimeError> {
// println!("enter apply_action");
let mut result = ActionResult::default();
let exec_fees = exec_fee(
&apply_state.config.fees,
action,
&receipt.receiver_id,
apply_state.current_protocol_version,
);
result.gas_burnt += exec_fees;
result.gas_used += exec_fees;
let account_id = &receipt.receiver_id;
let is_the_only_action = actions.len() == 1;
let is_refund = AccountId::is_system(&receipt.predecessor_id);
// Account validation
if let Err(e) = check_account_existence(
action,
account,
account_id,
apply_state.current_protocol_version,
is_the_only_action,
is_refund,
) {
result.result = Err(e);
return Ok(result);
}
// Permission validation
if let Err(e) = check_actor_permissions(action, account, actor_id, account_id) {
result.result = Err(e);
return Ok(result);
}
metrics::ACTION_CALLED_COUNT.with_label_values(&[action.as_ref()]).inc();
match action {
Action::CreateAccount(_) => {
action_create_account(
&apply_state.config.fees,
&apply_state.config.account_creation_config,
account,
actor_id,
&receipt.receiver_id,
&receipt.predecessor_id,
&mut result,
);
}
Action::DeployContract(deploy_contract) => {
action_deploy_contract(
state_update,
account.as_mut().expect(EXPECT_ACCOUNT_EXISTS),
account_id,
deploy_contract,
apply_state,
apply_state.current_protocol_version,
)?;
}
Action::FunctionCall(function_call) => {
action_function_call(
state_update,
apply_state,
account.as_mut().expect(EXPECT_ACCOUNT_EXISTS),
receipt,
action_receipt,
promise_results,
&mut result,
account_id,
function_call,
action_hash,
&apply_state.config,
action_index + 1 == actions.len(),
epoch_info_provider,
)?;
}
Action::Transfer(transfer) => {
if let Some(account) = account.as_mut() {
action_transfer(account, transfer)?;
// Check if this is a gas refund, then try to refund the access key allowance.
if is_refund && action_receipt.signer_id == receipt.receiver_id {
try_refund_allowance(
state_update,
&receipt.receiver_id,
&action_receipt.signer_public_key,
transfer,
)?;
}
} else {
// Implicit account creation
debug_assert!(is_implicit_account_creation_enabled(
apply_state.current_protocol_version
));
debug_assert!(!is_refund);
action_implicit_account_creation_transfer(
state_update,
&apply_state.config.fees,
account,
actor_id,
&receipt.receiver_id,
transfer,
apply_state.block_height,
apply_state.current_protocol_version,
);
}
}
Action::Stake(stake) => {
action_stake(
account.as_mut().expect(EXPECT_ACCOUNT_EXISTS),
&mut result,
account_id,
stake,
&apply_state.prev_block_hash,
epoch_info_provider,
)?;
}
Action::AddKey(add_key) => {
action_add_key(
apply_state,
state_update,
account.as_mut().expect(EXPECT_ACCOUNT_EXISTS),
&mut result,
account_id,
add_key,
)?;
}
Action::DeleteKey(delete_key) => {
action_delete_key(
&apply_state.config.fees,
state_update,
account.as_mut().expect(EXPECT_ACCOUNT_EXISTS),
&mut result,
account_id,
delete_key,
apply_state.current_protocol_version,
)?;
}
Action::DeleteAccount(delete_account) => {
action_delete_account(
state_update,
account,
actor_id,
receipt,
&mut result,
account_id,
delete_account,
apply_state.current_protocol_version,
)?;
}
#[cfg(feature = "protocol_feature_nep366_delegate_action")]
Action::Delegate(signed_delegate_action) => {
apply_delegate_action(
state_update,
apply_state,
action_receipt,
account_id,
signed_delegate_action,
&mut result,
)?;
}
};
Ok(result)
}
// Executes when all Receipt `input_data_ids` are in the state
fn apply_action_receipt(
&self,
state_update: &mut TrieUpdate,
apply_state: &ApplyState,
receipt: &Receipt,
outgoing_receipts: &mut Vec<Receipt>,
validator_proposals: &mut Vec<ValidatorStake>,
stats: &mut ApplyStats,
epoch_info_provider: &dyn EpochInfoProvider,
) -> Result<ExecutionOutcomeWithId, RuntimeError> {
let action_receipt = match &receipt.receipt {
ReceiptEnum::Action(action_receipt) => action_receipt,
_ => unreachable!("given receipt should be an action receipt"),
};
let account_id = &receipt.receiver_id;
// Collecting input data and removing it from the state
let promise_results = action_receipt
.input_data_ids
.iter()
.map(|data_id| {
let ReceivedData { data } = get_received_data(state_update, account_id, *data_id)?
.ok_or_else(|| {
StorageError::StorageInconsistentState(
"received data should be in the state".to_string(),
)
})?;
state_update.remove(TrieKey::ReceivedData {
receiver_id: account_id.clone(),
data_id: *data_id,
});
match data {
Some(value) => Ok(PromiseResult::Successful(value)),
None => Ok(PromiseResult::Failed),
}
})
.collect::<Result<Vec<PromiseResult>, RuntimeError>>()?;
// state_update might already have some updates so we need to make sure we commit it before
// executing the actual receipt
state_update.commit(StateChangeCause::ActionReceiptProcessingStarted {
receipt_hash: receipt.get_hash(),
});
let mut account = get_account(state_update, account_id)?;
let mut actor_id = receipt.predecessor_id.clone();
let mut result = ActionResult::default();
let exec_fee = apply_state.config.fees.fee(ActionCosts::new_action_receipt).exec_fee();
result.gas_used = exec_fee;
result.gas_burnt = exec_fee;
// Executing actions one by one
for (action_index, action) in action_receipt.actions.iter().enumerate() {
let action_hash = create_action_hash(
apply_state.current_protocol_version,
receipt,
&apply_state.prev_block_hash,
&apply_state.block_hash,
action_index,
);
let mut new_result = self.apply_action(
action,
state_update,
apply_state,
&mut account,
&mut actor_id,
receipt,
action_receipt,
&promise_results,
&action_hash,
action_index,
&action_receipt.actions,
epoch_info_provider,
)?;
if new_result.result.is_ok() {
if let Err(e) = new_result.new_receipts.iter().try_for_each(|receipt| {
validate_receipt(&apply_state.config.wasm_config.limit_config, receipt)
}) {
new_result.result = Err(ActionErrorKind::NewReceiptValidationError(e).into());
}
}
result.merge(new_result)?;
// TODO storage error
if let Err(ref mut res) = result.result {
res.index = Some(action_index as u64);
break;
}
}
// Going to check balance covers account's storage.
if result.result.is_ok() {
if let Some(ref mut account) = account {
match check_storage_stake(
account_id,
account,
&apply_state.config,
state_update,
apply_state.current_protocol_version,
) {
Ok(()) => {
set_account(state_update, account_id.clone(), account);
}
Err(StorageStakingError::LackBalanceForStorageStaking(amount)) => {
result.merge(ActionResult {
result: Err(ActionError {
index: None,
kind: ActionErrorKind::LackBalanceForState {
account_id: account_id.clone(),
amount,
},
}),
..Default::default()
})?;
}
Err(StorageStakingError::StorageError(err)) => {
return Err(RuntimeError::StorageError(
StorageError::StorageInconsistentState(err),
))
}
}
}
}
let gas_deficit_amount = if AccountId::is_system(&receipt.predecessor_id) {
// We will set gas_burnt for refund receipts to be 0 when we calculate tx_burnt_amount
// Here we don't set result.gas_burnt to be zero if CountRefundReceiptsInGasLimit is
// enabled because we want it to be counted in gas limit calculation later
if !checked_feature!(
"stable",
CountRefundReceiptsInGasLimit,
apply_state.current_protocol_version
) {
result.gas_burnt = 0;
result.gas_used = 0;
}
// If the refund fails tokens are burned.
if result.result.is_err() {
stats.other_burnt_amount = safe_add_balance(
stats.other_burnt_amount,
total_deposit(&action_receipt.actions)?,
)?
}
0
} else {
// Calculating and generating refunds
self.generate_refund_receipts(
apply_state.gas_price,
receipt,
action_receipt,
&mut result,
apply_state.current_protocol_version,
&apply_state.config.fees,
)?
};
stats.gas_deficit_amount = safe_add_balance(stats.gas_deficit_amount, gas_deficit_amount)?;
// Moving validator proposals
validator_proposals.append(&mut result.validator_proposals);
// Committing or rolling back state.
match &result.result {
Ok(_) => {
state_update.commit(StateChangeCause::ReceiptProcessing {
receipt_hash: receipt.get_hash(),
});
}
Err(_) => {
state_update.rollback();
}
};
// If the receipt is a refund, then we consider it free without burnt gas.
let gas_burnt: Gas =
if AccountId::is_system(&receipt.predecessor_id) { 0 } else { result.gas_burnt };
// `gas_deficit_amount` is strictly less than `gas_price * gas_burnt`.
let mut tx_burnt_amount =
safe_gas_to_balance(apply_state.gas_price, gas_burnt)? - gas_deficit_amount;
// The amount of tokens burnt for the execution of this receipt. It's used in the execution
// outcome.
let tokens_burnt = tx_burnt_amount;
// Adding burnt gas reward for function calls if the account exists.
let receiver_gas_reward = result.gas_burnt_for_function_call
* *apply_state.config.fees.burnt_gas_reward.numer() as u64
/ *apply_state.config.fees.burnt_gas_reward.denom() as u64;
// The balance that the current account should receive as a reward for function call
// execution.
let receiver_reward = safe_gas_to_balance(apply_state.gas_price, receiver_gas_reward)?
.saturating_sub(gas_deficit_amount);
if receiver_reward > 0 {
let mut account = get_account(state_update, account_id)?;
if let Some(ref mut account) = account {
// Validators receive the remaining execution reward that was not given to the
// account holder. If the account doesn't exist by the end of the execution, the
// validators receive the full reward.
tx_burnt_amount -= receiver_reward;
account.set_amount(safe_add_balance(account.amount(), receiver_reward)?);
set_account(state_update, account_id.clone(), account);
state_update.commit(StateChangeCause::ActionReceiptGasReward {
receipt_hash: receipt.get_hash(),
});
}
}
stats.tx_burnt_amount = safe_add_balance(stats.tx_burnt_amount, tx_burnt_amount)?;
// Generating outgoing data
// A {
// B().then(C())} B--data receipt->C
// A {
// B(); 42}
if !action_receipt.output_data_receivers.is_empty() {
if let Ok(ReturnData::ReceiptIndex(receipt_index)) = result.result {
// Modifying a new receipt instead of sending data
match result
.new_receipts
.get_mut(receipt_index as usize)
.expect("the receipt for the given receipt index should exist")
.receipt
{
ReceiptEnum::Action(ref mut new_action_receipt) => new_action_receipt
.output_data_receivers
.extend_from_slice(&action_receipt.output_data_receivers),
_ => unreachable!("the receipt should be an action receipt"),
}
} else {
let data = match result.result {
Ok(ReturnData::Value(ref data)) => Some(data.clone()),
Ok(_) => Some(vec![]),
Err(_) => None,
};
result.new_receipts.extend(action_receipt.output_data_receivers.iter().map(
|data_receiver| Receipt {
predecessor_id: account_id.clone(),
receiver_id: data_receiver.receiver_id.clone(),
receipt_id: CryptoHash::default(),
receipt: ReceiptEnum::Data(DataReceipt {
data_id: data_receiver.data_id,
data: data.clone(),
}),
},
));
};
}
// Generating receipt IDs
let receipt_ids = result
.new_receipts
.into_iter()
.enumerate()
.filter_map(|(receipt_index, mut new_receipt)| {
let receipt_id = create_receipt_id_from_receipt(
apply_state.current_protocol_version,
receipt,
&apply_state.prev_block_hash,
&apply_state.block_hash,
receipt_index,
);
new_receipt.receipt_id = receipt_id;
let is_action = matches!(&new_receipt.receipt, ReceiptEnum::Action(_));
outgoing_receipts.push(new_receipt);
if is_action {
Some(receipt_id)
} else {
None
}
})
.collect();
let status = match result.result {
Ok(ReturnData::ReceiptIndex(receipt_index)) => {
ExecutionStatus::SuccessReceiptId(create_receipt_id_from_receipt(
apply_state.current_protocol_version,
receipt,
&apply_state.prev_block_hash,
&apply_state.block_hash,
receipt_index as usize,
))
}
Ok(ReturnData::Value(data)) => ExecutionStatus::SuccessValue(data),
Ok(ReturnData::None) => ExecutionStatus::SuccessValue(vec![]),
Err(e) => ExecutionStatus::Failure(TxExecutionError::ActionError(e)),
};
Self::print_log(&result.logs);
Ok(ExecutionOutcomeWithId {
id: receipt.receipt_id,
outcome: ExecutionOutcome {
status,
logs: result.logs,
receipt_ids,
gas_burnt: result.gas_burnt,
tokens_burnt,
executor_id: account_id.clone(),
metadata: ExecutionMetadata::V3(result.profile),
},
})
}
fn generate_refund_receipts(
&self,
current_gas_price: Balance,
receipt: &Receipt,
action_receipt: &ActionReceipt,
result: &mut ActionResult,
current_protocol_version: ProtocolVersion,
transaction_costs: &RuntimeFeesConfig,
) -> Result<Balance, RuntimeError> {
let total_deposit = total_deposit(&action_receipt.actions)?;
let prepaid_gas = safe_add_gas(
total_prepaid_gas(&action_receipt.actions)?,
total_prepaid_send_fees(
transaction_costs,
&action_receipt.actions,
current_protocol_version,
)?,
)?;
let prepaid_exec_gas = safe_add_gas(
total_prepaid_exec_fees(
transaction_costs,
&action_receipt.actions,
&receipt.receiver_id,
current_protocol_version,
)?,
transaction_costs.fee(ActionCosts::new_action_receipt).exec_fee(),
)?;
let deposit_refund = if result.result.is_err() { total_deposit } else { 0 };
let gas_refund = if result.result.is_err() {
safe_add_gas(prepaid_gas, prepaid_exec_gas)? - result.gas_burnt
} else {
safe_add_gas(prepaid_gas, prepaid_exec_gas)? - result.gas_used
};
// Refund for the unused portion of the gas at the price at which this gas was purchased.
let mut gas_balance_refund = safe_gas_to_balance(action_receipt.gas_price, gas_refund)?;
let mut gas_deficit_amount = 0;
if current_gas_price > action_receipt.gas_price {
// In a rare scenario, when the current gas price is higher than the purchased gas
// price, the difference is subtracted from the refund. If the refund doesn't have
// enough balance to cover the difference, then the remaining balance is considered
// the deficit and it's reported in the stats for the balance checker.
gas_deficit_amount = safe_gas_to_balance(
current_gas_price - action_receipt.gas_price,
result.gas_burnt,
)?;
if gas_balance_refund >= gas_deficit_amount {
gas_balance_refund -= gas_deficit_amount;
gas_deficit_amount = 0;
} else {
gas_deficit_amount -= gas_balance_refund;
gas_balance_refund = 0;
}
} else {
// Refund for the difference of the purchased gas price and the the current gas price.
gas_balance_refund = safe_add_balance(
gas_balance_refund,
safe_gas_to_balance(
action_receipt.gas_price - current_gas_price,
result.gas_burnt,
)?,
)?;
}
if deposit_refund > 0 {
result
.new_receipts
.push(Receipt::new_balance_refund(&receipt.predecessor_id, deposit_refund));
}
if gas_balance_refund > 0 {
// Gas refunds refund the allowance of the access key, so if the key exists on the
// account it will increase the allowance by the refund amount.
result.new_receipts.push(Receipt::new_gas_refund(
&action_receipt.signer_id,
gas_balance_refund,
action_receipt.signer_public_key.clone(),
));
}
Ok(gas_deficit_amount)
}
fn process_receipt(
&self,
state_update: &mut TrieUpdate,
apply_state: &ApplyState,
receipt: &Receipt,
outgoing_receipts: &mut Vec<Receipt>,
validator_proposals: &mut Vec<ValidatorStake>,
stats: &mut ApplyStats,
epoch_info_provider: &dyn EpochInfoProvider,
) -> Result<Option<ExecutionOutcomeWithId>, RuntimeError> {
let account_id = &receipt.receiver_id;
match receipt.receipt {
ReceiptEnum::Data(ref data_receipt) => {
// Received a new data receipt.
// Saving the data into the state keyed by the data_id.
set_received_data(
state_update,
account_id.clone(),
data_receipt.data_id,
&ReceivedData { data: data_receipt.data.clone() },
);
// Check if there is already a receipt that was postponed and was awaiting for the
// given data_id.
// If we don't have a postponed receipt yet, we don't need to do anything for now.
if let Some(receipt_id) = get(
state_update,
&TrieKey::PostponedReceiptId {
receiver_id: account_id.clone(),
data_id: data_receipt.data_id,
},
)? {
// There is already a receipt that is awaiting for the just received data.
// Removing this pending data_id for the receipt from the state.
state_update.remove(TrieKey::PostponedReceiptId {
receiver_id: account_id.clone(),
data_id: data_receipt.data_id,
});
// Checking how many input data items is pending for the receipt.
let pending_data_count: u32 = get(
state_update,
&TrieKey::PendingDataCount { receiver_id: account_id.clone(), receipt_id },
)?
.ok_or_else(|| {
StorageError::StorageInconsistentState(
"pending data count should be in the state".to_string(),
)
})?;
if pending_data_count == 1 {
// It was the last input data pending for this receipt. We'll cleanup
// some receipt related fields from the state and execute the receipt.
// Removing pending data count from the state.
state_update.remove(TrieKey::PendingDataCount {
receiver_id: account_id.clone(),
receipt_id,
});
// Fetching the receipt itself.
let ready_receipt =
get_postponed_receipt(state_update, account_id, receipt_id)?
.ok_or_else(|| {
StorageError::StorageInconsistentState(
"pending receipt should be in the state".to_string(),
)
})?;
// Removing the receipt from the state.
remove_postponed_receipt(state_update, account_id, receipt_id);
// Executing the receipt. It will read all the input data and clean it up
// from the state.
return self
.apply_action_receipt(
state_update,
apply_state,
&ready_receipt,
outgoing_receipts,
validator_proposals,
stats,
epoch_info_provider,
)
.map(Some);
} else {
// There is still some pending data for the receipt, so we update the
// pending data count in the state.
set(
state_update,
TrieKey::PendingDataCount {
receiver_id: account_id.clone(),
receipt_id,
},
&(pending_data_count.checked_sub(1).ok_or_else(|| {
StorageError::StorageInconsistentState(
"pending data count is 0, but there is a new DataReceipt"
.to_string(),
)
})?),
);
}
}
}
ReceiptEnum::Action(ref action_receipt) => {
// Received a new action receipt. We'll first check how many input data items
// were already received before and saved in the state.
// And if we have all input data, then we can immediately execute the receipt.
// If not, then we will postpone this receipt for later.
let mut pending_data_count: u32 = 0;
for data_id in &action_receipt.input_data_ids {
if get_received_data(state_update, account_id, *data_id)?.is_none() {
pending_data_count += 1;
// The data for a given data_id is not available, so we save a link to this
// receipt_id for the pending data_id into the state.
set(
state_update,
TrieKey::PostponedReceiptId {
receiver_id: account_id.clone(),
data_id: *data_id,
},
&receipt.receipt_id,
)
}
}
if pending_data_count == 0 {
// All input data is available. Executing the receipt. It will cleanup
// input data from the state.
return self
.apply_action_receipt(
state_update,
apply_state,
receipt,
outgoing_receipts,
validator_proposals,
stats,
epoch_info_provider,
)
.map(Some);
} else {
// Not all input data is available now.
// Save the counter for the number of pending input data items into the state.
set(
state_update,
TrieKey::PendingDataCount {
receiver_id: account_id.clone(),
receipt_id: receipt.receipt_id,
},
&pending_data_count,
);
// Save the receipt itself into the state.
set_postponed_receipt(state_update, receipt);
}
}
};
// We didn't trigger execution, so we need to commit the state.
state_update
.commit(StateChangeCause::PostponedReceipt { receipt_hash: receipt.get_hash() });
Ok(None)
}
/// Iterates over the validators in the current shard and updates their accounts to return stake
/// and allocate rewards. Also updates protocol treasury account if it belongs to the current
/// shard.