forked from casper-network/casper-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwasm_test_builder.rs
More file actions
1946 lines (1708 loc) · 69.5 KB
/
wasm_test_builder.rs
File metadata and controls
1946 lines (1708 loc) · 69.5 KB
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::{
collections::{BTreeMap, BTreeSet},
convert::{TryFrom, TryInto},
ffi::OsStr,
fs,
iter::{self, FromIterator},
ops::Deref,
path::{Path, PathBuf},
rc::Rc,
sync::Arc,
};
use filesize::PathExt;
use lmdb::DatabaseFlags;
use num_rational::Ratio;
use num_traits::{CheckedMul, Zero};
use tempfile::TempDir;
use casper_execution_engine::engine_state::{
Error, ExecutionEngineV1, WasmV1Request, WasmV1Result, DEFAULT_MAX_QUERY_DEPTH,
};
use casper_storage::{
data_access_layer::{
balance::BalanceHandling,
inactive_validators::{
InactiveValidatorsUndelegationRequest, InactiveValidatorsUndelegationResult,
},
AuctionMethod, BalanceIdentifier, BalanceRequest, BalanceResult, BiddingRequest,
BiddingResult, BidsRequest, BlockRewardsRequest, BlockRewardsResult, BlockStore,
DataAccessLayer, EraValidatorsRequest, EraValidatorsResult, FeeRequest, FeeResult,
FlushRequest, FlushResult, GenesisRequest, GenesisResult, ProofHandling,
ProtocolUpgradeRequest, ProtocolUpgradeResult, PruneRequest, PruneResult, QueryRequest,
QueryResult, RoundSeigniorageRateRequest, RoundSeigniorageRateResult, StepRequest,
StepResult, SystemEntityRegistryPayload, SystemEntityRegistryRequest,
SystemEntityRegistryResult, SystemEntityRegistrySelector, TotalSupplyRequest,
TotalSupplyResult, TransferRequest, TrieRequest,
},
global_state::{
state::{
lmdb::LmdbGlobalState, scratch::ScratchGlobalState, CommitProvider, ScratchProvider,
StateProvider, StateReader,
},
transaction_source::lmdb::LmdbEnvironment,
trie::Trie,
trie_store::lmdb::LmdbTrieStore,
},
system::runtime_native::{Config as NativeRuntimeConfig, TransferConfig},
tracking_copy::{TrackingCopyEntityExt, TrackingCopyExt},
AddressGenerator,
};
use casper_types::{
account::AccountHash,
addressable_entity::{EntityKindTag, NamedKeyAddr, NamedKeys},
bytesrepr::{self, FromBytes},
contracts::ContractHash,
execution::Effects,
global_state::TrieMerkleProof,
runtime_args,
system::{
auction::{
BidKind, EraValidators, UnbondingPurses, ValidatorWeights, WithdrawPurses,
ARG_ERA_END_TIMESTAMP_MILLIS, ARG_EVICTED_VALIDATORS, AUCTION_DELAY_KEY, ERA_ID_KEY,
METHOD_RUN_AUCTION, UNBONDING_DELAY_KEY,
},
mint::{MINT_GAS_HOLD_HANDLING_KEY, MINT_GAS_HOLD_INTERVAL_KEY},
AUCTION, HANDLE_PAYMENT, MINT, STANDARD_PAYMENT,
},
AccessRights, AddressableEntity, AddressableEntityHash, AuctionCosts, BlockGlobalAddr,
BlockTime, ByteCode, ByteCodeAddr, ByteCodeHash, CLTyped, CLValue, Contract, Digest,
EntityAddr, EntryPoints, EraId, Gas, HandlePaymentCosts, HoldBalanceHandling, InitiatorAddr,
Key, KeyTag, MintCosts, Motes, Package, PackageHash, Phase, ProtocolUpgradeConfig,
ProtocolVersion, PublicKey, RefundHandling, StoredValue, SystemEntityRegistry, TransactionHash,
TransactionV1Hash, URef, OS_PAGE_SIZE, U512,
};
use crate::{
chainspec_config::{ChainspecConfig, CHAINSPEC_SYMLINK},
ExecuteRequest, ExecuteRequestBuilder, StepRequestBuilder, DEFAULT_GAS_PRICE,
DEFAULT_PROPOSER_ADDR, DEFAULT_PROTOCOL_VERSION, SYSTEM_ADDR,
};
/// LMDB initial map size is calculated based on DEFAULT_LMDB_PAGES and systems page size.
pub(crate) const DEFAULT_LMDB_PAGES: usize = 256_000_000;
/// LMDB max readers
///
/// The default value is chosen to be the same as the node itself.
pub(crate) const DEFAULT_MAX_READERS: u32 = 512;
/// This is appended to the data dir path provided to the `LmdbWasmTestBuilder`".
const GLOBAL_STATE_DIR: &str = "global_state";
/// A wrapper structure that groups an entity alongside its namedkeys.
#[derive(Debug)]
pub struct EntityWithNamedKeys {
entity: AddressableEntity,
named_keys: NamedKeys,
}
impl EntityWithNamedKeys {
/// Creates a new instance of an Entity with its NamedKeys.
pub fn new(entity: AddressableEntity, named_keys: NamedKeys) -> Self {
Self { entity, named_keys }
}
/// Returns a reference to the Entity.
pub fn entity(&self) -> AddressableEntity {
self.entity.clone()
}
/// Returns a reference to the main purse for the inner entity.
pub fn main_purse(&self) -> URef {
self.entity.main_purse()
}
/// Returns a reference to the NamedKeys.
pub fn named_keys(&self) -> &NamedKeys {
&self.named_keys
}
}
/// Wasm test builder where Lmdb state is held in a automatically cleaned up temporary directory.
// pub type TempLmdbWasmTestBuilder = WasmTestBuilder<TemporaryLmdbGlobalState>;
/// Builder for simple WASM test
pub struct WasmTestBuilder<S> {
/// Data access layer.
data_access_layer: Arc<S>,
/// [`ExecutionEngineV1`] is wrapped in [`Rc`] to work around a missing [`Clone`]
/// implementation.
execution_engine: Rc<ExecutionEngineV1>,
/// The chainspec.
chainspec: ChainspecConfig,
exec_results: Vec<WasmV1Result>,
upgrade_results: Vec<ProtocolUpgradeResult>,
prune_results: Vec<PruneResult>,
genesis_hash: Option<Digest>,
/// Post state hash.
post_state_hash: Option<Digest>,
/// Cached effects after successful runs i.e. `effects[0]` is the collection of effects for
/// first exec call, etc.
effects: Vec<Effects>,
/// Genesis effects.
genesis_effects: Option<Effects>,
/// Cached system account.
system_account: Option<AddressableEntity>,
/// Scratch global state used for in-memory execution and commit optimization.
scratch_global_state: Option<ScratchGlobalState>,
/// Global state dir, for implementations that define one.
global_state_dir: Option<PathBuf>,
/// Temporary directory, for implementation that uses one.
temp_dir: Option<Rc<TempDir>>,
}
impl<S: ScratchProvider> WasmTestBuilder<S> {
/// Commit scratch to global state, and reset the scratch cache.
pub fn write_scratch_to_db(&mut self) -> &mut Self {
let prestate_hash = self.post_state_hash.expect("Should have genesis hash");
if let Some(scratch) = self.scratch_global_state.take() {
let new_state_root = self
.data_access_layer
.write_scratch_to_db(prestate_hash, scratch)
.unwrap();
self.post_state_hash = Some(new_state_root);
}
self
}
/// Flushes the LMDB environment to disk.
pub fn flush_environment(&self) {
let request = FlushRequest::new();
if let FlushResult::Failure(gse) = self.data_access_layer.flush(request) {
panic!("flush failed: {:?}", gse)
}
}
/// Execute and commit transforms from an ExecuteRequest into a scratch global state.
/// You MUST call write_scratch_to_lmdb to flush these changes to LmdbGlobalState.
#[allow(deprecated)]
pub fn scratch_exec_and_commit(&mut self, mut exec_request: WasmV1Request) -> &mut Self {
if self.scratch_global_state.is_none() {
self.scratch_global_state = Some(self.data_access_layer.get_scratch_global_state());
}
let cached_state = self
.scratch_global_state
.as_ref()
.expect("scratch state should exist");
exec_request.state_hash = self.post_state_hash.expect("expected post_state_hash");
// First execute the request against our scratch global state.
let execution_result = self.execution_engine.execute(cached_state, exec_request);
let _post_state_hash = cached_state
.commit(
self.post_state_hash.expect("requires a post_state_hash"),
execution_result.effects().clone(),
)
.expect("should commit");
// Save transforms and execution results for WasmTestBuilder.
self.effects.push(execution_result.effects().clone());
self.exec_results.push(execution_result);
self
}
}
impl<S> Clone for WasmTestBuilder<S> {
fn clone(&self) -> Self {
WasmTestBuilder {
data_access_layer: Arc::clone(&self.data_access_layer),
execution_engine: Rc::clone(&self.execution_engine),
chainspec: self.chainspec.clone(),
exec_results: self.exec_results.clone(),
upgrade_results: self.upgrade_results.clone(),
prune_results: self.prune_results.clone(),
genesis_hash: self.genesis_hash,
post_state_hash: self.post_state_hash,
effects: self.effects.clone(),
genesis_effects: self.genesis_effects.clone(),
system_account: self.system_account.clone(),
scratch_global_state: None,
global_state_dir: self.global_state_dir.clone(),
temp_dir: self.temp_dir.clone(),
}
}
}
#[derive(Copy, Clone, Debug)]
enum GlobalStateMode {
/// Creates empty lmdb database with specified flags
Create(DatabaseFlags),
/// Opens existing database
Open(Digest),
}
impl GlobalStateMode {
fn post_state_hash(self) -> Option<Digest> {
match self {
GlobalStateMode::Create(_) => None,
GlobalStateMode::Open(post_state_hash) => Some(post_state_hash),
}
}
}
/// Wasm test builder where state is held in LMDB.
pub type LmdbWasmTestBuilder = WasmTestBuilder<DataAccessLayer<LmdbGlobalState>>;
impl Default for LmdbWasmTestBuilder {
fn default() -> Self {
Self::new_temporary_with_chainspec(&*CHAINSPEC_SYMLINK)
}
}
impl LmdbWasmTestBuilder {
/// Upgrades the execution engine using the scratch trie.
pub fn upgrade_using_scratch(
&mut self,
upgrade_config: &mut ProtocolUpgradeConfig,
) -> &mut Self {
let pre_state_hash = self.post_state_hash.expect("should have state hash");
upgrade_config.with_pre_state_hash(pre_state_hash);
let scratch_state = self.data_access_layer.get_scratch_global_state();
let pre_state_hash = upgrade_config.pre_state_hash();
let req = ProtocolUpgradeRequest::new(upgrade_config.clone());
let result = {
let result = scratch_state.protocol_upgrade(req);
if let ProtocolUpgradeResult::Success { effects, .. } = result {
let post_state_hash = self
.data_access_layer
.write_scratch_to_db(pre_state_hash, scratch_state)
.unwrap();
self.post_state_hash = Some(post_state_hash);
let mut engine_config = self.chainspec.engine_config();
engine_config.set_protocol_version(upgrade_config.new_protocol_version());
self.execution_engine = Rc::new(ExecutionEngineV1::new(engine_config));
ProtocolUpgradeResult::Success {
post_state_hash,
effects,
}
} else {
result
}
};
self.upgrade_results.push(result);
self
}
/// Returns an [`LmdbWasmTestBuilder`] with configuration.
pub fn new_with_config<T: AsRef<OsStr> + ?Sized>(
data_dir: &T,
chainspec: ChainspecConfig,
) -> Self {
let _ = env_logger::try_init();
let page_size = *OS_PAGE_SIZE;
let global_state_dir = Self::global_state_dir(data_dir);
Self::create_global_state_dir(&global_state_dir);
let environment = Arc::new(
LmdbEnvironment::new(
&global_state_dir,
page_size * DEFAULT_LMDB_PAGES,
DEFAULT_MAX_READERS,
true,
)
.expect("should create LmdbEnvironment"),
);
let trie_store = Arc::new(
LmdbTrieStore::new(&environment, None, DatabaseFlags::empty())
.expect("should create LmdbTrieStore"),
);
let max_query_depth = DEFAULT_MAX_QUERY_DEPTH;
let global_state = LmdbGlobalState::empty(environment, trie_store, max_query_depth)
.expect("should create LmdbGlobalState");
let data_access_layer = Arc::new(DataAccessLayer {
block_store: BlockStore::new(),
state: global_state,
max_query_depth,
});
let engine_config = chainspec.engine_config();
let engine_state = ExecutionEngineV1::new(engine_config);
WasmTestBuilder {
data_access_layer,
execution_engine: Rc::new(engine_state),
chainspec,
exec_results: Vec::new(),
upgrade_results: Vec::new(),
prune_results: Vec::new(),
genesis_hash: None,
post_state_hash: None,
effects: Vec::new(),
system_account: None,
genesis_effects: None,
scratch_global_state: None,
global_state_dir: Some(global_state_dir),
temp_dir: None,
}
}
fn create_or_open<T: AsRef<Path>>(
global_state_dir: T,
chainspec: ChainspecConfig,
protocol_version: ProtocolVersion,
mode: GlobalStateMode,
) -> Self {
let _ = env_logger::try_init();
let page_size = *OS_PAGE_SIZE;
match mode {
GlobalStateMode::Create(_database_flags) => {}
GlobalStateMode::Open(_post_state_hash) => {
Self::create_global_state_dir(&global_state_dir)
}
}
let environment = LmdbEnvironment::new(
&global_state_dir,
page_size * DEFAULT_LMDB_PAGES,
DEFAULT_MAX_READERS,
true,
)
.expect("should create LmdbEnvironment");
let max_query_depth = DEFAULT_MAX_QUERY_DEPTH;
let global_state = match mode {
GlobalStateMode::Create(database_flags) => {
let trie_store = LmdbTrieStore::new(&environment, None, database_flags)
.expect("should open LmdbTrieStore");
LmdbGlobalState::empty(Arc::new(environment), Arc::new(trie_store), max_query_depth)
.expect("should create LmdbGlobalState")
}
GlobalStateMode::Open(post_state_hash) => {
let trie_store =
LmdbTrieStore::open(&environment, None).expect("should open LmdbTrieStore");
LmdbGlobalState::new(
Arc::new(environment),
Arc::new(trie_store),
post_state_hash,
max_query_depth,
)
}
};
let data_access_layer = Arc::new(DataAccessLayer {
block_store: BlockStore::new(),
state: global_state,
max_query_depth,
});
let mut engine_config = chainspec.engine_config();
engine_config.set_protocol_version(protocol_version);
let engine_state = ExecutionEngineV1::new(engine_config);
let post_state_hash = mode.post_state_hash();
let builder = WasmTestBuilder {
data_access_layer,
execution_engine: Rc::new(engine_state),
chainspec,
exec_results: Vec::new(),
upgrade_results: Vec::new(),
prune_results: Vec::new(),
genesis_hash: None,
post_state_hash,
effects: Vec::new(),
genesis_effects: None,
system_account: None,
scratch_global_state: None,
global_state_dir: Some(global_state_dir.as_ref().to_path_buf()),
temp_dir: None,
};
builder
}
/// Returns an [`LmdbWasmTestBuilder`] with configuration and values from
/// a given chainspec.
pub fn new_with_chainspec<T: AsRef<OsStr> + ?Sized, P: AsRef<Path>>(
data_dir: &T,
chainspec_path: P,
) -> Self {
let chainspec_config = ChainspecConfig::from_chainspec_path(chainspec_path)
.expect("must build chainspec configuration");
Self::new_with_config(data_dir, chainspec_config)
}
/// Returns an [`LmdbWasmTestBuilder`] with configuration and values from
/// the production chainspec.
pub fn new_with_production_chainspec<T: AsRef<OsStr> + ?Sized>(data_dir: &T) -> Self {
Self::new_with_chainspec(data_dir, &*CHAINSPEC_SYMLINK)
}
/// Returns a new [`LmdbWasmTestBuilder`].
pub fn new<T: AsRef<OsStr> + ?Sized>(data_dir: &T) -> Self {
Self::new_with_config(data_dir, Default::default())
}
/// Creates a new instance of builder using the supplied configurations, opening wrapped LMDBs
/// (e.g. in the Trie and Data stores) rather than creating them.
pub fn open<T: AsRef<OsStr> + ?Sized>(
data_dir: &T,
chainspec: ChainspecConfig,
protocol_version: ProtocolVersion,
post_state_hash: Digest,
) -> Self {
let global_state_path = Self::global_state_dir(data_dir);
Self::open_raw(
global_state_path,
chainspec,
protocol_version,
post_state_hash,
)
}
/// Creates a new instance of builder using the supplied configurations, opening wrapped LMDBs
/// (e.g. in the Trie and Data stores) rather than creating them.
/// Differs from `open` in that it doesn't append `GLOBAL_STATE_DIR` to the supplied path.
pub fn open_raw<T: AsRef<Path>>(
global_state_dir: T,
chainspec: ChainspecConfig,
protocol_version: ProtocolVersion,
post_state_hash: Digest,
) -> Self {
Self::create_or_open(
global_state_dir,
chainspec,
protocol_version,
GlobalStateMode::Open(post_state_hash),
)
}
/// Creates new temporary lmdb builder with an engine config instance.
///
/// Once [`LmdbWasmTestBuilder`] instance goes out of scope a global state directory will be
/// removed as well.
pub fn new_temporary_with_config(chainspec: ChainspecConfig) -> Self {
let temp_dir = tempfile::tempdir().unwrap();
let database_flags = DatabaseFlags::default();
let mut builder = Self::create_or_open(
temp_dir.path(),
chainspec,
DEFAULT_PROTOCOL_VERSION,
GlobalStateMode::Create(database_flags),
);
builder.temp_dir = Some(Rc::new(temp_dir));
builder
}
/// Creates new temporary lmdb builder with a path to a chainspec to load.
///
/// Once [`LmdbWasmTestBuilder`] instance goes out of scope a global state directory will be
/// removed as well.
pub fn new_temporary_with_chainspec<P: AsRef<Path>>(chainspec_path: P) -> Self {
let chainspec = ChainspecConfig::from_chainspec_path(chainspec_path)
.expect("must build chainspec configuration");
Self::new_temporary_with_config(chainspec)
}
fn create_global_state_dir<T: AsRef<Path>>(global_state_path: T) {
fs::create_dir_all(&global_state_path).unwrap_or_else(|_| {
panic!(
"Expected to create {}",
global_state_path.as_ref().display()
)
});
}
fn global_state_dir<T: AsRef<OsStr> + ?Sized>(data_dir: &T) -> PathBuf {
let mut path = PathBuf::from(data_dir);
path.push(GLOBAL_STATE_DIR);
path
}
/// Returns the file size on disk of the backing lmdb file behind LmdbGlobalState.
pub fn lmdb_on_disk_size(&self) -> Option<u64> {
if let Some(path) = self.global_state_dir.as_ref() {
let mut path = path.clone();
path.push("data.lmdb");
return path.as_path().size_on_disk().ok();
}
None
}
/// run step against scratch global state.
pub fn step_with_scratch(&mut self, step_request: StepRequest) -> &mut Self {
if self.scratch_global_state.is_none() {
self.scratch_global_state = Some(self.data_access_layer.get_scratch_global_state());
}
let cached_state = self
.scratch_global_state
.as_ref()
.expect("scratch state should exist");
match cached_state.step(step_request) {
StepResult::RootNotFound => {
panic!("Root not found")
}
StepResult::Failure(err) => {
panic!("{:?}", err)
}
StepResult::Success { .. } => {}
}
self
}
/// Runs a [`TransferRequest`] and commits the resulting effects.
pub fn transfer_and_commit(&mut self, mut transfer_request: TransferRequest) -> &mut Self {
let pre_state_hash = self.post_state_hash.expect("expected post_state_hash");
transfer_request.set_state_hash_and_config(pre_state_hash, self.native_runtime_config());
let transfer_result = self.data_access_layer.transfer(transfer_request);
let gas = Gas::new(self.chainspec.system_costs_config.mint_costs().transfer);
let execution_result = WasmV1Result::from_transfer_result(transfer_result, gas)
.expect("transfer result should map to wasm v1 result");
let effects = execution_result.effects().clone();
self.effects.push(effects.clone());
self.exec_results.push(execution_result);
self.commit_transforms(pre_state_hash, effects);
self
}
}
impl<S> WasmTestBuilder<S>
where
S: StateProvider + CommitProvider,
{
/// Takes a [`GenesisRequest`], executes the request and returns Self.
pub fn run_genesis(&mut self, request: GenesisRequest) -> &mut Self {
match self.data_access_layer.genesis(request) {
GenesisResult::Fatal(msg) => {
panic!("{}", msg);
}
GenesisResult::Failure(err) => {
panic!("{:?}", err);
}
GenesisResult::Success {
post_state_hash,
effects,
} => {
self.genesis_hash = Some(post_state_hash);
self.post_state_hash = Some(post_state_hash);
self.system_account = self.get_entity_by_account_hash(*SYSTEM_ADDR);
self.genesis_effects = Some(effects);
}
}
self
}
fn query_system_entity_registry(
&self,
post_state_hash: Option<Digest>,
) -> Option<SystemEntityRegistry> {
match self.query(post_state_hash, Key::SystemEntityRegistry, &[]) {
Ok(StoredValue::CLValue(cl_registry)) => {
let system_entity_registry =
CLValue::into_t::<SystemEntityRegistry>(cl_registry).unwrap();
Some(system_entity_registry)
}
Ok(_) => None,
Err(_) => None,
}
}
/// Queries state for a [`StoredValue`].
pub fn query(
&self,
maybe_post_state: Option<Digest>,
base_key: Key,
path: &[String],
) -> Result<StoredValue, String> {
let post_state = maybe_post_state
.or(self.post_state_hash)
.expect("builder must have a post-state hash");
let query_request = QueryRequest::new(post_state, base_key, path.to_vec());
let query_result = self.data_access_layer.query(query_request);
if let QueryResult::Success { value, .. } = query_result {
return Ok(value.deref().clone());
}
Err(format!("{:?}", query_result))
}
/// Query a named key in global state by account hash.
pub fn query_named_key_by_account_hash(
&self,
maybe_post_state: Option<Digest>,
account_hash: AccountHash,
name: &str,
) -> Result<StoredValue, String> {
let entity_addr = self
.get_entity_hash_by_account_hash(account_hash)
.map(|entity_hash| EntityAddr::new_account(entity_hash.value()))
.expect("must get EntityAddr");
self.query_named_key(maybe_post_state, entity_addr, name)
}
/// Query a named key.
pub fn query_named_key(
&self,
maybe_post_state: Option<Digest>,
entity_addr: EntityAddr,
name: &str,
) -> Result<StoredValue, String> {
let named_key_addr = NamedKeyAddr::new_from_string(entity_addr, name.to_string())
.expect("could not create named key address");
let empty_path: Vec<String> = vec![];
let maybe_stored_value = self
.query(maybe_post_state, Key::NamedKey(named_key_addr), &empty_path)
.expect("no stored value found");
let key = maybe_stored_value
.as_cl_value()
.map(|cl_val| CLValue::into_t::<Key>(cl_val.clone()))
.expect("must be cl_value")
.expect("must get key");
self.query(maybe_post_state, key, &[])
}
/// Queries state for a dictionary item.
pub fn query_dictionary_item(
&self,
maybe_post_state: Option<Digest>,
dictionary_seed_uref: URef,
dictionary_item_key: &str,
) -> Result<StoredValue, String> {
let dictionary_address =
Key::dictionary(dictionary_seed_uref, dictionary_item_key.as_bytes());
let empty_path: Vec<String> = vec![];
self.query(maybe_post_state, dictionary_address, &empty_path)
}
/// Queries for a [`StoredValue`] and returns the [`StoredValue`] and a Merkle proof.
pub fn query_with_proof(
&self,
maybe_post_state: Option<Digest>,
base_key: Key,
path: &[String],
) -> Result<(StoredValue, Vec<TrieMerkleProof<Key, StoredValue>>), String> {
let post_state = maybe_post_state
.or(self.post_state_hash)
.expect("builder must have a post-state hash");
let path_vec: Vec<String> = path.to_vec();
let query_request = QueryRequest::new(post_state, base_key, path_vec);
let query_result = self.data_access_layer.query(query_request);
if let QueryResult::Success { value, proofs } = query_result {
return Ok((value.deref().clone(), proofs));
}
panic! {"{:?}", query_result};
}
/// Queries for the total supply of token.
/// # Panics
/// Panics if the total supply can't be found.
pub fn total_supply(
&self,
protocol_version: ProtocolVersion,
maybe_post_state: Option<Digest>,
) -> U512 {
let post_state = maybe_post_state
.or(self.post_state_hash)
.expect("builder must have a post-state hash");
let result = self
.data_access_layer
.total_supply(TotalSupplyRequest::new(post_state, protocol_version));
if let TotalSupplyResult::Success { total_supply } = result {
total_supply
} else {
panic!("total supply should exist at every root hash {:?}", result);
}
}
/// Queries for the round seigniorage rate.
/// # Panics
/// Panics if the total supply or seigniorage rate can't be found.
pub fn round_seigniorage_rate(
&mut self,
maybe_post_state: Option<Digest>,
protocol_version: ProtocolVersion,
) -> Ratio<U512> {
let post_state = maybe_post_state
.or(self.post_state_hash)
.expect("builder must have a post-state hash");
let result =
self.data_access_layer
.round_seigniorage_rate(RoundSeigniorageRateRequest::new(
post_state,
protocol_version,
));
if let RoundSeigniorageRateResult::Success { rate } = result {
rate
} else {
panic!(
"round seigniorage rate should exist at every root hash {:?}",
result
);
}
}
/// Queries for the base round reward.
/// # Panics
/// Panics if the total supply or seigniorage rate can't be found.
pub fn base_round_reward(
&mut self,
maybe_post_state: Option<Digest>,
protocol_version: ProtocolVersion,
) -> U512 {
let post_state = maybe_post_state
.or(self.post_state_hash)
.expect("builder must have a post-state hash");
let total_supply = self.total_supply(protocol_version, Some(post_state));
let rate = self.round_seigniorage_rate(Some(post_state), protocol_version);
rate.checked_mul(&Ratio::from(total_supply))
.map(|ratio| ratio.to_integer())
.expect("must get base round reward")
}
/// Direct auction interactions for stake management.
pub fn bidding(
&mut self,
maybe_post_state: Option<Digest>,
protocol_version: ProtocolVersion,
initiator: InitiatorAddr,
auction_method: AuctionMethod,
) -> BiddingResult {
let post_state = maybe_post_state
.or(self.post_state_hash)
.expect("builder must have a post-state hash");
let transaction_hash = TransactionHash::V1(TransactionV1Hash::default());
let authorization_keys = BTreeSet::from_iter(iter::once(initiator.account_hash()));
let config = &self.chainspec;
let fee_handling = config.core_config.fee_handling;
let refund_handling = config.core_config.refund_handling;
let vesting_schedule_period_millis = config.core_config.vesting_schedule_period.millis();
let allow_auction_bids = config.core_config.allow_auction_bids;
let compute_rewards = config.core_config.compute_rewards;
let max_delegators_per_validator = config.core_config.max_delegators_per_validator;
let minimum_delegation_amount = config.core_config.minimum_delegation_amount;
let balance_hold_interval = config.core_config.gas_hold_interval.millis();
let native_runtime_config = casper_storage::system::runtime_native::Config::new(
TransferConfig::Unadministered,
fee_handling,
refund_handling,
vesting_schedule_period_millis,
allow_auction_bids,
compute_rewards,
max_delegators_per_validator,
minimum_delegation_amount,
balance_hold_interval,
);
let bidding_req = BiddingRequest::new(
native_runtime_config,
post_state,
protocol_version,
transaction_hash,
initiator,
authorization_keys,
auction_method,
);
self.data_access_layer().bidding(bidding_req)
}
/// Runs an optional custom payment [`WasmV1Request`] and a session `WasmV1Request`.
///
/// If the custom payment is `Some` and its execution fails, the session request is not
/// attempted.
pub fn exec(&mut self, mut execute_request: ExecuteRequest) -> &mut Self {
let mut effects = Effects::new();
if let Some(mut payment) = execute_request.custom_payment {
payment.state_hash = self.post_state_hash.expect("expected post_state_hash");
let payment_result = self
.execution_engine
.execute(self.data_access_layer.as_ref(), payment);
// If executing payment code failed, record this and exit without attempting session
// execution.
effects = payment_result.effects().clone();
let payment_failed = payment_result.error().is_some();
self.exec_results.push(payment_result);
if payment_failed {
self.effects.push(effects);
return self;
}
}
execute_request.session.state_hash =
self.post_state_hash.expect("expected post_state_hash");
let session_result = self
.execution_engine
.execute(self.data_access_layer.as_ref(), execute_request.session);
// Cache transformations
effects.append(session_result.effects().clone());
self.effects.push(effects);
self.exec_results.push(session_result);
self
}
/// Execute a `WasmV1Request`.
pub fn exec_wasm_v1(&mut self, mut request: WasmV1Request) -> &mut Self {
request.state_hash = self.post_state_hash.expect("expected post_state_hash");
let result = self
.execution_engine
.execute(self.data_access_layer.as_ref(), request);
let effects = result.effects().clone();
self.exec_results.push(result);
self.effects.push(effects);
self
}
/// Commit effects of previous exec call on the latest post-state hash.
pub fn commit(&mut self) -> &mut Self {
let prestate_hash = self.post_state_hash.expect("Should have genesis hash");
let effects = self.effects.last().cloned().unwrap_or_default();
self.commit_transforms(prestate_hash, effects)
}
/// Runs a commit request, expects a successful response, and
/// overwrites existing cached post state hash with a new one.
pub fn commit_transforms(&mut self, pre_state_hash: Digest, effects: Effects) -> &mut Self {
let post_state_hash = self
.data_access_layer
.commit(pre_state_hash, effects)
.expect("should commit");
self.post_state_hash = Some(post_state_hash);
self
}
/// Upgrades the execution engine.
pub fn upgrade(&mut self, upgrade_config: &mut ProtocolUpgradeConfig) -> &mut Self {
let pre_state_hash = self.post_state_hash.expect("should have state hash");
upgrade_config.with_pre_state_hash(pre_state_hash);
let req = ProtocolUpgradeRequest::new(upgrade_config.clone());
let result = self.data_access_layer.protocol_upgrade(req);
if let ProtocolUpgradeResult::Success {
post_state_hash, ..
} = result
{
let mut engine_config = self.chainspec.engine_config();
engine_config.set_protocol_version(upgrade_config.new_protocol_version());
self.execution_engine = Rc::new(ExecutionEngineV1::new(engine_config));
self.post_state_hash = Some(post_state_hash);
}
self.upgrade_results.push(result);
self
}
/// Executes a request to call the system auction contract.
pub fn run_auction(
&mut self,
era_end_timestamp_millis: u64,
evicted_validators: Vec<PublicKey>,
) -> &mut Self {
let auction = self.get_auction_contract_hash();
let exec_request = ExecuteRequestBuilder::contract_call_by_hash(
*SYSTEM_ADDR,
auction,
METHOD_RUN_AUCTION,
runtime_args! {
ARG_ERA_END_TIMESTAMP_MILLIS => era_end_timestamp_millis,
ARG_EVICTED_VALIDATORS => evicted_validators,
},
)
.build();
self.exec(exec_request).expect_success().commit()
}
/// Increments engine state.
pub fn step(&mut self, step_request: StepRequest) -> StepResult {
let step_result = self.data_access_layer.step(step_request);
if let StepResult::Success {
post_state_hash, ..
} = step_result
{
self.post_state_hash = Some(post_state_hash);
}
step_result
}
fn native_runtime_config(&self) -> NativeRuntimeConfig {
let administrators: BTreeSet<AccountHash> = self
.chainspec
.core_config
.administrators
.iter()
.map(|x| x.to_account_hash())
.collect();
let allow_unrestricted = self.chainspec.core_config.allow_unrestricted_transfers;
let transfer_config = TransferConfig::new(administrators, allow_unrestricted);
NativeRuntimeConfig::new(
transfer_config,
self.chainspec.core_config.fee_handling,
self.chainspec.core_config.refund_handling,
self.chainspec.core_config.vesting_schedule_period.millis(),
self.chainspec.core_config.allow_auction_bids,
self.chainspec.core_config.compute_rewards,
self.chainspec.core_config.max_delegators_per_validator,
self.chainspec.core_config.minimum_delegation_amount,
self.chainspec.core_config.gas_hold_interval.millis(),
)
}
/// Distribute fees.
pub fn distribute_fees(
&mut self,
pre_state_hash: Option<Digest>,
protocol_version: ProtocolVersion,
block_time: u64,
) -> FeeResult {
let native_runtime_config = self.native_runtime_config();
let pre_state_hash = pre_state_hash.or(self.post_state_hash).unwrap();
let fee_req = FeeRequest::new(
native_runtime_config,
pre_state_hash,
protocol_version,
block_time.into(),
);
let fee_result = self.data_access_layer.distribute_fees(fee_req);
if let FeeResult::Success {
post_state_hash, ..
} = fee_result
{
self.post_state_hash = Some(post_state_hash);
}
fee_result
}
/// Distributes the rewards.
pub fn distribute(
&mut self,
pre_state_hash: Option<Digest>,
protocol_version: ProtocolVersion,
rewards: BTreeMap<PublicKey, U512>,