-
Notifications
You must be signed in to change notification settings - Fork 116
/
DiemAccount.move
3368 lines (3032 loc) · 143 KB
/
DiemAccount.move
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
address 0x1 {
/// The `DiemAccount` module manages accounts. It defines the `DiemAccount` resource and
/// numerous auxiliary data structures. It also defines the prolog and epilog that run
/// before and after every transaction.
/////// 0L /////////
// File Prefix for errors: 1201 used for OL errors
module DiemAccount {
friend 0x1::MigrateJail;
friend 0x1::MakeWhole;
use 0x1::AccountFreezing;
use 0x1::CoreAddresses;
use 0x1::ChainId;
use 0x1::AccountLimits::{Self, AccountLimitMutationCapability};
use 0x1::XUS::XUS;
use 0x1::DualAttestation;
use 0x1::Errors;
use 0x1::Event::{Self, EventHandle};
use 0x1::Hash;
use 0x1::BCS;
use 0x1::DiemConfig;
use 0x1::DiemTimestamp;
use 0x1::DiemTransactionPublishingOption;
use 0x1::Signer;
use 0x1::SlidingNonce;
use 0x1::TransactionFee;
use 0x1::ValidatorConfig;
use 0x1::ValidatorOperatorConfig;
use 0x1::VASP;
use 0x1::Vector;
use 0x1::DesignatedDealer;
use 0x1::Diem::{Self, Diem};
use 0x1::Option::{Self, Option};
use 0x1::Roles;
use 0x1::DiemId;
//////// 0L ////////
use 0x1::VDF;
use 0x1::DiemSystem;
use 0x1::TowerState;
use 0x1::Testnet::is_testnet;
use 0x1::FIFO;
use 0x1::FixedPoint32;
use 0x1::GAS::GAS;
use 0x1::ValidatorUniverse;
use 0x1::Wallet;
use 0x1::Receipts;
use 0x1::Ancestry;
use 0x1::Vouch;
use 0x1::Jail;
use 0x1::Debug::print;
/// An `address` is a Diem Account iff it has a published DiemAccount resource.
struct DiemAccount has key {
/// The current authentication key.
/// This can be different from the key used to create the account
authentication_key: vector<u8>,
/// A `withdraw_capability` allows whoever holds this capability
/// to withdraw from the account. At the time of account creation
/// this capability is stored in this option. It can later be removed
/// by `extract_withdraw_capability` and also restored via `restore_withdraw_capability`.
withdraw_capability: Option<WithdrawCapability>,
/// A `key_rotation_capability` allows whoever holds this capability
/// the ability to rotate the authentication key for the account. At
/// the time of account creation this capability is stored in this
/// option. It can later be "extracted" from this field via
/// `extract_key_rotation_capability`, and can also be restored via
/// `restore_key_rotation_capability`.
key_rotation_capability: Option<KeyRotationCapability>,
/// Event handle to which ReceivePaymentEvents are emitted when
/// payments are received.
received_events: EventHandle<ReceivedPaymentEvent>,
/// Event handle to which SentPaymentEvents are emitted when
/// payments are sent.
sent_events: EventHandle<SentPaymentEvent>,
/// The current sequence number of the account.
/// Incremented by one each time a transaction is submitted by
/// this account.
sequence_number: u64,
}
/// A resource that holds the total value of currency of type `Token`
/// currently held by the account.
struct Balance<Token> has key {
/// Stores the value of the balance in its balance field. A coin has
/// a `value` field. The amount of money in the balance is changed
/// by modifying this field.
coin: Diem<Token>,
}
/// The holder of WithdrawCapability for account_address can withdraw Diem from
/// account_address/DiemAccount/balance.
/// There is at most one WithdrawCapability in existence for a given address.
struct WithdrawCapability has store {
/// Address that WithdrawCapability was associated with when it was created.
/// This field does not change.
account_address: address,
}
/// The holder of KeyRotationCapability for account_address can rotate the authentication key for
/// account_address (i.e., write to account_address/DiemAccount/authentication_key).
/// There is at most one KeyRotationCapability in existence for a given address.
struct KeyRotationCapability has store {
/// Address that KeyRotationCapability was associated with when it was created.
/// This field does not change.
account_address: address,
}
/// A wrapper around an `AccountLimitMutationCapability` which is used to check for account limits
/// and to record freeze/unfreeze events.
struct AccountOperationsCapability has key {
limits_cap: AccountLimitMutationCapability,
creation_events: Event::EventHandle<CreateAccountEvent>,
}
/// A resource that holds the event handle for all the past WriteSet transactions that have been committed on chain.
struct DiemWriteSetManager has key {
upgrade_events: Event::EventHandle<Self::AdminTransactionEvent>,
}
/// Message for sent events
struct SentPaymentEvent has drop, store {
/// The amount of Diem<Token> sent
amount: u64,
/// The code symbol for the currency that was sent
currency_code: vector<u8>,
/// The address that was paid
payee: address,
/// Metadata associated with the payment
metadata: vector<u8>,
}
/// Message for received events
struct ReceivedPaymentEvent has drop, store {
/// The amount of Diem<Token> received
amount: u64,
/// The code symbol for the currency that was received
currency_code: vector<u8>,
/// The address that sent the coin
payer: address,
/// Metadata associated with the payment
metadata: vector<u8>,
}
/// Message for committed WriteSet transaction.
struct AdminTransactionEvent has drop, store {
// The block time when this WriteSet is committed.
committed_timestamp_secs: u64,
}
/// Message for creation of a new account
struct CreateAccountEvent has drop, store {
/// Address of the created account
created: address,
/// Role of the created account
role_id: u64
}
const MAX_U64: u128 = 18446744073709551615;
/// The `DiemAccount` resource is not in the required state
const EACCOUNT: u64 = 12010;
/// Tried to deposit a coin whose value was zero
const ECOIN_DEPOSIT_IS_ZERO: u64 = 12012;
/// Tried to deposit funds that would have surpassed the account's limits
const EDEPOSIT_EXCEEDS_LIMITS: u64 = 12013;
/// Tried to create a balance for an account whose role does not allow holding balances
const EROLE_CANT_STORE_BALANCE: u64 = 12014;
/// The account does not hold a large enough balance in the specified currency
const EINSUFFICIENT_BALANCE: u64 = 12015;
/// The withdrawal of funds would have exceeded the the account's limits
const EWITHDRAWAL_EXCEEDS_LIMITS: u64 = 12016;
/// The `WithdrawCapability` for this account has already been extracted
const EWITHDRAW_CAPABILITY_ALREADY_EXTRACTED: u64 = 12017;
/// The provided authentication had an invalid length
const EMALFORMED_AUTHENTICATION_KEY: u64 = 12018;
/// The `KeyRotationCapability` for this account has already been extracted
const EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED: u64 = 12019;
/// An account cannot be created at the reserved VM address of 0x0
const ECANNOT_CREATE_AT_VM_RESERVED: u64 = 120110;
/// The `WithdrawCapability` for this account is not extracted
const EWITHDRAW_CAPABILITY_NOT_EXTRACTED: u64 = 120111;
/// Tried to add a balance in a currency that this account already has
const EADD_EXISTING_CURRENCY: u64 = 120115;
/// Attempted to send funds to an account that does not exist
const EPAYEE_DOES_NOT_EXIST: u64 = 120117;
/// Attempted to send funds in a currency that the receiving account does not hold.
/// e.g., `Diem<XDX>` to an account that exists, but does not have a `Balance<XDX>` resource
const EPAYEE_CANT_ACCEPT_CURRENCY_TYPE: u64 = 120118;
/// Tried to withdraw funds in a currency that the account does hold
const EPAYER_DOESNT_HOLD_CURRENCY: u64 = 120119;
/// An invalid amount of gas units was provided for execution of the transaction
const EGAS: u64 = 120120;
/// The `AccountOperationsCapability` was not in the required state
const EACCOUNT_OPERATIONS_CAPABILITY: u64 = 120122;
/// The `DiemWriteSetManager` was not in the required state
const EWRITESET_MANAGER: u64 = 120123;
/// An account cannot be created at the reserved core code address of 0x1
const ECANNOT_CREATE_AT_CORE_CODE: u64 = 120124;
//////// 0L ////////
const EBELOW_MINIMUM_VALUE_BOOTSTRAP_COIN: u64 = 120125;
const EWITHDRAWAL_NOT_FOR_COMMUNITY_WALLET: u64 = 120126;
const ESLOW_WALLET_TRANSFERS_DISABLED_SYSTEMWIDE: u64 = 120127;
const EWITHDRAWAL_SLOW_WAL_EXCEEDS_UNLOCKED_LIMIT: u64 = 120128;
/////// 0L end /////////
/// Prologue errors. These are separated out from the other errors in this
/// module since they are mapped separately to major VM statuses, and are
/// important to the semantics of the system.
const PROLOGUE_EACCOUNT_FROZEN: u64 = 1000;
const PROLOGUE_EINVALID_ACCOUNT_AUTH_KEY: u64 = 1001;
const PROLOGUE_ESEQUENCE_NUMBER_TOO_OLD: u64 = 1002;
const PROLOGUE_ESEQUENCE_NUMBER_TOO_NEW: u64 = 1003;
const PROLOGUE_EACCOUNT_DNE: u64 = 1004;
const PROLOGUE_ECANT_PAY_GAS_DEPOSIT: u64 = 1005;
const PROLOGUE_ETRANSACTION_EXPIRED: u64 = 1006;
const PROLOGUE_EBAD_CHAIN_ID: u64 = 1007;
const PROLOGUE_ESCRIPT_NOT_ALLOWED: u64 = 1008;
const PROLOGUE_EMODULE_NOT_ALLOWED: u64 = 1009;
const PROLOGUE_EINVALID_WRITESET_SENDER: u64 = 1010;
const PROLOGUE_ESEQUENCE_NUMBER_TOO_BIG: u64 = 1011;
const PROLOGUE_EBAD_TRANSACTION_FEE_CURRENCY: u64 = 1012;
const PROLOGUE_ESECONDARY_KEYS_ADDRESSES_COUNT_MISMATCH: u64 = 1013;
//////// 0L //////////
const BOOTSTRAP_COIN_VALUE: u64 = 1000000;
struct Escrow <Token> has store {
to_account: address,
escrow: Diem::Diem<Token>,
}
//////// 0L //////////
struct AutopayEscrow <Token> has key, store {
list: FIFO::FIFO<Escrow<Token>>,
}
//////// 0L //////////
struct EscrowList<Token> has key {
accounts: vector<EscrowSettings>
}
//////// 0L //////////
struct EscrowSettings has store {
account: address,
//what percent of your available account limit should be dedicated to autopay?
share: u64,
}
//////// 0L ////////
// A helper function for the VM to MOCK THE SIGNATURE OF ANY ADDRESS.
// This is necessary for migrating user state, when a new struct needs to be created.
// This is restricted by `friend` visibility, which is defined above as the 0x1::MigrateAutoPayBal module for a one-time use.
// language/changes/1-friend-visibility.md
public(friend) fun scary_create_signer_for_migrations(vm: &signer, addr: address): signer {
CoreAddresses::assert_diem_root(vm);
create_signer(addr)
}
//////// 0L ////////
fun new_escrow<Token: store>(
account: &signer,
payer: address,
payee: address,
amount: u64,
) acquires Balance, AutopayEscrow {
Roles::assert_diem_root(account);
// Formal verification spec: should not get anyone else's balance struct
let balance_struct = borrow_global_mut<Balance<Token>>(payer);
let coin = Diem::withdraw<Token>(&mut balance_struct.coin, amount);
let new_escrow = Escrow {
to_account: payee,
escrow: coin,
};
let state = borrow_global_mut<AutopayEscrow<Token>>(payer);
FIFO::push<Escrow<Token>>(&mut state.list, new_escrow);
}
/////// 0L /////////
public fun process_escrow<Token: store>(
account: &signer
) acquires EscrowList, AutopayEscrow, Balance, AccountOperationsCapability {
Roles::assert_diem_root(account);
let account_list = &borrow_global<EscrowList<Token>>(
CoreAddresses::DIEM_ROOT_ADDRESS()
).accounts;
let account_len = Vector::length<EscrowSettings>(account_list);
let account_idx = 0;
while (account_idx < account_len) {
let EscrowSettings {account: account_addr, share: percentage}
= Vector::borrow<EscrowSettings>(account_list, account_idx);
//get transfer limit room
let (limit_room, withdrawal_allowed)
= AccountLimits::max_withdrawal<Token>(*account_addr);
if (!withdrawal_allowed) {
account_idx = account_idx + 1;
continue
};
limit_room = FixedPoint32::multiply_u64(
limit_room ,
FixedPoint32::create_from_rational(*percentage, 100)
);
let amount_sent: u64 = 0;
let payment_list = &mut borrow_global_mut<AutopayEscrow<Token>>(*account_addr).list;
let num_payments = FIFO::len<Escrow<Token>>(payment_list);
// Pay out escrow until limit is reached
while (limit_room > 0 && num_payments > 0) {
let Escrow<Token> {to_account, escrow} = FIFO::pop<Escrow<Token>>(payment_list);
let recipient_coins = borrow_global_mut<Balance<Token>>(to_account);
let payment_size = Diem::value<Token>(&escrow);
if (payment_size > limit_room) {
let (coin1, coin2) = Diem::split<Token>(escrow, limit_room);
Diem::deposit<Token>(&mut recipient_coins.coin, coin2);
let new_escrow = Escrow {
to_account: to_account,
escrow: coin1,
};
FIFO::push_LIFO<Escrow<Token>>(payment_list, new_escrow);
amount_sent = amount_sent + limit_room;
limit_room = 0;
} else {
// This entire escrow is being paid out
Diem::deposit<Token>(&mut recipient_coins.coin, escrow);
limit_room = limit_room - payment_size;
amount_sent = amount_sent + payment_size;
num_payments = num_payments - 1;
}
};
//update account limits
if (amount_sent > 0) {
_ = AccountLimits::update_withdrawal_limits<Token>(
amount_sent,
*account_addr,
&borrow_global<AccountOperationsCapability>(
CoreAddresses::DIEM_ROOT_ADDRESS()
).limits_cap
);
};
account_idx = account_idx + 1;
}
}
/////// 0L /////////
public fun initialize_escrow<Token: store>(
sender: &signer
) acquires EscrowList {
let account = Signer::address_of(sender);
if (!exists<AutopayEscrow<Token>>(account)) {
move_to<AutopayEscrow<Token>>(
sender,
AutopayEscrow { list: FIFO::empty<Escrow<Token>>() }
);
let escrow_list = &mut borrow_global_mut<EscrowList<Token>>(
CoreAddresses::DIEM_ROOT_ADDRESS()
).accounts;
let idx = 0;
let len = Vector::length<EscrowSettings>(escrow_list);
let found = false;
while (idx < len) {
let account_addr = Vector::borrow<EscrowSettings>(escrow_list, idx).account;
if (account_addr == account) {
found = true;
break
};
idx = idx + 1;
};
if (!found){
// Share initialized to 100
let default_percentage: u64 = 100;
let settings = EscrowSettings { account: account, share: default_percentage };
Vector::push_back<EscrowSettings>(escrow_list, settings);
};
};
}
/////// 0L /////////
public fun initialize_escrow_root<Token: store>(sender: &signer) {
move_to<EscrowList<Token>>(
sender,
EscrowList<Token> { accounts: Vector::empty<EscrowSettings>() }
);
}
// Unused
// /////// 0L /////////
// public fun update_escrow_percentage<Token: store>(
// sender: &signer,
// new_percentage: u64,
// ) acquires EscrowList {
// assert(new_percentage >= 50, 1);
// assert(new_percentage <= 100, 1);
// let escrow_list = &mut borrow_global_mut<EscrowList<Token>>(
// CoreAddresses::DIEM_ROOT_ADDRESS()
// ).accounts;
// let account = Signer::address_of(sender);
// let idx = 0;
// let len = Vector::length<EscrowSettings>(escrow_list);
// while (idx < len) {
// let settings = Vector::borrow_mut<EscrowSettings>(escrow_list, idx);
// if (settings.account == account) {
// settings.share = new_percentage;
// return
// };
// idx = idx + 1;
// };
// // Should never reach this point, if you do, autopay does not exist for the account.
// assert(false, 1);
// }
/// Initialize this module. This is only callable from genesis.
public fun initialize(
dr_account: &signer,
dummy_auth_key_prefix: vector<u8>,
) acquires AccountOperationsCapability {
DiemTimestamp::assert_genesis();
// Operational constraint, not a privilege constraint.
CoreAddresses::assert_diem_root(dr_account);
create_diem_root_account(
copy dummy_auth_key_prefix,
);
/////// 0L /////////
// create_treasury_compliance_account(
// dr_account,
// copy dummy_auth_key_prefix,
// );
}
spec initialize {
pragma opaque;
include CoreAddresses::AbortsIfNotDiemRoot{account: dr_account};
include CreateDiemRootAccountAbortsIf{auth_key_prefix: dummy_auth_key_prefix};
include CreateTreasuryComplianceAccountAbortsIf{auth_key_prefix: dummy_auth_key_prefix};
aborts_if exists<AccountFreezing::FreezingBit>(CoreAddresses::TREASURY_COMPLIANCE_ADDRESS())
with Errors::ALREADY_PUBLISHED;
// modifies and ensures needed to make this function opaque.
include CreateDiemRootAccountModifies;
include CreateDiemRootAccountEnsures;
include CreateTreasuryComplianceAccountModifies;
include CreateTreasuryComplianceAccountEnsures;
}
//////// 0L ////////
// Permissions: PUBLIC, ANYONE, OPEN!
// This function has no permissions, it doesn't check the signer.
// And it exceptionally is moving a resource to a different account than the signer.
// DiemAccount is the only code in the VM which can place a resource in an account.
// As such the module and especially this function has an attack surface.
/////// 0L ////////
// Function code: 01
public fun create_user_account_with_proof(
sender: &signer,
challenge: &vector<u8>,
solution: &vector<u8>,
difficulty: u64,
security: u64,
):address acquires AccountOperationsCapability, Balance, CumulativeDeposits, DiemAccount {
// TODO: extract address_duplicated with TowerState::init_miner_state
let (new_account_address, auth_key_prefix) = VDF::extract_address_from_challenge(challenge);
let new_signer = create_signer(new_account_address);
Roles::new_user_role_with_proof(&new_signer);
Event::publish_generator(&new_signer);
add_currencies_for_account<GAS>(&new_signer, false);
make_account(new_signer, auth_key_prefix);
onboarding_gas_transfer<GAS>(sender, new_account_address, BOOTSTRAP_COIN_VALUE);
// Init the miner state
// this verifies the VDF proof, which we use to rate limit account creation.
// account will not be created if this step fails.
let new_signer = create_signer(new_account_address);
TowerState::init_miner_state(&new_signer, challenge, solution, difficulty, security);
Ancestry::init(sender, &new_signer);
new_account_address
}
/////// 0L ////////
// Function code: 01
public fun create_user_account_with_coin(
sender: &signer,
new_account: address,
new_account_authkey_prefix: vector<u8>,
value: u64,
):address acquires AccountOperationsCapability, Balance, CumulativeDeposits, DiemAccount, SlowWallet {
let new_signer = create_signer(new_account);
Roles::new_user_role_with_proof(&new_signer);
Event::publish_generator(&new_signer);
add_currencies_for_account<GAS>(&new_signer, false);
make_account(new_signer, new_account_authkey_prefix);
let new_signer = create_signer(new_account);
Ancestry::init(sender, &new_signer);
// if the initial coin sent is the minimum amount, don't check transfer limits.
if (value <= BOOTSTRAP_COIN_VALUE) {
onboarding_gas_transfer<GAS>(sender, new_account, value);
new_account
}
// otherwise, if the onboarder wants to send more, then it must respect the transfer limits.
else {
let with_cap = extract_withdraw_capability(sender);
pay_from<GAS>(
&with_cap,
new_account,
value,
b"account generation",
b"",
);
restore_withdraw_capability(with_cap);
new_account
}
}
/////// 0L ////////
// spec fun create_user_account {
// include AddCurrencyForAccountEnsures<Token>{addr: new_account_address};
// }
/////// 0L ////////
// Permissions: PUBLIC, ANYONE, OPEN!
// Warning: this function exceptionally is moving a resource to a different account than the signer.
// DiemAccount is the only code in the VM which can place a resource in an account.
// As such the module and especially this function has an attack surface.
// Function code:02
public fun create_validator_account_with_proof(
sender: &signer,
challenge: &vector<u8>,
solution: &vector<u8>,
difficulty: u64,
security: u64,
ow_human_name: vector<u8>,
op_address: address,
op_auth_key_prefix: vector<u8>,
op_consensus_pubkey: vector<u8>,
op_validator_network_addresses: vector<u8>,
op_fullnode_network_addresses: vector<u8>,
op_human_name: vector<u8>,
):address acquires DiemAccount, Balance, AccountOperationsCapability, CumulativeDeposits, SlowWalletList { //////// 0L ////////
let sender_addr = Signer::address_of(sender);
// Rate limit spam accounts.
// check the validator is in set before creating
assert(DiemSystem::is_validator(sender_addr), Errors::limit_exceeded(120101));
assert(TowerState::can_create_val_account(sender_addr), Errors::limit_exceeded(120102));
// Check there's enough balance for bootstrapping both operator and validator account
assert(
balance<GAS>(sender_addr) > 2 * BOOTSTRAP_COIN_VALUE,
Errors::limit_exceeded(EINSUFFICIENT_BALANCE)
);
// Create Owner Account
let (new_account_address, auth_key_prefix) = VDF::extract_address_from_challenge(challenge);
let new_signer = create_signer(new_account_address);
// if the new account exists, the function is meant to be upgrading the account.
if (exists_at(new_account_address)) {
return upgrade_validator_account_with_proof(
sender,
challenge,
solution,
difficulty,
security,
ow_human_name,
op_address,
op_auth_key_prefix,
op_consensus_pubkey,
op_validator_network_addresses,
op_fullnode_network_addresses,
op_human_name,
)
};
// TODO: Perhaps this needs to be moved to the epoch boundary, so that it is only the VM which can escalate these privileges.
Roles::new_validator_role_with_proof(&new_signer, &create_signer(CoreAddresses::DIEM_ROOT_ADDRESS()));
Event::publish_generator(&new_signer);
ValidatorConfig::publish_with_proof(&new_signer, ow_human_name);
add_currencies_for_account<GAS>(&new_signer, false);
// This also verifies the VDF proof, which we use to rate limit account creation.
TowerState::init_miner_state(&new_signer, challenge, solution, difficulty, security);
// Create OP Account
let new_op_account = create_signer(op_address);
Roles::new_validator_operator_role_with_proof(&new_op_account);
Event::publish_generator(&new_op_account);
ValidatorOperatorConfig::publish_with_proof(&new_op_account, op_human_name);
add_currencies_for_account<GAS>(&new_op_account, false);
// Link owner to OP
ValidatorConfig::set_operator(&new_signer, op_address);
// OP sends network info to Owner config"
ValidatorConfig::set_config(
&new_op_account, // signer
new_account_address,
op_consensus_pubkey,
op_validator_network_addresses,
op_fullnode_network_addresses
);
// User can join validator universe list, but will only join if
// the mining is above the threshold in the preceeding period.
ValidatorUniverse::add_self(&new_signer);
Jail::init(&new_signer);
make_account(new_signer, auth_key_prefix);
make_account(new_op_account, op_auth_key_prefix);
TowerState::reset_rate_limit(sender);
// Transfer for owner
onboarding_gas_transfer<GAS>(sender, new_account_address, BOOTSTRAP_COIN_VALUE);
// Transfer for operator as well
onboarding_gas_transfer<GAS>(sender, op_address, BOOTSTRAP_COIN_VALUE);
let new_signer = create_signer(new_account_address);
Ancestry::init(sender, &new_signer);
Vouch::init(&new_signer);
Vouch::vouch_for(sender, new_account_address);
set_slow(&new_signer);
new_account_address
}
/////// 0L ////////
// Permissions: PUBLIC, ANYONE, OPEN!
// upgrades a regular account, to a validator account.
// Warning: this function exceptionally is moving a resource to a different account than the signer.
// DiemAccount is the only code in the VM which can place a resource in an account.
// As such the module and especially this function has an attack surface.
// Function code:02
public fun upgrade_validator_account_with_proof(
sender: &signer,
challenge: &vector<u8>,
solution: &vector<u8>,
difficulty: u64,
security: u64,
ow_human_name: vector<u8>,
op_address: address,
op_auth_key_prefix: vector<u8>,
op_consensus_pubkey: vector<u8>,
op_validator_network_addresses: vector<u8>,
op_fullnode_network_addresses: vector<u8>,
op_human_name: vector<u8>,
):address acquires DiemAccount, Balance, AccountOperationsCapability, CumulativeDeposits, SlowWalletList { //////// 0L ////////
let sender_addr = Signer::address_of(sender);
// Rate limit spam accounts.
assert(TowerState::can_create_val_account(sender_addr), Errors::limit_exceeded(120103));
// Check there's enough balance for bootstrapping both operator and validator account
assert(
balance<GAS>(sender_addr) > 2 * BOOTSTRAP_COIN_VALUE,
Errors::limit_exceeded(EINSUFFICIENT_BALANCE)
);
// Create Owner Account
let (new_account_address, _auth_key_prefix) = VDF::extract_address_from_challenge(challenge);
let new_signer = create_signer(new_account_address);
assert(exists_at(new_account_address), Errors::not_published(EACCOUNT));
// assert(TowerState::is_init(new_account_address), 120104);
// verifies the VDF proof, since we are not calling TowerState init.
// if the account already has a tower started just verify the block zero submitted
if (TowerState::is_init(new_account_address)) {
let valid = VDF::verify(
challenge,
solution,
&difficulty,
&security,
);
assert(valid, Errors::invalid_argument(120105));
} else {
// otherwise initialize this TowerState with a block 0.
let proof = TowerState::create_proof_blob(
*challenge,
*solution,
*&difficulty,
*&security,
);
TowerState::commit_state(&new_signer, proof);
};
// TODO: Perhaps this needs to be moved to the epoch boundary, so that it is only the VM which can escalate these privileges.
// Upgrade the user
Roles::upgrade_user_to_validator(&new_signer, &create_signer(CoreAddresses::DIEM_ROOT_ADDRESS()));
// Event::publish_generator(&new_signer);
ValidatorConfig::publish_with_proof(&new_signer, ow_human_name);
// currencies already added for owner account
// add_currencies_for_account<GAS>(&new_signer, false);
// checks the operator account has not been created yet.
// Create OP Account
let new_op_account = create_signer(op_address);
Roles::new_validator_operator_role_with_proof(&new_op_account);
Event::publish_generator(&new_op_account);
ValidatorOperatorConfig::publish_with_proof(&new_op_account, op_human_name);
add_currencies_for_account<GAS>(&new_op_account, false);
// Link owner to OP
ValidatorConfig::set_operator(&new_signer, op_address);
// OP sends network info to Owner config"
ValidatorConfig::set_config(
&new_op_account, // signer
new_account_address,
op_consensus_pubkey,
op_validator_network_addresses,
op_fullnode_network_addresses
);
// User can join validator universe list, but will only join if
// the mining is above the threshold in the preceeding period.
ValidatorUniverse::add_self(&new_signer);
Jail::init(&new_signer);
// no need to make the owner address.
// make_account(new_signer, auth_key_prefix);
make_account(new_op_account, op_auth_key_prefix);
TowerState::reset_rate_limit(sender);
// the miner who is upgrading may have coins, but better safe...
// Transfer for owner
onboarding_gas_transfer<GAS>(sender, new_account_address, BOOTSTRAP_COIN_VALUE);
// Transfer for operator as well
onboarding_gas_transfer<GAS>(sender, op_address, BOOTSTRAP_COIN_VALUE);
let new_signer = create_signer(new_account_address);
Ancestry::init(sender, &new_signer);
Vouch::init(&new_signer);
Vouch::vouch_for(sender, new_account_address);
set_slow(&new_signer);
new_account_address
}
/// Return `true` if `addr` has already published account limits for `Token`
fun has_published_account_limits<Token: store>(addr: address): bool {
if (VASP::is_vasp(addr)) {
VASP::has_account_limits<Token>(addr)
}
else {
AccountLimits::has_window_published<Token>(addr)
}
}
spec fun spec_has_published_account_limits<Token>(addr: address): bool {
if (VASP::is_vasp(addr)) VASP::spec_has_account_limits<Token>(addr)
else AccountLimits::has_window_published<Token>(addr)
}
/// Returns whether we should track and record limits for the `payer` or `payee` account.
/// Depending on the `is_withdrawal` flag passed in we determine whether the
/// `payer` or `payee` account is being queried. `VASP->any` and
/// `any->VASP` transfers are tracked in the VASP.
fun should_track_limits_for_account<Token: store>(
payer: address, payee: address, is_withdrawal: bool
): bool {
if (is_withdrawal) {
has_published_account_limits<Token>(payer) &&
VASP::is_vasp(payer) &&
!VASP::is_same_vasp(payer, payee)
} else {
has_published_account_limits<Token>(payee) &&
VASP::is_vasp(payee) &&
!VASP::is_same_vasp(payee, payer)
}
}
spec should_track_limits_for_account {
pragma opaque;
aborts_if false;
ensures result == spec_should_track_limits_for_account<Token>(payer, payee, is_withdrawal);
}
spec fun spec_should_track_limits_for_account<Token>(
payer: address, payee: address, is_withdrawal: bool
): bool {
if (is_withdrawal) {
spec_has_published_account_limits<Token>(payer) &&
VASP::is_vasp(payer) &&
!VASP::spec_is_same_vasp(payer, payee)
} else {
spec_has_published_account_limits<Token>(payee) &&
VASP::is_vasp(payee) &&
!VASP::spec_is_same_vasp(payee, payer)
}
}
/// Record a payment of `to_deposit` from `payer` to `payee` with the attached `metadata`
public(friend) fun deposit<Token: store>(
payer: address,
payee: address,
to_deposit: Diem<Token>,
metadata: vector<u8>,
metadata_signature: vector<u8>
) acquires DiemAccount, Balance, AccountOperationsCapability, CumulativeDeposits { //////// 0L ////////
DiemTimestamp::assert_operating();
AccountFreezing::assert_not_frozen(payee);
// Check that the `to_deposit` coin is non-zero
let deposit_value = Diem::value(&to_deposit);
assert(deposit_value > 0, Errors::invalid_argument(ECOIN_DEPOSIT_IS_ZERO));
// Check that an account exists at `payee`
assert(exists_at(payee), Errors::not_published(EPAYEE_DOES_NOT_EXIST));
/////// 0L /////////
// // Check that `payee` can accept payments in `Token`
// assert(
// exists<Balance<Token>>(payee),
// Errors::invalid_argument(EPAYEE_CANT_ACCEPT_CURRENCY_TYPE)
// );
// Check that the payment complies with dual attestation rules
DualAttestation::assert_payment_ok<Token>(
payer, payee, deposit_value, copy metadata, metadata_signature
);
// Ensure that this deposit is compliant with the account limits on
// this account.
if (should_track_limits_for_account<Token>(payer, payee, false)) {
assert(
AccountLimits::update_deposit_limits<Token>(
deposit_value,
VASP::parent_address(payee),
&borrow_global<AccountOperationsCapability>(CoreAddresses::DIEM_ROOT_ADDRESS()).limits_cap
),
Errors::limit_exceeded(EDEPOSIT_EXCEEDS_LIMITS)
)
};
// Deposit the `to_deposit` coin
Diem::deposit(&mut borrow_global_mut<Balance<Token>>(payee).coin, to_deposit);
// Log a received event
Event::emit_event<ReceivedPaymentEvent>(
&mut borrow_global_mut<DiemAccount>(payee).received_events,
ReceivedPaymentEvent {
amount: deposit_value,
currency_code: Diem::currency_code<Token>(),
payer,
metadata
}
);
//////// 0L ////////
// if the account wants to be tracked add tracking
maybe_update_deposit(payee, deposit_value);
}
spec deposit {
pragma opaque;
modifies global<Balance<Token>>(payee);
modifies global<DiemAccount>(payee);
modifies global<AccountLimits::Window<Token>>(VASP::spec_parent_address(payee));
// TODO(wrwg): precisely specify what changed in the modified resources using `update_field`
ensures exists<DiemAccount>(payee);
ensures exists<Balance<Token>>(payee);
ensures global<DiemAccount>(payee).withdraw_capability
== old(global<DiemAccount>(payee).withdraw_capability);
ensures global<DiemAccount>(payee).authentication_key
== old(global<DiemAccount>(payee).authentication_key);
ensures Event::spec_guid_eq(global<DiemAccount>(payee).sent_events,
old(global<DiemAccount>(payee).sent_events));
ensures Event::spec_guid_eq(global<DiemAccount>(payee).received_events,
old(global<DiemAccount>(payee).received_events));
let amount = to_deposit.value;
include DepositAbortsIf<Token>{amount: amount};
include DepositOverflowAbortsIf<Token>{amount: amount};
include DepositEnsures<Token>{amount: amount};
include DepositEmits<Token>{amount: amount};
}
spec schema DepositAbortsIf<Token> {
payer: address;
payee: address;
amount: u64;
metadata_signature: vector<u8>;
metadata: vector<u8>;
include DepositAbortsIfRestricted<Token>;
include AccountFreezing::AbortsIfFrozen{account: payee};
aborts_if !exists<Balance<Token>>(payee) with Errors::INVALID_ARGUMENT;
aborts_if !exists_at(payee) with Errors::NOT_PUBLISHED;
}
spec schema DepositOverflowAbortsIf<Token> {
payee: address;
amount: u64;
aborts_if balance<Token>(payee) + amount > max_u64() with Errors::LIMIT_EXCEEDED;
}
spec schema DepositAbortsIfRestricted<Token> {
payer: address;
payee: address;
amount: u64;
metadata_signature: vector<u8>;
metadata: vector<u8>;
include DiemTimestamp::AbortsIfNotOperating;
aborts_if amount == 0 with Errors::INVALID_ARGUMENT;
include DualAttestation::AssertPaymentOkAbortsIf<Token>{value: amount};
include
spec_should_track_limits_for_account<Token>(payer, payee, false) ==>
AccountLimits::UpdateDepositLimitsAbortsIf<Token> {
addr: VASP::spec_parent_address(payee),
};
aborts_if
spec_should_track_limits_for_account<Token>(payer, payee, false) &&
!AccountLimits::spec_update_deposit_limits<Token>(amount, VASP::spec_parent_address(payee))
with Errors::LIMIT_EXCEEDED;
include Diem::AbortsIfNoCurrency<Token>;
}
spec schema DepositEnsures<Token> {
payee: address;
amount: u64;
ensures balance<Token>(payee) == old(balance<Token>(payee)) + amount;
}
spec schema DepositEmits<Token> {
payer: address;
payee: address;
amount: u64;
metadata: vector<u8>;
let handle = global<DiemAccount>(payee).received_events;
let msg = ReceivedPaymentEvent {
amount,
currency_code: Diem::spec_currency_code<Token>(),
payer,
metadata
};
emits msg to handle;
}
/// Mint 'mint_amount' to 'designated_dealer_address' for 'tier_index' tier.
/// Max valid tier index is 3 since there are max 4 tiers per DD.
/// Sender should be treasury compliance account and receiver authorized DD.
public fun tiered_mint<Token: store>(
tc_account: &signer,
designated_dealer_address: address,
mint_amount: u64,
tier_index: u64,
) acquires DiemAccount, Balance, AccountOperationsCapability, CumulativeDeposits { //////// 0L ////////
let coin = DesignatedDealer::tiered_mint<Token>(
tc_account, mint_amount, designated_dealer_address, tier_index
);
// Use the reserved address as the payer because the funds did not come from an existing
// balance
deposit(CoreAddresses::VM_RESERVED_ADDRESS(), designated_dealer_address, coin, x"", x"")
}
spec tiered_mint {
pragma opaque;
modifies global<DiemAccount>(designated_dealer_address);
modifies global<DesignatedDealer::Dealer>(designated_dealer_address);
modifies global<DesignatedDealer::TierInfo<Token>>(designated_dealer_address);
modifies global<Balance<Token>>(designated_dealer_address);
modifies global<AccountLimits::Window<Token>>(VASP::spec_parent_address(designated_dealer_address));
modifies global<Diem::CurrencyInfo<Token>>(CoreAddresses::CURRENCY_INFO_ADDRESS());
include TieredMintAbortsIf<Token>;
include TieredMintEnsures<Token>;
include TieredMintEmits<Token>;
}
spec schema TieredMintAbortsIf<Token> {
tc_account: signer;
designated_dealer_address: address;
mint_amount: u64;
tier_index: u64;
include DesignatedDealer::TieredMintAbortsIf<Token>{dd_addr: designated_dealer_address, amount: mint_amount};
include DepositAbortsIf<Token>{payer: CoreAddresses::VM_RESERVED_ADDRESS(),
payee: designated_dealer_address, amount: mint_amount, metadata: x"", metadata_signature: x""};
include DepositOverflowAbortsIf<Token>{payee: designated_dealer_address, amount: mint_amount};
}
spec schema TieredMintEnsures<Token> {
designated_dealer_address: address;
mint_amount: u64;
let dealer_balance = global<Balance<Token>>(designated_dealer_address).coin.value;
let post post_dealer_balance = global<Balance<Token>>(designated_dealer_address).coin.value;
let currency_info = global<Diem::CurrencyInfo<Token>>(CoreAddresses::CURRENCY_INFO_ADDRESS());
let post post_currency_info = global<Diem::CurrencyInfo<Token>>(CoreAddresses::CURRENCY_INFO_ADDRESS());
/// Total value of the currency increases by `amount`.
ensures post_currency_info == update_field(currency_info, total_value, currency_info.total_value + mint_amount);
/// The balance of designated dealer increases by `amount`.
ensures post_dealer_balance == dealer_balance + mint_amount;