casper-execution-engine 9.0.0

Casper execution engine crates.
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
use std::{cell::RefCell, collections::BTreeSet, convert::TryInto, iter::FromIterator, rc::Rc};

use rand::RngCore;

use casper_storage::{
    global_state::state::lmdb::LmdbGlobalStateView, tracking_copy::new_temporary_tracking_copy,
    AddressGenerator, TrackingCopy,
};

use super::{AllowInstallUpgrade, ExecError, RuntimeContext};
use crate::engine_state::{BlockInfo, EngineConfig, EngineConfigBuilder};
use casper_types::{
    account::{
        AccountHash, AddKeyFailure, RemoveKeyFailure, SetThresholdFailure, ACCOUNT_HASH_LENGTH,
    },
    addressable_entity::{ActionType, AssociatedKeys, EntryPoints, Weight},
    bytesrepr::ToBytes,
    contracts::NamedKeys,
    execution::TransformKindV2,
    system::{AUCTION, HANDLE_PAYMENT, MINT, STANDARD_PAYMENT},
    AccessRights, AddressableEntity, AddressableEntityHash, BlockGlobalAddr, BlockHash, BlockTime,
    ByteCodeHash, CLValue, ContextAccessRights, Digest, EntityAddr, EntityKind, EntryPointType,
    Gas, HashAddr, Key, PackageHash, Phase, ProtocolVersion, PublicKey, RuntimeArgs,
    RuntimeFootprint, SecretKey, StoredValue, SystemHashRegistry, Tagged, Timestamp,
    TransactionHash, TransactionV1Hash, URef, KEY_HASH_LENGTH, U256, U512,
};
use tempfile::TempDir;

const TXN_HASH_RAW: [u8; 32] = [1u8; 32];
const PHASE: Phase = Phase::Session;
const GAS_LIMIT: u64 = 500_000_000_000_000u64;

fn test_engine_config() -> EngineConfig {
    EngineConfig::default()
}

fn new_tracking_copy(
    account_hash: AccountHash,
    init_entity_key: Key,
    init_entity: AddressableEntity,
) -> (TrackingCopy<LmdbGlobalStateView>, TempDir) {
    let entity_key_cl_value = CLValue::from_t(init_entity_key).expect("must convert to cl value");

    let initial_data = [
        (init_entity_key, StoredValue::AddressableEntity(init_entity)),
        (
            Key::Account(account_hash),
            StoredValue::CLValue(entity_key_cl_value),
        ),
    ];
    new_temporary_tracking_copy(initial_data, None, true)
}

fn new_addressable_entity_with_purse(
    account_hash: AccountHash,
    entity_hash: AddressableEntityHash,
    entity_kind: EntityKind,
    purse: [u8; 32],
) -> (Key, Key, AddressableEntity) {
    let associated_keys = AssociatedKeys::new(account_hash, Weight::new(1));
    let entity = AddressableEntity::new(
        PackageHash::default(),
        ByteCodeHash::default(),
        ProtocolVersion::V2_0_0,
        URef::new(purse, AccessRights::READ_ADD_WRITE),
        associated_keys,
        Default::default(),
        entity_kind,
    );
    let account_key = Key::Account(account_hash);
    let contract_key = Key::addressable_entity_key(entity_kind.tag(), entity_hash);

    (account_key, contract_key, entity)
}

fn new_addressable_entity(
    account_hash: AccountHash,
    entity_hash: AddressableEntityHash,
) -> (Key, Key, AddressableEntity) {
    new_addressable_entity_with_purse(
        account_hash,
        entity_hash,
        EntityKind::Account(account_hash),
        [0; 32],
    )
}

// create random account key.
fn random_account_key<G: RngCore>(entropy_source: &mut G) -> Key {
    let mut key = [0u8; 32];
    entropy_source.fill_bytes(&mut key);
    Key::Account(AccountHash::new(key))
}

// create random contract key.
fn random_contract_key<G: RngCore>(entropy_source: &mut G) -> Key {
    let mut key_hash = [0u8; 32];
    entropy_source.fill_bytes(&mut key_hash);
    Key::AddressableEntity(EntityAddr::SmartContract(key_hash))
}

// Create URef Key.
fn create_uref_as_key(address_generator: &mut AddressGenerator, rights: AccessRights) -> Key {
    let address = address_generator.create_address();
    Key::URef(URef::new(address, rights))
}

fn random_hash<G: RngCore>(entropy_source: &mut G) -> Key {
    let mut key = [0u8; KEY_HASH_LENGTH];
    entropy_source.fill_bytes(&mut key);
    Key::Hash(key)
}

fn new_runtime_context<'a>(
    addressable_entity: &'a AddressableEntity,
    account_hash: AccountHash,
    entity_address: Key,
    named_keys: &'a mut NamedKeys,
    access_rights: ContextAccessRights,
    address_generator: AddressGenerator,
) -> (RuntimeContext<'a, LmdbGlobalStateView>, TempDir) {
    let (mut tracking_copy, tempdir) =
        new_tracking_copy(account_hash, entity_address, addressable_entity.clone());

    let mint_hash = HashAddr::default();

    let default_system_registry = {
        let mut registry = SystemHashRegistry::new();
        registry.insert(MINT.to_string(), mint_hash);
        registry.insert(HANDLE_PAYMENT.to_string(), HashAddr::default());
        registry.insert(STANDARD_PAYMENT.to_string(), HashAddr::default());
        registry.insert(AUCTION.to_string(), HashAddr::default());
        StoredValue::CLValue(CLValue::from_t(registry).unwrap())
    };

    tracking_copy.write(Key::SystemEntityRegistry, default_system_registry);
    tracking_copy.write(
        Key::Account(account_hash),
        StoredValue::CLValue(CLValue::from_t(entity_address).expect("must get cl_value")),
    );
    tracking_copy.write(
        entity_address,
        StoredValue::AddressableEntity(addressable_entity.clone()),
    );

    // write block time to gs
    let now = Timestamp::now();
    let cl_value = CLValue::from_t(now.millis()).expect("should get cl_value");
    let stored_value = StoredValue::CLValue(cl_value);
    tracking_copy.write(Key::BlockGlobal(BlockGlobalAddr::BlockTime), stored_value);

    // write protocol version to gs
    let protocol_version = ProtocolVersion::V2_0_0;
    let cl_value = CLValue::from_t(protocol_version.destructure()).expect("should get cl_value");
    let stored_value = StoredValue::CLValue(cl_value);
    tracking_copy.write(
        Key::BlockGlobal(BlockGlobalAddr::ProtocolVersion),
        stored_value,
    );

    // write the addressable entity flag to gs
    let cl_value = CLValue::from_t(false).expect("should get cl_value");
    let stored_value = StoredValue::CLValue(cl_value);
    tracking_copy.write(
        Key::BlockGlobal(BlockGlobalAddr::AddressableEntity),
        stored_value,
    );

    let addr = match entity_address {
        Key::AddressableEntity(entity_addr) => entity_addr,
        Key::Account(account_hash) => EntityAddr::Account(account_hash.value()),
        Key::Hash(hash) => EntityAddr::SmartContract(hash),
        _ => panic!("unexpected key"),
    };

    let runtime_footprint = RuntimeFootprint::new_entity_footprint(
        addr,
        addressable_entity.clone(),
        named_keys.clone(),
        EntryPoints::new(),
    );

    let engine_config = {
        let config_builder = EngineConfigBuilder::new();
        config_builder.with_enable_entity(true).build()
    };

    let runtime_context = RuntimeContext::new(
        named_keys,
        Rc::new(RefCell::new(runtime_footprint)),
        entity_address,
        BTreeSet::from_iter(vec![account_hash]),
        access_rights,
        account_hash,
        Rc::new(RefCell::new(address_generator)),
        Rc::new(RefCell::new(tracking_copy)),
        engine_config,
        BlockInfo::new(
            Digest::default(),
            BlockTime::new(0),
            BlockHash::default(),
            0,
            ProtocolVersion::V2_0_0,
        ),
        TransactionHash::V1(TransactionV1Hash::from_raw([1u8; 32])),
        Phase::Session,
        RuntimeArgs::new(),
        Gas::new(U512::from(GAS_LIMIT)),
        Gas::default(),
        Vec::default(),
        U512::MAX,
        EntryPointType::Caller,
        AllowInstallUpgrade::Forbidden,
    );

    (runtime_context, tempdir)
}

#[allow(clippy::assertions_on_constants)]
fn assert_forged_reference<T>(result: Result<T, ExecError>) {
    match result {
        Err(ExecError::ForgedReference(_)) => assert!(true),
        _ => panic!("Error. Test should have failed with ForgedReference error but didn't."),
    }
}

#[allow(clippy::assertions_on_constants)]
fn assert_invalid_access<T: std::fmt::Debug>(
    result: Result<T, ExecError>,
    expecting: AccessRights,
) {
    match result {
        Err(ExecError::InvalidAccess { required }) if required == expecting => assert!(true),
        other => panic!(
            "Error. Test should have failed with InvalidAccess error but didn't: {:?}.",
            other
        ),
    }
}

fn build_runtime_context_and_execute<T, F>(
    mut named_keys: NamedKeys,
    functor: F,
) -> Result<T, ExecError>
where
    F: FnOnce(RuntimeContext<LmdbGlobalStateView>) -> Result<T, ExecError>,
{
    let secret_key = SecretKey::ed25519_from_bytes([222; SecretKey::ED25519_LENGTH])
        .expect("should create secret key");
    let public_key = PublicKey::from(&secret_key);
    let account_hash = public_key.to_account_hash();
    let entity_hash = AddressableEntityHash::new([10u8; 32]);
    let deploy_hash = [1u8; 32];
    let (_, entity_key, addressable_entity) =
        new_addressable_entity(public_key.to_account_hash(), entity_hash);

    let address_generator = AddressGenerator::new(&deploy_hash, Phase::Session);
    let access_rights = addressable_entity.extract_access_rights(entity_hash, &named_keys);
    let (runtime_context, _tempdir) = new_runtime_context(
        &addressable_entity,
        account_hash,
        entity_key,
        &mut named_keys,
        access_rights,
        address_generator,
    );

    functor(runtime_context)
}

#[track_caller]
fn last_transform_kind_on_addressable_entity(
    runtime_context: &RuntimeContext<LmdbGlobalStateView>,
) -> TransformKindV2 {
    let key = runtime_context.context_key;
    runtime_context
        .effects()
        .transforms()
        .iter()
        .rev()
        .find_map(|transform| (transform.key() == &key).then(|| transform.kind().clone()))
        .unwrap()
}

#[test]
fn use_uref_valid() {
    // Test fixture
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref_as_key = create_uref_as_key(&mut rng, AccessRights::READ_WRITE);
    let mut named_keys = NamedKeys::new();
    named_keys.insert(String::new(), uref_as_key);
    // Use uref as the key to perform an action on the global state.
    // This should succeed because the uref is valid.
    let value = StoredValue::CLValue(CLValue::from_t(43_i32).unwrap());
    let result = build_runtime_context_and_execute(named_keys, |mut rc| {
        rc.metered_write_gs(uref_as_key, value)
    });
    result.expect("writing using valid uref should succeed");
}

#[test]
fn use_uref_forged() {
    // Test fixture
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref = create_uref_as_key(&mut rng, AccessRights::READ_WRITE);
    let named_keys = NamedKeys::new();
    // named_keys.insert(String::new(), Key::from(uref));
    let value = StoredValue::CLValue(CLValue::from_t(43_i32).unwrap());
    let result =
        build_runtime_context_and_execute(named_keys, |mut rc| rc.metered_write_gs(uref, value));

    assert_forged_reference(result);
}

#[test]
fn account_key_not_writeable() {
    let mut rng = rand::thread_rng();
    let acc_key = random_account_key(&mut rng);
    let result = build_runtime_context_and_execute(NamedKeys::new(), |mut rc| {
        rc.metered_write_gs(
            acc_key,
            StoredValue::CLValue(CLValue::from_t(1_i32).unwrap()),
        )
    });
    assert_invalid_access(result, AccessRights::WRITE);
}

#[test]
fn entity_key_readable_valid() {
    // Entity key is readable if it is a "base" key - current context of the
    // execution.
    let result = build_runtime_context_and_execute(NamedKeys::new(), |rc| {
        let context_key = rc.get_context_key();
        let runtime_footprint = rc.runtime_footprint();

        let entity_hash = runtime_footprint.borrow().hash_addr();
        let key_hash = context_key.into_entity_hash_addr().expect("must get hash");

        assert_eq!(entity_hash, key_hash);
        Ok(())
    });

    assert!(result.is_ok());
}

#[test]
fn account_key_addable_returns_type_mismatch() {
    // Account key is not addable anymore as we do not store an account underneath they key
    // but instead there is a CLValue which acts as an indirection to the corresponding entity.
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref_as_key = create_uref_as_key(&mut rng, AccessRights::READ);
    let mut named_keys = NamedKeys::new();
    named_keys.insert(String::new(), uref_as_key);
    let result = build_runtime_context_and_execute(named_keys, |mut rc| {
        let account_key: Key = rc.account_hash.into();
        let uref_name = "NewURef".to_owned();
        let named_key = StoredValue::CLValue(CLValue::from_t((uref_name, uref_as_key)).unwrap());

        rc.metered_add_gs(account_key, named_key)
    });

    assert!(result.is_err());
}

#[test]
fn account_key_addable_invalid() {
    // Account key is NOT addable if it is a "base" key - current context of the
    // execution.
    let mut rng = rand::thread_rng();
    let other_acc_key = random_account_key(&mut rng);

    let result = build_runtime_context_and_execute(NamedKeys::new(), |mut rc| {
        rc.metered_add_gs(
            other_acc_key,
            StoredValue::CLValue(CLValue::from_t(1_i32).unwrap()),
        )
    });

    assert_invalid_access(result, AccessRights::ADD);
}

#[test]
fn contract_key_readable_valid() {
    // Account key is readable if it is a "base" key - current context of the
    // execution.
    let mut rng = rand::thread_rng();
    let contract_key = random_contract_key(&mut rng);
    let result =
        build_runtime_context_and_execute(NamedKeys::new(), |mut rc| rc.read_gs(&contract_key));

    assert!(result.is_ok());
}

#[test]
fn contract_key_not_writeable() {
    // Account key is readable if it is a "base" key - current context of the
    // execution.
    let mut rng = rand::thread_rng();
    let contract_key = random_contract_key(&mut rng);
    let result = build_runtime_context_and_execute(NamedKeys::new(), |mut rc| {
        rc.metered_write_gs(
            contract_key,
            StoredValue::CLValue(CLValue::from_t(1_i32).unwrap()),
        )
    });

    assert_invalid_access(result, AccessRights::WRITE);
}

#[test]
fn contract_key_addable_valid() {
    // Contract key is addable if it is a "base" key - current context of the execution.
    let account_hash = AccountHash::new([0u8; 32]);
    let entity_hash = AddressableEntityHash::new([1u8; 32]);
    let (_account_key, entity_key, entity) = new_addressable_entity(account_hash, entity_hash);
    let authorization_keys = BTreeSet::from_iter(vec![account_hash]);
    let mut address_generator = AddressGenerator::new(&TXN_HASH_RAW, PHASE);

    let mut rng = rand::thread_rng();
    let contract_key = random_contract_key(&mut rng);
    let entity_as_stored_value = StoredValue::AddressableEntity(AddressableEntity::default());
    let mut access_rights = entity_as_stored_value
        .as_addressable_entity()
        .unwrap()
        .extract_access_rights(AddressableEntityHash::default(), &NamedKeys::new());

    let (tracking_copy, _tempdir) = new_tracking_copy(account_hash, entity_key, entity);
    let tracking_copy = Rc::new(RefCell::new(tracking_copy));
    tracking_copy
        .borrow_mut()
        .write(contract_key, entity_as_stored_value.clone());

    let default_system_registry = {
        let mut registry = SystemHashRegistry::new();
        registry.insert(MINT.to_string(), HashAddr::default());
        registry.insert(HANDLE_PAYMENT.to_string(), HashAddr::default());
        registry.insert(STANDARD_PAYMENT.to_string(), HashAddr::default());
        registry.insert(AUCTION.to_string(), HashAddr::default());
        StoredValue::CLValue(CLValue::from_t(registry).unwrap())
    };

    tracking_copy
        .borrow_mut()
        .write(Key::SystemEntityRegistry, default_system_registry);

    let uref_as_key = create_uref_as_key(&mut address_generator, AccessRights::WRITE);
    let uref_name = "NewURef".to_owned();
    let named_uref_tuple =
        StoredValue::CLValue(CLValue::from_t((uref_name.clone(), uref_as_key)).unwrap());
    let mut named_keys = NamedKeys::new();
    named_keys.insert(uref_name, uref_as_key);

    access_rights.extend(&[uref_as_key.into_uref().expect("should be a URef")]);

    let addr = match contract_key {
        Key::AddressableEntity(entity_addr) => entity_addr,
        Key::Account(account_hash) => EntityAddr::Account(account_hash.value()),
        Key::Hash(hash) => EntityAddr::SmartContract(hash),
        _ => panic!("unexpected key"),
    };

    let runtime_footprint = RuntimeFootprint::new_entity_footprint(
        addr,
        AddressableEntity::default(),
        named_keys.clone(),
        EntryPoints::new(),
    );

    let mut runtime_context = RuntimeContext::new(
        &mut named_keys,
        Rc::new(RefCell::new(runtime_footprint)),
        contract_key,
        authorization_keys,
        access_rights,
        account_hash,
        Rc::new(RefCell::new(address_generator)),
        Rc::clone(&tracking_copy),
        EngineConfig::default(),
        BlockInfo::new(
            Digest::default(),
            BlockTime::new(0),
            BlockHash::default(),
            0,
            ProtocolVersion::V2_0_0,
        ),
        TransactionHash::V1(TransactionV1Hash::from_raw(TXN_HASH_RAW)),
        PHASE,
        RuntimeArgs::new(),
        Gas::new(U512::from(GAS_LIMIT)),
        Gas::default(),
        Vec::default(),
        U512::zero(),
        EntryPointType::Caller,
        AllowInstallUpgrade::Forbidden,
    );

    assert!(runtime_context
        .metered_add_gs(contract_key, named_uref_tuple)
        .is_err())
}

#[test]
fn contract_key_addable_invalid() {
    let account_hash = AccountHash::new([0u8; 32]);
    let entity_hash = AddressableEntityHash::new([1u8; 32]);
    let (_, entity_key, entity) = new_addressable_entity(account_hash, entity_hash);
    let authorization_keys = BTreeSet::from_iter(vec![account_hash]);
    let mut address_generator = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let mut rng = rand::thread_rng();
    let contract_key = random_contract_key(&mut rng);

    let other_contract_key = random_contract_key(&mut rng);
    let contract = StoredValue::AddressableEntity(AddressableEntity::default());
    let mut access_rights = contract
        .as_addressable_entity()
        .unwrap()
        .extract_access_rights(AddressableEntityHash::default(), &NamedKeys::new());
    let (tracking_copy, _tempdir) = new_tracking_copy(account_hash, entity_key, entity.clone());
    let tracking_copy = Rc::new(RefCell::new(tracking_copy));

    tracking_copy.borrow_mut().write(contract_key, contract);

    let uref_as_key = create_uref_as_key(&mut address_generator, AccessRights::WRITE);
    let uref_name = "NewURef".to_owned();
    let named_uref_tuple = StoredValue::CLValue(CLValue::from_t((uref_name, uref_as_key)).unwrap());

    let mut named_keys = NamedKeys::new();
    named_keys.insert(String::new(), uref_as_key);

    access_rights.extend(&[uref_as_key.into_uref().expect("should be a URef")]);

    let addr = match entity_key {
        Key::AddressableEntity(entity_addr) => entity_addr,
        Key::Account(account_hash) => EntityAddr::Account(account_hash.value()),
        Key::Hash(hash) => EntityAddr::SmartContract(hash),
        _ => panic!("unexpected key"),
    };

    let runtime_footprint = RuntimeFootprint::new_entity_footprint(
        addr,
        AddressableEntity::default(),
        named_keys.clone(),
        EntryPoints::new(),
    );

    let mut runtime_context = RuntimeContext::new(
        &mut named_keys,
        Rc::new(RefCell::new(runtime_footprint)),
        other_contract_key,
        authorization_keys,
        access_rights,
        account_hash,
        Rc::new(RefCell::new(address_generator)),
        Rc::clone(&tracking_copy),
        EngineConfig::default(),
        BlockInfo::new(
            Digest::default(),
            BlockTime::new(0),
            BlockHash::default(),
            0,
            ProtocolVersion::V2_0_0,
        ),
        TransactionHash::V1(TransactionV1Hash::from_raw(TXN_HASH_RAW)),
        PHASE,
        RuntimeArgs::new(),
        Gas::new(U512::from(GAS_LIMIT)),
        Gas::default(),
        Vec::default(),
        U512::zero(),
        EntryPointType::Caller,
        AllowInstallUpgrade::Forbidden,
    );

    let result = runtime_context.metered_add_gs(contract_key, named_uref_tuple);

    assert_invalid_access(result, AccessRights::ADD);
}

#[test]
fn uref_key_readable_valid() {
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref_key = create_uref_as_key(&mut rng, AccessRights::READ);

    let mut named_keys = NamedKeys::new();
    named_keys.insert(String::new(), uref_key);

    let result = build_runtime_context_and_execute(named_keys, |mut rc| rc.read_gs(&uref_key));
    assert!(result.is_ok());
}

#[test]
fn uref_key_readable_invalid() {
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref_key = create_uref_as_key(&mut rng, AccessRights::WRITE);

    let mut named_keys = NamedKeys::new();
    named_keys.insert(String::new(), uref_key);

    let result = build_runtime_context_and_execute(named_keys, |mut rc| rc.read_gs(&uref_key));
    assert_invalid_access(result, AccessRights::READ);
}

#[test]
fn uref_key_writeable_valid() {
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref_key = create_uref_as_key(&mut rng, AccessRights::WRITE);

    let mut named_keys = NamedKeys::new();
    named_keys.insert(String::new(), uref_key);

    let result = build_runtime_context_and_execute(named_keys, |mut rc| {
        rc.metered_write_gs(
            uref_key,
            StoredValue::CLValue(CLValue::from_t(1_i32).unwrap()),
        )
    });
    assert!(result.is_ok());
}

#[test]
fn uref_key_writeable_invalid() {
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref_key = create_uref_as_key(&mut rng, AccessRights::READ);

    let mut named_keys = NamedKeys::new();
    named_keys.insert(String::new(), uref_key);

    let result = build_runtime_context_and_execute(named_keys, |mut rc| {
        rc.metered_write_gs(
            uref_key,
            StoredValue::CLValue(CLValue::from_t(1_i32).unwrap()),
        )
    });
    assert_invalid_access(result, AccessRights::WRITE);
}

#[test]
fn uref_key_addable_valid() {
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref_key = create_uref_as_key(&mut rng, AccessRights::ADD_WRITE);

    let mut named_keys = NamedKeys::new();
    named_keys.insert(String::new(), uref_key);

    let result = build_runtime_context_and_execute(named_keys, |mut rc| {
        rc.metered_write_gs(uref_key, CLValue::from_t(10_i32).unwrap())
            .expect("Writing to the GlobalState should work.");
        rc.metered_add_gs(uref_key, CLValue::from_t(1_i32).unwrap())
    });
    assert!(result.is_ok());
}

#[test]
fn uref_key_addable_invalid() {
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref_key = create_uref_as_key(&mut rng, AccessRights::WRITE);

    let mut named_keys = NamedKeys::new();
    named_keys.insert(String::new(), uref_key);

    let result = build_runtime_context_and_execute(named_keys, |mut rc| {
        rc.metered_add_gs(
            uref_key,
            StoredValue::CLValue(CLValue::from_t(1_i32).unwrap()),
        )
    });
    assert_invalid_access(result, AccessRights::ADD);
}

#[test]
fn hash_key_is_not_writeable() {
    // values under hash's are immutable
    let functor = |runtime_context: RuntimeContext<LmdbGlobalStateView>| {
        let mut rng = rand::thread_rng();
        let key = random_hash(&mut rng);
        runtime_context.validate_writeable(&key)
    };
    let result = build_runtime_context_and_execute(NamedKeys::new(), functor);
    assert!(result.is_err())
}

#[test]
fn hash_key_is_not_addable() {
    // values under hashes are immutable
    let functor = |runtime_context: RuntimeContext<LmdbGlobalStateView>| {
        let mut rng = rand::thread_rng();
        let key = random_hash(&mut rng);
        runtime_context.validate_addable(&key)
    };
    let result = build_runtime_context_and_execute(NamedKeys::new(), functor);
    assert!(result.is_err())
}

#[test]
fn manage_associated_keys() {
    // Testing a valid case only - successfully added a key, and successfully removed,
    // making sure `account_dirty` mutated
    let named_keys = NamedKeys::new();
    let functor = |mut runtime_context: RuntimeContext<LmdbGlobalStateView>| {
        let account_hash = AccountHash::new([42; 32]);
        let weight = Weight::new(155);

        // Add a key (this doesn't check for all invariants as `add_key`
        // is already tested in different place)
        runtime_context
            .add_associated_key(account_hash, weight)
            .expect("Unable to add key");

        let transform_kind = last_transform_kind_on_addressable_entity(&runtime_context);
        let entity = match transform_kind {
            TransformKindV2::Write(StoredValue::AddressableEntity(entity)) => entity,
            _ => panic!("Invalid transform operation found"),
        };
        entity
            .associated_keys()
            .get(&account_hash)
            .expect("Account hash wasn't added to associated keys");

        let new_weight = Weight::new(100);
        runtime_context
            .update_associated_key(account_hash, new_weight)
            .expect("Unable to update key");

        let transform_kind = last_transform_kind_on_addressable_entity(&runtime_context);
        let entity = match transform_kind {
            TransformKindV2::Write(StoredValue::AddressableEntity(entity)) => entity,
            _ => panic!("Invalid transform operation found"),
        };
        let value = entity
            .associated_keys()
            .get(&account_hash)
            .expect("Account hash wasn't added to associated keys");

        assert_eq!(value, &new_weight, "value was not updated");

        // Remove a key that was already added
        runtime_context
            .remove_associated_key(account_hash)
            .expect("Unable to remove key");

        // Verify
        let transform_kind = last_transform_kind_on_addressable_entity(&runtime_context);
        let entity = match transform_kind {
            TransformKindV2::Write(StoredValue::AddressableEntity(entity)) => entity,
            _ => panic!("Invalid transform operation found"),
        };

        let actual = entity.associated_keys().get(&account_hash);

        assert!(actual.is_none());

        // Remove a key that was already removed
        runtime_context
            .remove_associated_key(account_hash)
            .expect_err("A non existing key was unexpectedly removed again");

        Ok(())
    };
    let _ = build_runtime_context_and_execute(named_keys, functor);
}

#[test]
fn action_thresholds_management() {
    // Testing a valid case only - successfully added a key, and successfully removed,
    // making sure `account_dirty` mutated
    let named_keys = NamedKeys::new();
    let functor = |mut runtime_context: RuntimeContext<LmdbGlobalStateView>| {
        let entity_hash_by_account_hash =
            CLValue::from_t(Key::Hash([2; 32])).expect("must convert to cl_value");

        runtime_context
            .metered_write_gs_unsafe(
                Key::Account(AccountHash::new([42; 32])),
                entity_hash_by_account_hash,
            )
            .expect("must write key to gs");

        runtime_context
            .add_associated_key(AccountHash::new([42; 32]), Weight::new(254))
            .expect("Unable to add associated key with maximum weight");
        runtime_context
            .set_action_threshold(ActionType::KeyManagement, Weight::new(253))
            .expect("Unable to set action threshold KeyManagement");
        runtime_context
            .set_action_threshold(ActionType::Deployment, Weight::new(252))
            .expect("Unable to set action threshold Deployment");

        let transform_kind = last_transform_kind_on_addressable_entity(&runtime_context);
        let mutated_entity = match transform_kind {
            TransformKindV2::Write(StoredValue::AddressableEntity(entity)) => entity,
            _ => panic!("Invalid transform operation found"),
        };

        assert_eq!(
            mutated_entity.action_thresholds().deployment(),
            &Weight::new(252)
        );
        assert_eq!(
            mutated_entity.action_thresholds().key_management(),
            &Weight::new(253)
        );

        runtime_context
            .set_action_threshold(ActionType::Deployment, Weight::new(255))
            .expect_err("Shouldn't be able to set deployment threshold higher than key management");

        Ok(())
    };
    let _ = build_runtime_context_and_execute(named_keys, functor);
}

#[test]
fn should_verify_ownership_before_adding_key() {
    // Testing a valid case only - successfully added a key, and successfully removed,
    // making sure `account_dirty` mutated
    let named_keys = NamedKeys::new();
    let functor = |mut runtime_context: RuntimeContext<LmdbGlobalStateView>| {
        // Overwrites a `context_key` to a different one before doing any operation as
        // account `[0; 32]`
        let entity_hash_by_account_hash =
            CLValue::from_t(Key::Hash([2; 32])).expect("must convert to cl_value");

        runtime_context
            .metered_write_gs_unsafe(
                Key::Account(AccountHash::new([84; 32])),
                entity_hash_by_account_hash,
            )
            .expect("must write key to gs");

        runtime_context
            .metered_write_gs_unsafe(Key::Hash([1; 32]), AddressableEntity::default())
            .expect("must write key to gs");

        runtime_context.context_key = Key::Hash([1; 32]);

        let err = runtime_context
            .add_associated_key(AccountHash::new([84; 32]), Weight::new(123))
            .expect_err("This operation should return error");

        match err {
            ExecError::UnexpectedKeyVariant(_) => {
                // This is the v2.0.0 error as this test is currently using Key::Hash
                // instead of Key::AddressableEntity
            }
            ExecError::AddKeyFailure(AddKeyFailure::PermissionDenied) => {}
            e => panic!("Invalid error variant: {:?}", e),
        }

        Ok(())
    };
    let _ = build_runtime_context_and_execute(named_keys, functor);
}

#[test]
fn should_verify_ownership_before_removing_a_key() {
    // Testing a valid case only - successfully added a key, and successfully removed,
    // making sure `account_dirty` mutated
    let named_keys = NamedKeys::new();
    let functor = |mut runtime_context: RuntimeContext<LmdbGlobalStateView>| {
        // Overwrites a `context_key` to a different one before doing any operation as
        // account `[0; 32]`
        runtime_context.context_key = Key::Hash([1; 32]);

        let err = runtime_context
            .remove_associated_key(AccountHash::new([84; 32]))
            .expect_err("This operation should return error");

        match err {
            ExecError::UnexpectedKeyVariant(_) => {
                // this is the v2.0 error because this test is currently using
                // Key::Hash instead of Key::AddressableEntity
            }
            ExecError::RemoveKeyFailure(RemoveKeyFailure::PermissionDenied) => {}
            ref e => panic!("Invalid error variant: {:?}", e),
        }

        Ok(())
    };
    let _ = build_runtime_context_and_execute(named_keys, functor);
}

#[test]
fn should_verify_ownership_before_setting_action_threshold() {
    // Testing a valid case only - successfully added a key, and successfully removed,
    // making sure `account_dirty` mutated
    let named_keys = NamedKeys::new();
    let functor = |mut runtime_context: RuntimeContext<LmdbGlobalStateView>| {
        // Overwrites a `context_key` to a different one before doing any operation as
        // account `[0; 32]`
        runtime_context.context_key = Key::Hash([1; 32]);

        let err = runtime_context
            .set_action_threshold(ActionType::Deployment, Weight::new(123))
            .expect_err("This operation should return error");

        match err {
            ExecError::UnexpectedKeyVariant(_) => {
                // this is what is returned under protocol version 2.0 because Key::Hash(_) is
                // deprecated.
            }
            ExecError::SetThresholdFailure(SetThresholdFailure::PermissionDeniedError) => {}
            ref e => panic!("Invalid error variant: {:?}", e),
        }

        Ok(())
    };
    let _ = build_runtime_context_and_execute(named_keys, functor);
}

#[test]
fn remove_uref_works() {
    // Test that `remove_uref` removes Key from both ephemeral representation
    // which is one of the current RuntimeContext, and also puts that change
    // into the `TrackingCopy` so that it's later committed to the GlobalState.
    let deploy_hash = [1u8; 32];
    let mut address_generator = AddressGenerator::new(&deploy_hash, Phase::Session);
    let uref_name = "Foo".to_owned();
    let uref_key = create_uref_as_key(&mut address_generator, AccessRights::READ);
    let account_hash = AccountHash::new([0u8; 32]);
    let entity_hash = AddressableEntityHash::new([0u8; 32]);
    let mut named_keys = NamedKeys::new();
    named_keys.insert(uref_name.clone(), uref_key);
    let (_, entity_key, addressable_entity) = new_addressable_entity(account_hash, entity_hash);

    let access_rights = addressable_entity.extract_access_rights(entity_hash, &named_keys);

    let (mut runtime_context, _tempdir) = new_runtime_context(
        &addressable_entity,
        account_hash,
        entity_key,
        &mut named_keys,
        access_rights,
        address_generator,
    );

    assert!(runtime_context.named_keys_contains_key(&uref_name));
    assert!(runtime_context.remove_key(&uref_name).is_ok());
    // It is valid to retain the access right for the given runtime context
    // even if you remove the URef from the named keys.
    assert!(runtime_context.validate_key(&uref_key).is_ok());
    assert!(!runtime_context.named_keys_contains_key(&uref_name));

    let entity_named_keys = runtime_context
        .get_named_keys(entity_key)
        .expect("must get named keys for entity");
    assert!(!entity_named_keys.contains(&uref_name));
    // The next time the account is used, the access right is gone for the removed
    // named key.

    let next_session_access_rights = addressable_entity.extract_access_rights(
        AddressableEntityHash::new(account_hash.value()),
        &entity_named_keys,
    );
    let address_generator = AddressGenerator::new(&deploy_hash, Phase::Session);

    let (runtime_context, _tempdir) = new_runtime_context(
        &addressable_entity,
        account_hash,
        entity_key,
        &mut named_keys,
        next_session_access_rights,
        address_generator,
    );
    assert!(runtime_context.validate_key(&uref_key).is_err());
}

#[test]
fn an_accounts_access_rights_should_include_main_purse() {
    let test_main_purse = URef::new([42u8; 32], AccessRights::READ_ADD_WRITE);
    // All other access rights except for main purse are extracted from named keys.
    let account_hash = AccountHash::new([0u8; 32]);
    let entity_hash = AddressableEntityHash::new([1u8; 32]);
    let named_keys = NamedKeys::new();
    let (_context_key, _, entity) = new_addressable_entity_with_purse(
        account_hash,
        entity_hash,
        EntityKind::Account(account_hash),
        test_main_purse.addr(),
    );
    assert!(
        named_keys.is_empty(),
        "Named keys does not contain main purse"
    );
    let access_rights = entity.extract_access_rights(entity_hash, &named_keys);
    assert!(
        access_rights.has_access_rights_to_uref(&test_main_purse),
        "Main purse should be included in access rights"
    );
}

#[test]
fn validate_valid_purse_of_an_account() {
    // Tests that URef which matches a purse of a given context gets validated
    let test_main_purse = URef::new([42u8; 32], AccessRights::READ_ADD_WRITE);

    let mut named_keys = NamedKeys::new();
    named_keys.insert("entry".to_string(), Key::from(test_main_purse));

    let deploy_hash = [1u8; 32];
    let account_hash = AccountHash::new([0u8; 32]);
    let entity_hash = AddressableEntityHash::new([1u8; 32]);
    let (context_key, _, entity) = new_addressable_entity_with_purse(
        account_hash,
        entity_hash,
        EntityKind::Account(account_hash),
        test_main_purse.addr(),
    );

    let mut access_rights = entity.extract_access_rights(entity_hash, &named_keys);
    access_rights.extend(&[test_main_purse]);

    let address_generator = AddressGenerator::new(&deploy_hash, Phase::Session);
    let (runtime_context, _tempdir) = new_runtime_context(
        &entity,
        account_hash,
        context_key,
        &mut named_keys,
        access_rights,
        address_generator,
    );

    // URef that has the same id as purse of an account gets validated
    // successfully.
    assert!(runtime_context.validate_uref(&test_main_purse).is_ok());

    let purse = test_main_purse.with_access_rights(AccessRights::READ);
    assert!(runtime_context.validate_uref(&purse).is_ok());
    let purse = test_main_purse.with_access_rights(AccessRights::ADD);
    assert!(runtime_context.validate_uref(&purse).is_ok());
    let purse = test_main_purse.with_access_rights(AccessRights::WRITE);
    assert!(runtime_context.validate_uref(&purse).is_ok());

    // Purse ID that doesn't match account's purse should fail as it's also not
    // in known urefs.
    let purse = URef::new([53; 32], AccessRights::READ_ADD_WRITE);
    assert!(runtime_context.validate_uref(&purse).is_err());
}

#[test]
fn should_meter_for_gas_storage_write() {
    // Test fixture
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref_as_key = create_uref_as_key(&mut rng, AccessRights::READ_WRITE);

    let mut named_keys = NamedKeys::new();
    named_keys.insert("entry".to_string(), uref_as_key);

    let value = StoredValue::CLValue(CLValue::from_t(43_i32).unwrap());
    let expected_write_cost = test_engine_config()
        .storage_costs()
        .calculate_gas_cost(value.serialized_length());

    let (gas_usage_before, gas_usage_after) =
        build_runtime_context_and_execute(named_keys, |mut rc| {
            let gas_before = rc.gas_counter();
            rc.metered_write_gs(uref_as_key, value)
                .expect("should write");
            let gas_after = rc.gas_counter();
            Ok((gas_before, gas_after))
        })
        .expect("should run test");

    assert!(
        gas_usage_after > gas_usage_before,
        "{} <= {}",
        gas_usage_after,
        gas_usage_before
    );

    assert_eq!(
        Some(gas_usage_after),
        gas_usage_before.checked_add(expected_write_cost)
    );
}

#[test]
fn should_meter_for_gas_storage_add() {
    // Test fixture
    let mut rng = AddressGenerator::new(&TXN_HASH_RAW, PHASE);
    let uref_as_key = create_uref_as_key(&mut rng, AccessRights::ADD_WRITE);

    let mut named_keys = NamedKeys::new();
    named_keys.insert("entry".to_string(), uref_as_key);

    let value = StoredValue::CLValue(CLValue::from_t(43_i32).unwrap());
    let expected_add_cost = test_engine_config()
        .storage_costs()
        .calculate_gas_cost(value.serialized_length());

    let (gas_usage_before, gas_usage_after) =
        build_runtime_context_and_execute(named_keys, |mut rc| {
            rc.metered_write_gs(uref_as_key, value.clone())
                .expect("should write");
            let gas_before = rc.gas_counter();
            rc.metered_add_gs(uref_as_key, value).expect("should add");
            let gas_after = rc.gas_counter();
            Ok((gas_before, gas_after))
        })
        .expect("should run test");

    assert!(
        gas_usage_after > gas_usage_before,
        "{} <= {}",
        gas_usage_after,
        gas_usage_before
    );

    assert_eq!(
        Some(gas_usage_after),
        gas_usage_before.checked_add(expected_add_cost)
    );
}

#[test]
fn associated_keys_add_full() {
    let final_add_result = build_runtime_context_and_execute(NamedKeys::new(), |mut rc| {
        let associated_keys_before = rc.runtime_footprint().borrow().associated_keys().len();

        for count in 0..(rc.engine_config.max_associated_keys() as usize - associated_keys_before) {
            let account_hash = {
                let mut addr = [0; ACCOUNT_HASH_LENGTH];
                U256::from(count).to_big_endian(&mut addr);
                AccountHash::new(addr)
            };
            let weight = Weight::new(count.try_into().unwrap());
            rc.add_associated_key(account_hash, weight)
                .unwrap_or_else(|e| panic!("should add key {}: {:?}", count, e));
        }

        rc.add_associated_key(AccountHash::new([42; 32]), Weight::new(42))
    });

    assert!(matches!(
        final_add_result.expect_err("should error out"),
        ExecError::AddKeyFailure(AddKeyFailure::MaxKeysLimit)
    ));
}