-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
aptos_vm.rs
2732 lines (2538 loc) · 105 KB
/
aptos_vm.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
// Copyright © Aptos Foundation
// Parts of the project are originally copyright © Meta Platforms, Inc.
// SPDX-License-Identifier: Apache-2.0
use crate::{
block_executor::{AptosTransactionOutput, BlockAptosVM},
counters::*,
data_cache::{AsMoveResolver, StorageAdapter},
errors::{discarded_output, expect_only_successful_execution},
gas::{check_gas, get_gas_parameters},
keyless_validation,
move_vm_ext::{
get_max_binary_format_version, get_max_identifier_size,
session::user_transaction_sessions::{
abort_hook::AbortHookSession, epilogue::EpilogueSession, prologue::PrologueSession,
user::UserSession,
},
AptosMoveResolver, MoveVmExt, SessionExt, SessionId, UserTransactionContext,
},
sharded_block_executor::{executor_client::ExecutorClient, ShardedBlockExecutor},
system_module_names::*,
transaction_metadata::TransactionMetadata,
transaction_validation, verifier,
verifier::randomness::has_randomness_attribute,
VMExecutor, VMValidator,
};
use anyhow::anyhow;
use aptos_block_executor::txn_commit_hook::NoOpTransactionCommitHook;
use aptos_crypto::HashValue;
use aptos_framework::{
natives::{code::PublishRequest, randomness::RandomnessContext},
RuntimeModuleMetadataV1,
};
use aptos_gas_algebra::{Gas, GasQuantity, NumBytes, Octa};
use aptos_gas_meter::{AptosGasMeter, GasAlgebra, StandardGasAlgebra, StandardGasMeter};
use aptos_gas_schedule::{AptosGasParameters, TransactionGasParameters, VMGasParameters};
use aptos_logger::{enabled, prelude::*, Level};
use aptos_memory_usage_tracker::MemoryTrackedGasMeter;
use aptos_metrics_core::TimerHelper;
#[cfg(any(test, feature = "testing"))]
use aptos_types::state_store::StateViewId;
use aptos_types::{
account_config,
account_config::{new_block_event_key, AccountResource},
block_executor::{
config::{BlockExecutorConfig, BlockExecutorConfigFromOnchain, BlockExecutorLocalConfig},
partitioner::PartitionedTransactions,
},
block_metadata::BlockMetadata,
block_metadata_ext::{BlockMetadataExt, BlockMetadataWithRandomness},
chain_id::ChainId,
fee_statement::FeeStatement,
invalid_signature,
move_utils::as_move_value::AsMoveValue,
on_chain_config::{
new_epoch_event_key, randomness_api_v0_config::RequiredGasDeposit, ConfigurationResource,
FeatureFlag, Features, OnChainConfig, TimedFeatureOverride, TimedFeatures,
TimedFeaturesBuilder,
},
randomness::Randomness,
state_store::{StateView, TStateView},
transaction::{
authenticator::AnySignature, signature_verified_transaction::SignatureVerifiedTransaction,
BlockOutput, EntryFunction, ExecutionError, ExecutionStatus, ModuleBundle, Multisig,
MultisigTransactionPayload, Script, SignatureCheckedTransaction, SignedTransaction,
Transaction, TransactionAuxiliaryData, TransactionOutput, TransactionPayload,
TransactionStatus, VMValidatorResult, ViewFunctionOutput, WriteSetPayload,
},
vm_status::{AbortLocation, StatusCode, VMStatus},
};
use aptos_utils::{aptos_try, return_on_failure};
use aptos_vm_logging::{log_schema::AdapterLogSchema, speculative_error, speculative_log};
use aptos_vm_types::{
abstract_write_op::AbstractResourceWriteOp,
change_set::VMChangeSet,
output::VMOutput,
resolver::{ExecutorView, ResourceGroupView},
storage::{change_set_configs::ChangeSetConfigs, StorageGasParameters},
};
use ark_bn254::Bn254;
use ark_groth16::PreparedVerifyingKey;
use claims::assert_err;
use fail::fail_point;
use move_binary_format::{
access::ModuleAccess,
compatibility::Compatibility,
deserializer::DeserializerConfig,
errors::{Location, PartialVMError, PartialVMResult, VMError, VMResult},
CompiledModule,
};
use move_core_types::{
account_address::AccountAddress,
ident_str,
identifier::Identifier,
language_storage::{ModuleId, TypeTag},
move_resource::MoveStructType,
transaction_argument::convert_txn_args,
value::{serialize_values, MoveValue},
vm_status::StatusType,
};
use move_vm_runtime::{
logging::expect_no_verification_errors,
module_traversal::{TraversalContext, TraversalStorage},
};
use move_vm_types::gas::{GasMeter, UnmeteredGasMeter};
use num_cpus;
use once_cell::sync::{Lazy, OnceCell};
use std::{
cmp::{max, min},
collections::{BTreeMap, BTreeSet},
marker::Sync,
sync::Arc,
};
static EXECUTION_CONCURRENCY_LEVEL: OnceCell<usize> = OnceCell::new();
static NUM_EXECUTION_SHARD: OnceCell<usize> = OnceCell::new();
static NUM_PROOF_READING_THREADS: OnceCell<usize> = OnceCell::new();
static PARANOID_TYPE_CHECKS: OnceCell<bool> = OnceCell::new();
static DISCARD_FAILED_BLOCKS: OnceCell<bool> = OnceCell::new();
static PROCESSED_TRANSACTIONS_DETAILED_COUNTERS: OnceCell<bool> = OnceCell::new();
static TIMED_FEATURE_OVERRIDE: OnceCell<TimedFeatureOverride> = OnceCell::new();
// TODO: Don't expose this in AptosVM, and use only in BlockAptosVM!
pub static RAYON_EXEC_POOL: Lazy<Arc<rayon::ThreadPool>> = Lazy::new(|| {
Arc::new(
rayon::ThreadPoolBuilder::new()
.num_threads(num_cpus::get())
.thread_name(|index| format!("par_exec-{}", index))
.build()
.unwrap(),
)
});
macro_rules! deprecated_module_bundle {
() => {
VMStatus::error(
StatusCode::FEATURE_UNDER_GATING,
Some("Module bundle payload has been removed".to_string()),
)
};
}
macro_rules! unwrap_or_discard {
($res:expr) => {
match $res {
Ok(s) => s,
Err(e) => {
// covers both VMStatus itself and VMError which can convert to VMStatus
let s: VMStatus = e.into();
let o = discarded_output(s.status_code());
return (s, o);
},
}
};
}
pub(crate) fn get_system_transaction_output(
session: SessionExt,
fee_statement: FeeStatement,
status: ExecutionStatus,
change_set_configs: &ChangeSetConfigs,
) -> Result<VMOutput, VMStatus> {
get_transaction_output(
session,
fee_statement,
status,
change_set_configs,
TransactionAuxiliaryData::default(),
)
}
pub(crate) fn get_transaction_output(
session: SessionExt,
fee_statement: FeeStatement,
status: ExecutionStatus,
change_set_configs: &ChangeSetConfigs,
auxiliary_data: TransactionAuxiliaryData,
) -> Result<VMOutput, VMStatus> {
let change_set = session.finish(change_set_configs)?;
Ok(VMOutput::new(
change_set,
fee_statement,
TransactionStatus::Keep(status),
auxiliary_data,
))
}
pub(crate) fn get_or_vm_startup_failure<'a, T>(
gas_params: &'a Result<T, String>,
log_context: &AdapterLogSchema,
) -> Result<&'a T, VMStatus> {
gas_params.as_ref().map_err(|err| {
let msg = format!("VM Startup Failed. {}", err);
speculative_error!(log_context, msg.clone());
VMStatus::error(StatusCode::VM_STARTUP_FAILURE, Some(msg))
})
}
pub struct AptosVM {
is_simulation: bool,
move_vm: MoveVmExt,
gas_feature_version: u64,
gas_params: Result<AptosGasParameters, String>,
pub(crate) storage_gas_params: Result<StorageGasParameters, String>,
timed_features: TimedFeatures,
/// For a new chain, or even mainnet, the VK might not necessarily be set.
pvk: Option<PreparedVerifyingKey<Bn254>>,
randomness_api_v0_required_deposit: RequiredGasDeposit,
}
impl AptosVM {
pub fn new(
resolver: &impl AptosMoveResolver,
override_is_delayed_field_optimization_capable: Option<bool>,
) -> Self {
let _timer = TIMER.timer_with(&["AptosVM::new"]);
let randomness_api_v0_required_deposit = RequiredGasDeposit::fetch_config(resolver)
.unwrap_or_else(RequiredGasDeposit::default_if_missing);
let features = Features::fetch_config(resolver).unwrap_or_default();
let (
gas_params,
storage_gas_params,
native_gas_params,
misc_gas_params,
gas_feature_version,
) = get_gas_parameters(&features, resolver);
// If no chain ID is in storage, we assume we are in a testing environment and use ChainId::TESTING
let chain_id = ChainId::fetch_config(resolver).unwrap_or_else(ChainId::test);
let timestamp = ConfigurationResource::fetch_config(resolver)
.map(|config| config.last_reconfiguration_time())
.unwrap_or(0);
let mut timed_features_builder = TimedFeaturesBuilder::new(chain_id, timestamp);
if let Some(profile) = Self::get_timed_feature_override() {
timed_features_builder = timed_features_builder.with_override_profile(profile)
}
let timed_features = timed_features_builder.build();
// If aggregator execution is enabled, we need to tag aggregator_v2 types,
// so they can be exchanged with identifiers during VM execution.
let override_is_delayed_field_optimization_capable =
override_is_delayed_field_optimization_capable
.unwrap_or_else(|| resolver.is_delayed_field_optimization_capable());
let aggregator_v2_type_tagging = override_is_delayed_field_optimization_capable
&& features.is_aggregator_v2_delayed_fields_enabled();
let move_vm = MoveVmExt::new(
native_gas_params,
misc_gas_params,
gas_feature_version,
chain_id.id(),
features,
timed_features.clone(),
resolver,
aggregator_v2_type_tagging,
)
.expect("should be able to create Move VM; check if there are duplicated natives");
// We use an `Option` to handle the VK not being set on-chain, or an incorrect VK being set
// via governance (although, currently, we do check for that in `keyless_account.move`).
let pvk = keyless_validation::get_groth16_vk_onchain(resolver)
.ok()
.and_then(|vk| {
// println!("[aptos-vm][groth16] PVK cached in VM: {}", vk.hash());
vk.try_into().ok()
});
Self {
is_simulation: false,
move_vm,
gas_feature_version,
gas_params,
storage_gas_params,
timed_features,
pvk,
randomness_api_v0_required_deposit,
}
}
pub fn new_session<'r, S: AptosMoveResolver>(
&self,
resolver: &'r S,
session_id: SessionId,
user_transaction_context_opt: Option<UserTransactionContext>,
) -> SessionExt<'r, '_> {
self.move_vm
.new_session(resolver, session_id, user_transaction_context_opt)
}
#[inline(always)]
fn features(&self) -> &Features {
self.move_vm.features()
}
/// Sets execution concurrency level when invoked the first time.
pub fn set_concurrency_level_once(mut concurrency_level: usize) {
concurrency_level = min(concurrency_level, num_cpus::get());
// Only the first call succeeds, due to OnceCell semantics.
EXECUTION_CONCURRENCY_LEVEL.set(concurrency_level).ok();
}
/// Get the concurrency level if already set, otherwise return default 1
/// (sequential execution).
///
/// The concurrency level is fixed to 1 if gas profiling is enabled.
pub fn get_concurrency_level() -> usize {
match EXECUTION_CONCURRENCY_LEVEL.get() {
Some(concurrency_level) => *concurrency_level,
None => 1,
}
}
pub fn set_num_shards_once(mut num_shards: usize) {
num_shards = max(num_shards, 1);
// Only the first call succeeds, due to OnceCell semantics.
NUM_EXECUTION_SHARD.set(num_shards).ok();
}
pub fn get_num_shards() -> usize {
match NUM_EXECUTION_SHARD.get() {
Some(num_shards) => *num_shards,
None => 1,
}
}
/// Sets runtime config when invoked the first time.
pub fn set_paranoid_type_checks(enable: bool) {
// Only the first call succeeds, due to OnceCell semantics.
PARANOID_TYPE_CHECKS.set(enable).ok();
}
/// Get the paranoid type check flag if already set, otherwise return default true
pub fn get_paranoid_checks() -> bool {
match PARANOID_TYPE_CHECKS.get() {
Some(enable) => *enable,
None => true,
}
}
/// Sets runtime config when invoked the first time.
pub fn set_discard_failed_blocks(enable: bool) {
// Only the first call succeeds, due to OnceCell semantics.
DISCARD_FAILED_BLOCKS.set(enable).ok();
}
/// Get the discard failed blocks flag if already set, otherwise return default (false)
pub fn get_discard_failed_blocks() -> bool {
match DISCARD_FAILED_BLOCKS.get() {
Some(enable) => *enable,
None => false,
}
}
// Set the override profile for timed features.
pub fn set_timed_feature_override(profile: TimedFeatureOverride) {
TIMED_FEATURE_OVERRIDE.set(profile).ok();
}
pub fn get_timed_feature_override() -> Option<TimedFeatureOverride> {
TIMED_FEATURE_OVERRIDE.get().cloned()
}
/// Sets the # of async proof reading threads.
pub fn set_num_proof_reading_threads_once(mut num_threads: usize) {
// TODO(grao): Do more analysis to tune this magic number.
num_threads = min(num_threads, 256);
// Only the first call succeeds, due to OnceCell semantics.
NUM_PROOF_READING_THREADS.set(num_threads).ok();
}
/// Returns the # of async proof reading threads if already set, otherwise return default value
/// (32).
pub fn get_num_proof_reading_threads() -> usize {
match NUM_PROOF_READING_THREADS.get() {
Some(num_threads) => *num_threads,
None => 32,
}
}
/// Sets additional details in counters when invoked the first time.
pub fn set_processed_transactions_detailed_counters() {
// Only the first call succeeds, due to OnceCell semantics.
PROCESSED_TRANSACTIONS_DETAILED_COUNTERS.set(true).ok();
}
/// Get whether we should capture additional details in counters
pub fn get_processed_transactions_detailed_counters() -> bool {
match PROCESSED_TRANSACTIONS_DETAILED_COUNTERS.get() {
Some(value) => *value,
None => false,
}
}
/// Returns the internal gas schedule if it has been loaded, or an error if it hasn't.
#[cfg(any(test, feature = "testing"))]
pub fn gas_params(&self) -> Result<&AptosGasParameters, VMStatus> {
let log_context = AdapterLogSchema::new(StateViewId::Miscellaneous, 0);
get_or_vm_startup_failure(&self.gas_params, &log_context)
}
pub fn as_move_resolver<'r, R: ExecutorView>(
&self,
executor_view: &'r R,
) -> StorageAdapter<'r, R> {
StorageAdapter::new_with_config(
executor_view,
self.gas_feature_version,
self.features(),
None,
)
}
pub fn as_move_resolver_with_group_view<'r, R: ExecutorView + ResourceGroupView>(
&self,
executor_view: &'r R,
) -> StorageAdapter<'r, R> {
StorageAdapter::new_with_config(
executor_view,
self.gas_feature_version,
self.features(),
Some(executor_view),
)
}
fn fee_statement_from_gas_meter(
txn_data: &TransactionMetadata,
gas_meter: &impl AptosGasMeter,
storage_fee_refund: u64,
) -> FeeStatement {
let gas_used = Self::gas_used(txn_data.max_gas_amount(), gas_meter);
FeeStatement::new(
gas_used,
u64::from(gas_meter.execution_gas_used()),
u64::from(gas_meter.io_gas_used()),
u64::from(gas_meter.storage_fee_used()),
storage_fee_refund,
)
}
pub(crate) fn failed_transaction_cleanup(
&self,
prologue_change_set: VMChangeSet,
error_vm_status: VMStatus,
gas_meter: &mut impl AptosGasMeter,
txn_data: &TransactionMetadata,
resolver: &impl AptosMoveResolver,
log_context: &AdapterLogSchema,
change_set_configs: &ChangeSetConfigs,
traversal_context: &mut TraversalContext,
) -> (VMStatus, VMOutput) {
if self.gas_feature_version >= 12 {
// Check if the gas meter's internal counters are consistent.
//
// Since we are already in the failure epilogue, there is not much we can do
// other than logging the inconsistency.
//
// This is a tradeoff. We have to either
// 1. Continue to calculate the gas cost based on the numbers we have.
// 2. Discard the transaction.
//
// Option (2) does not work, since it would enable DoS attacks.
// Option (1) is not ideal, but optimistically, it should allow the network
// to continue functioning, less the transactions that run into this problem.
if let Err(err) = gas_meter.algebra().check_consistency() {
println!(
"[aptos-vm][gas-meter][failure-epilogue] {}",
err.message()
.unwrap_or("No message found -- this should not happen.")
);
}
}
let (txn_status, txn_aux_data) = TransactionStatus::from_vm_status(
error_vm_status.clone(),
self.features()
.is_enabled(FeatureFlag::CHARGE_INVARIANT_VIOLATION),
self.features(),
);
match txn_status {
TransactionStatus::Keep(status) => {
// The transaction should be kept. Run the appropriate post transaction workflows
// including epilogue. This runs a new session that ignores any side effects that
// might abort the execution (e.g., spending additional funds needed to pay for
// gas). Even if the previous failure occurred while running the epilogue, it
// should not fail now. If it somehow fails here, there is no choice but to
// discard the transaction.
let txn_output = match self.finish_aborted_transaction(
prologue_change_set,
gas_meter,
txn_data,
resolver,
status,
log_context,
change_set_configs,
traversal_context,
) {
Ok((change_set, fee_statement, status)) => VMOutput::new(
change_set,
fee_statement,
TransactionStatus::Keep(status),
txn_aux_data,
),
Err(err) => discarded_output(err.status_code()),
};
(error_vm_status, txn_output)
},
TransactionStatus::Discard(status_code) => {
let discarded_output = discarded_output(status_code);
(error_vm_status, discarded_output)
},
TransactionStatus::Retry => unreachable!(),
}
}
fn inject_abort_info_if_available(&self, status: ExecutionStatus) -> ExecutionStatus {
match status {
ExecutionStatus::MoveAbort {
location: AbortLocation::Module(module),
code,
..
} => {
let info = self
.extract_module_metadata(&module)
.and_then(|m| m.extract_abort_info(code));
ExecutionStatus::MoveAbort {
location: AbortLocation::Module(module),
code,
info,
}
},
_ => status,
}
}
fn finish_aborted_transaction(
&self,
prologue_change_set: VMChangeSet,
gas_meter: &mut impl AptosGasMeter,
txn_data: &TransactionMetadata,
resolver: &impl AptosMoveResolver,
status: ExecutionStatus,
log_context: &AdapterLogSchema,
change_set_configs: &ChangeSetConfigs,
traversal_context: &mut TraversalContext,
) -> Result<(VMChangeSet, FeeStatement, ExecutionStatus), VMStatus> {
// Storage refund is zero since no slots are deleted in aborted transactions.
const ZERO_STORAGE_REFUND: u64 = 0;
let is_account_init_for_sponsored_transaction =
is_account_init_for_sponsored_transaction(txn_data, self.features(), resolver)?;
if is_account_init_for_sponsored_transaction {
let mut abort_hook_session =
AbortHookSession::new(self, txn_data, resolver, prologue_change_set)?;
// Abort information is injected using the user defined error in the Move contract.
let status = self.inject_abort_info_if_available(status);
abort_hook_session.execute(|session| {
create_account_if_does_not_exist(
session,
gas_meter,
txn_data.sender(),
traversal_context,
)
// if this fails, it is likely due to out of gas, so we try again without metering
// and then validate below that we charged sufficiently.
.or_else(|_err| {
create_account_if_does_not_exist(
session,
&mut UnmeteredGasMeter,
txn_data.sender(),
traversal_context,
)
})
.map_err(expect_no_verification_errors)
.or_else(|err| {
expect_only_successful_execution(
err,
&format!("{:?}::{}", ACCOUNT_MODULE, CREATE_ACCOUNT_IF_DOES_NOT_EXIST),
log_context,
)
})
})?;
let mut change_set = abort_hook_session.finish(change_set_configs)?;
if let Err(err) = self.charge_change_set(&mut change_set, gas_meter, txn_data, resolver)
{
info!(
*log_context,
"Failed during charge_change_set: {:?}. Most likely exceeded gas limited.", err,
);
};
let fee_statement =
AptosVM::fee_statement_from_gas_meter(txn_data, gas_meter, ZERO_STORAGE_REFUND);
// Verify we charged sufficiently for creating an account slot
let gas_params = get_or_vm_startup_failure(&self.gas_params, log_context)?;
let gas_unit_price = u64::from(txn_data.gas_unit_price());
let gas_used = fee_statement.gas_used();
let storage_fee = fee_statement.storage_fee_used();
let storage_refund = fee_statement.storage_fee_refund();
let actual = gas_used * gas_unit_price + storage_fee - storage_refund;
let expected = u64::from(
gas_meter
.disk_space_pricing()
.hack_account_creation_fee_lower_bound(&gas_params.vm.txn),
);
if actual < expected {
expect_only_successful_execution(
PartialVMError::new(StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR)
.with_message(
"Insufficient fee for storing account for sponsored transaction"
.to_string(),
)
.finish(Location::Undefined),
&format!("{:?}::{}", ACCOUNT_MODULE, CREATE_ACCOUNT_IF_DOES_NOT_EXIST),
log_context,
)?;
}
let mut epilogue_session = EpilogueSession::new(
self,
txn_data,
resolver,
change_set,
ZERO_STORAGE_REFUND.into(),
)?;
epilogue_session.execute(|session| {
transaction_validation::run_failure_epilogue(
session,
gas_meter.balance(),
fee_statement,
self.features(),
txn_data,
log_context,
traversal_context,
)
})?;
epilogue_session
.finish(change_set_configs)
.map(|set| (set, fee_statement, status))
} else {
let mut epilogue_session = EpilogueSession::new(
self,
txn_data,
resolver,
prologue_change_set,
ZERO_STORAGE_REFUND.into(),
)?;
let status = self.inject_abort_info_if_available(status);
let fee_statement =
AptosVM::fee_statement_from_gas_meter(txn_data, gas_meter, ZERO_STORAGE_REFUND);
epilogue_session.execute(|session| {
transaction_validation::run_failure_epilogue(
session,
gas_meter.balance(),
fee_statement,
self.features(),
txn_data,
log_context,
traversal_context,
)
})?;
epilogue_session
.finish(change_set_configs)
.map(|set| (set, fee_statement, status))
}
}
fn success_transaction_cleanup(
&self,
mut epilogue_session: EpilogueSession,
gas_meter: &impl AptosGasMeter,
txn_data: &TransactionMetadata,
log_context: &AdapterLogSchema,
change_set_configs: &ChangeSetConfigs,
traversal_context: &mut TraversalContext,
) -> Result<(VMStatus, VMOutput), VMStatus> {
if self.gas_feature_version >= 12 {
// Check if the gas meter's internal counters are consistent.
//
// It's better to fail the transaction due to invariant violation than to allow
// potentially bogus states to be committed.
if let Err(err) = gas_meter.algebra().check_consistency() {
println!(
"[aptos-vm][gas-meter][success-epilogue] {}",
err.message()
.unwrap_or("No message found -- this should not happen.")
);
return Err(err.finish(Location::Undefined).into());
}
}
let fee_statement = AptosVM::fee_statement_from_gas_meter(
txn_data,
gas_meter,
u64::from(epilogue_session.get_storage_fee_refund()),
);
epilogue_session.execute(|session| {
transaction_validation::run_success_epilogue(
session,
gas_meter.balance(),
fee_statement,
self.features(),
txn_data,
log_context,
traversal_context,
)
})?;
let change_set = epilogue_session.finish(change_set_configs)?;
let output = VMOutput::new(
change_set,
fee_statement,
TransactionStatus::Keep(ExecutionStatus::Success),
TransactionAuxiliaryData::default(),
);
Ok((VMStatus::Executed, output))
}
fn validate_and_execute_script(
&self,
session: &mut SessionExt,
// Note: cannot use AptosGasMeter because it is not implemented for
// UnmeteredGasMeter.
gas_meter: &mut impl GasMeter,
traversal_context: &mut TraversalContext,
senders: Vec<AccountAddress>,
script: &Script,
) -> Result<(), VMStatus> {
// Note: Feature gating is needed here because the traversal of the dependencies could
// result in shallow-loading of the modules and therefore subtle changes in
// the error semantics.
if self.gas_feature_version >= 15 {
session.check_script_dependencies_and_check_gas(
gas_meter,
traversal_context,
script.code(),
)?;
}
let loaded_func = session.load_script(script.code(), script.ty_args().to_vec())?;
// TODO(Gerardo): consolidate the extended validation to verifier.
verifier::event_validation::verify_no_event_emission_in_script(
script.code(),
&session.get_vm_config().deserializer_config,
)?;
let args = verifier::transaction_arg_validation::validate_combine_signer_and_txn_args(
session,
senders,
convert_txn_args(script.args()),
&loaded_func,
self.features().is_enabled(FeatureFlag::STRUCT_CONSTRUCTORS),
)?;
session.execute_script(
script.code(),
script.ty_args().to_vec(),
args,
gas_meter,
traversal_context,
)?;
Ok(())
}
fn validate_and_execute_entry_function(
&self,
resolver: &impl AptosMoveResolver,
session: &mut SessionExt,
gas_meter: &mut impl AptosGasMeter,
traversal_context: &mut TraversalContext,
senders: Vec<AccountAddress>,
entry_fn: &EntryFunction,
_txn_data: &TransactionMetadata,
) -> Result<(), VMStatus> {
// Note: Feature gating is needed here because the traversal of the dependencies could
// result in shallow-loading of the modules and therefore subtle changes in
// the error semantics.
if self.gas_feature_version >= 15 {
let module_id = traversal_context
.referenced_module_ids
.alloc(entry_fn.module().clone());
session.check_dependencies_and_charge_gas(gas_meter, traversal_context, [(
module_id.address(),
module_id.name(),
)])?;
}
let (function, is_friend_or_private) = session.load_function_and_is_friend_or_private_def(
entry_fn.module(),
entry_fn.function(),
entry_fn.ty_args(),
)?;
// The `has_randomness_attribute()` should have been feature-gated in 1.11...
if is_friend_or_private && has_randomness_attribute(resolver, session, entry_fn)? {
let txn_context = session
.get_native_extensions()
.get_mut::<RandomnessContext>();
txn_context.mark_unbiasable();
}
let struct_constructors_enabled =
self.features().is_enabled(FeatureFlag::STRUCT_CONSTRUCTORS);
let args = verifier::transaction_arg_validation::validate_combine_signer_and_txn_args(
session,
senders,
entry_fn.args().to_vec(),
&function,
struct_constructors_enabled,
)?;
session.execute_entry_function(
entry_fn.module(),
entry_fn.function(),
entry_fn.ty_args().to_vec(),
args,
gas_meter,
traversal_context,
)?;
Ok(())
}
fn execute_script_or_entry_function<'a, 'r, 'l>(
&'l self,
resolver: &'r impl AptosMoveResolver,
mut session: UserSession<'r, 'l>,
gas_meter: &mut impl AptosGasMeter,
traversal_context: &mut TraversalContext<'a>,
txn_data: &TransactionMetadata,
payload: &'a TransactionPayload,
log_context: &AdapterLogSchema,
new_published_modules_loaded: &mut bool,
change_set_configs: &ChangeSetConfigs,
) -> Result<(VMStatus, VMOutput), VMStatus> {
fail_point!("aptos_vm::execute_script_or_entry_function", |_| {
Err(VMStatus::Error {
status_code: StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR,
sub_status: Some(move_core_types::vm_status::sub_status::unknown_invariant_violation::EPARANOID_FAILURE),
message: None,
})
});
gas_meter.charge_intrinsic_gas_for_transaction(txn_data.transaction_size())?;
if txn_data.is_keyless() {
gas_meter.charge_keyless()?;
}
match payload {
TransactionPayload::Script(script) => {
session.execute(|session| {
self.validate_and_execute_script(
session,
gas_meter,
traversal_context,
txn_data.senders(),
script,
)
})?;
},
TransactionPayload::EntryFunction(entry_fn) => {
session.execute(|session| {
self.validate_and_execute_entry_function(
resolver,
session,
gas_meter,
traversal_context,
txn_data.senders(),
entry_fn,
txn_data,
)
})?;
},
// Not reachable as this function should only be invoked for entry or script
// transaction payload.
_ => unreachable!("Only scripts or entry functions are executed"),
};
session.execute(|session| {
self.resolve_pending_code_publish(
session,
gas_meter,
traversal_context,
new_published_modules_loaded,
)
})?;
let epilogue_session = self.charge_change_set_and_respawn_session(
session,
resolver,
gas_meter,
change_set_configs,
txn_data,
)?;
self.success_transaction_cleanup(
epilogue_session,
gas_meter,
txn_data,
log_context,
change_set_configs,
traversal_context,
)
}
fn charge_change_set(
&self,
change_set: &mut VMChangeSet,
gas_meter: &mut impl AptosGasMeter,
txn_data: &TransactionMetadata,
resolver: &impl AptosMoveResolver,
) -> Result<GasQuantity<Octa>, VMStatus> {
gas_meter.charge_io_gas_for_transaction(txn_data.transaction_size())?;
for (event, _layout) in change_set.events() {
gas_meter.charge_io_gas_for_event(event)?;
}
for (key, op_size) in change_set.write_set_size_iter() {
gas_meter.charge_io_gas_for_write(key, &op_size)?;
}
let mut storage_refund = gas_meter.process_storage_fee_for_all(
change_set,
txn_data.transaction_size,
txn_data.gas_unit_price,
resolver.as_executor_view(),
)?;
if !self.features().is_storage_deletion_refund_enabled() {
storage_refund = 0.into();
}
Ok(storage_refund)
}
fn charge_change_set_and_respawn_session<'r, 'l>(
&'l self,
user_session: UserSession<'r, 'l>,
resolver: &'r impl AptosMoveResolver,
gas_meter: &mut impl AptosGasMeter,
change_set_configs: &ChangeSetConfigs,
txn_data: &'l TransactionMetadata,
) -> Result<EpilogueSession<'r, 'l>, VMStatus> {
let mut change_set = user_session.finish(change_set_configs)?;
let storage_refund =
self.charge_change_set(&mut change_set, gas_meter, txn_data, resolver)?;
// TODO[agg_v1](fix): Charge for aggregator writes
EpilogueSession::new(self, txn_data, resolver, change_set, storage_refund)
}
fn simulate_multisig_transaction<'a, 'r, 'l>(
&'l self,
resolver: &'r impl AptosMoveResolver,
mut session: UserSession<'r, 'l>,
gas_meter: &mut impl AptosGasMeter,
traversal_context: &mut TraversalContext<'a>,
txn_data: &TransactionMetadata,
payload: &'a Multisig,
log_context: &AdapterLogSchema,
new_published_modules_loaded: &mut bool,
change_set_configs: &ChangeSetConfigs,
) -> Result<(VMStatus, VMOutput), VMStatus> {
match &payload.transaction_payload {
None => Err(VMStatus::error(StatusCode::MISSING_DATA, None)),
Some(multisig_payload) => {
match multisig_payload {
MultisigTransactionPayload::EntryFunction(entry_function) => {
aptos_try!({
return_on_failure!(session.execute(|session| self
.execute_multisig_entry_function(
resolver,
session,
gas_meter,
traversal_context,
payload.multisig_address,
entry_function,
new_published_modules_loaded,
txn_data,
)));
// TODO: Deduplicate this against execute_multisig_transaction
// A bit tricky since we need to skip success/failure cleanups,
// which is in the middle. Introducing a boolean would make the code
// messier.
let epilogue_session = self.charge_change_set_and_respawn_session(
session,
resolver,
gas_meter,
change_set_configs,
txn_data,
)?;