-
Notifications
You must be signed in to change notification settings - Fork 36
/
accounts_store.rs
1804 lines (1647 loc) · 68.7 KB
/
accounts_store.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! User accounts and transactions.
use crate::constants::{MEMO_CREATE_CANISTER, MEMO_TOP_UP_CANISTER};
use crate::multi_part_transactions_processor::{MultiPartTransactionToBeProcessed, MultiPartTransactionsProcessor};
use crate::state::StableState;
use crate::stats::Stats;
use crate::time::time_millis;
use candid::CandidType;
use dfn_candid::Candid;
use histogram::AccountsStoreHistogram;
use ic_base_types::{CanisterId, PrincipalId};
use ic_crypto_sha::Sha256;
use ic_ledger_core::timestamp::TimeStamp;
use ic_ledger_core::tokens::SignedTokens;
use ic_nns_common::types::NeuronId;
use ic_nns_constants::{CYCLES_MINTING_CANISTER_ID, GOVERNANCE_CANISTER_ID};
use ic_stable_structures::{storable::Bound, Storable};
use icp_ledger::Operation::{self, Approve, Burn, Mint, Transfer, TransferFrom};
use icp_ledger::{AccountIdentifier, BlockIndex, Memo, Subaccount, Tokens};
use itertools::Itertools;
use on_wire::{FromWire, IntoWire};
use serde::Deserialize;
use std::borrow::Cow;
use std::cmp::{min, Ordering};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::fmt;
use std::ops::RangeTo;
use std::time::{Duration, SystemTime};
pub mod histogram;
pub mod schema;
use schema::{
map::AccountsDbAsMap,
proxy::{AccountsDb, AccountsDbAsProxy},
AccountsDbBTreeMapTrait, AccountsDbTrait,
};
type TransactionIndex = u64;
/// The data migration is more complicated if there are too many accounts. With below this many
/// accounts we avoid some complications.
const PRE_MIGRATION_LIMIT: u64 = 300_000;
/// Accounts, transactions and related data.
#[derive(Default)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct AccountsStore {
// TODO(NNS1-720): Use AccountIdentifier directly as the key for this HashMap
accounts_db: schema::proxy::AccountsDbAsProxy,
hardware_wallets_and_sub_accounts: HashMap<AccountIdentifier, AccountWrapper>,
// pending_transactions: HashMap<(from, to), (TransactionType, timestamp_ms_since_epoch)>
pending_transactions: HashMap<(AccountIdentifier, AccountIdentifier), (TransactionType, u64)>,
transactions: VecDeque<Transaction>,
neuron_accounts: HashMap<AccountIdentifier, NeuronDetails>,
block_height_synced_up_to: Option<BlockIndex>,
multi_part_transactions_processor: MultiPartTransactionsProcessor,
accounts_db_stats: AccountsDbStats,
last_ledger_sync_timestamp_nanos: u64,
neurons_topped_up_count: u64,
}
impl fmt::Debug for AccountsStore {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"AccountsStore{{accounts_db: {:?}, hardware_wallets_and_sub_accounts: HashMap[{:?}], pending_transactions: HashMap[{:?}], transactions: VecDeque[{:?}], neuron_accounts: HashMap[{:?}], block_height_synced_up_to: {:?}, multi_part_transactions_processor: {:?}, accounts_db_stats: {:?}, last_ledger_sync_timestamp_nanos: {:?}, neurons_topped_up_count: {:?}}}",
self.accounts_db,
self.hardware_wallets_and_sub_accounts.len(),
self.pending_transactions.len(),
self.transactions.len(),
self.neuron_accounts.len(),
self.block_height_synced_up_to,
self.multi_part_transactions_processor,
self.accounts_db_stats,
self.last_ledger_sync_timestamp_nanos,
self.neurons_topped_up_count,
)
}
}
#[derive(Default, CandidType, Deserialize, Debug, Eq, PartialEq)]
pub struct AccountsDbStats {
pub sub_accounts_count: u64,
pub hardware_wallet_accounts_count: u64,
}
/// An abstraction over sub-accounts and hardware wallets.
#[derive(CandidType, Deserialize, Debug, Eq, PartialEq)]
enum AccountWrapper {
SubAccount(AccountIdentifier, u8), // Account Identifier + Sub Account Identifier
HardwareWallet(Vec<AccountIdentifier>), // Vec of Account Identifiers since a hardware wallet could theoretically be shared between multiple accounts
}
/// A user's account.
#[derive(CandidType, Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct Account {
/// The user principal.
///
/// Note: The principal was not stored for early users. When early users log in, we discover their principal and set this field.
principal: Option<PrincipalId>,
account_identifier: AccountIdentifier,
default_account_transactions: Vec<TransactionIndex>,
sub_accounts: HashMap<u8, NamedSubAccount>,
hardware_wallet_accounts: Vec<NamedHardwareWalletAccount>,
canisters: Vec<NamedCanister>,
}
impl Storable for Account {
const BOUND: Bound = Bound::Unbounded;
fn to_bytes(&self) -> Cow<'_, [u8]> {
candid::encode_one(self).expect("Failed to serialize account").into()
}
fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
candid::decode_one(&bytes).expect("Failed to parse account from store.")
}
}
#[derive(CandidType, Deserialize, Debug, Eq, PartialEq, Clone)]
struct NamedSubAccount {
name: String,
account_identifier: AccountIdentifier,
transactions: Vec<TransactionIndex>,
}
#[derive(CandidType, Deserialize, Debug, Eq, PartialEq, Clone)]
struct NamedHardwareWalletAccount {
name: String,
principal: PrincipalId,
transactions: Vec<TransactionIndex>,
}
#[derive(CandidType, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct NamedCanister {
name: String,
canister_id: CanisterId,
}
impl NamedCanister {
/// A value used to decide how `NamedCanister`s are sorted.
///
/// This will sort the canisters such that those with names specified will appear first and will be
/// sorted by their names. Then those without names will appear last, sorted by their canister Ids.
///
/// Note: This allocates a string, so for sorting long lists this will be slow.
/// - Consider using `sort_by_cached_key(|x| x.sorting_key())`, if allowed in canisters.
/// - Determine whether the native ordering of principals is acceptable. If so, the key can
/// be of type `(bool, &str, &Principal)` where the string is the name.
fn sorting_key(&self) -> (bool, String) {
if self.name.is_empty() {
(true, self.canister_id.to_string())
} else {
(false, self.name.clone())
}
}
}
impl Ord for NamedCanister {
fn cmp(&self, other: &Self) -> Ordering {
self.sorting_key().cmp(&other.sorting_key())
}
}
impl PartialOrd for NamedCanister {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(CandidType, Deserialize, Debug, Eq, PartialEq)]
struct Transaction {
transaction_index: TransactionIndex,
block_height: BlockIndex,
timestamp: TimeStamp,
memo: Memo,
transfer: Operation,
transaction_type: Option<TransactionType>,
}
#[derive(Copy, Clone, CandidType, Deserialize, Debug, Eq, PartialEq)]
pub struct CreateCanisterArgs {
pub controller: PrincipalId,
pub amount: Tokens,
pub refund_address: AccountIdentifier,
}
#[derive(Copy, Clone, CandidType, Deserialize, Debug, Eq, PartialEq)]
pub struct TopUpCanisterArgs {
pub principal: PrincipalId,
pub canister_id: CanisterId,
pub amount: Tokens,
pub refund_address: AccountIdentifier,
}
#[derive(Clone, CandidType, Deserialize, Debug, Eq, PartialEq)]
pub struct RefundTransactionArgs {
pub recipient_principal: PrincipalId,
pub from_sub_account: Subaccount,
pub amount: Tokens,
pub original_transaction_block_height: BlockIndex,
pub refund_address: AccountIdentifier,
pub error_message: String,
}
#[derive(Copy, Clone, CandidType, Deserialize, Debug, Eq, PartialEq)]
pub enum TransactionType {
Burn,
Mint,
Transfer,
Approve,
TransferFrom,
StakeNeuron,
StakeNeuronNotification,
TopUpNeuron,
CreateCanister,
TopUpCanister(CanisterId),
ParticipateSwap(CanisterId),
}
#[derive(Clone, CandidType, Deserialize, Debug, Eq, PartialEq)]
pub struct NeuronDetails {
account_identifier: AccountIdentifier,
principal: PrincipalId,
memo: Memo,
neuron_id: Option<NeuronId>,
}
#[derive(CandidType)]
pub enum CreateSubAccountResponse {
Ok(SubAccountDetails),
AccountNotFound,
SubAccountLimitExceeded,
NameTooLong,
}
#[derive(CandidType, Deserialize)]
pub struct RenameSubAccountRequest {
account_identifier: AccountIdentifier,
new_name: String,
}
#[derive(CandidType)]
pub enum RenameSubAccountResponse {
Ok,
AccountNotFound,
SubAccountNotFound,
NameTooLong,
}
#[derive(CandidType, Deserialize)]
pub struct RegisterHardwareWalletRequest {
name: String,
principal: PrincipalId,
}
#[derive(CandidType)]
pub enum RegisterHardwareWalletResponse {
Ok,
AccountNotFound,
HardwareWalletAlreadyRegistered,
HardwareWalletLimitExceeded,
NameTooLong,
}
#[derive(CandidType)]
pub struct AccountDetails {
pub principal: PrincipalId,
pub account_identifier: AccountIdentifier,
pub sub_accounts: Vec<SubAccountDetails>,
pub hardware_wallet_accounts: Vec<HardwareWalletAccountDetails>,
}
#[derive(CandidType)]
pub struct SubAccountDetails {
name: String,
sub_account: Subaccount,
account_identifier: AccountIdentifier,
}
#[derive(CandidType)]
pub struct HardwareWalletAccountDetails {
pub name: String,
pub principal: PrincipalId,
pub account_identifier: AccountIdentifier,
}
#[derive(CandidType, Deserialize)]
pub struct AttachCanisterRequest {
name: String,
canister_id: CanisterId,
}
#[derive(CandidType)]
pub enum AttachCanisterResponse {
Ok,
CanisterLimitExceeded,
CanisterAlreadyAttached,
NameAlreadyTaken,
NameTooLong,
AccountNotFound,
}
#[derive(CandidType, Deserialize)]
pub struct RenameCanisterRequest {
name: String,
canister_id: CanisterId,
}
#[derive(CandidType)]
pub enum RenameCanisterResponse {
Ok,
NameAlreadyTaken,
NameTooLong,
AccountNotFound,
CanisterNotFound,
}
#[derive(CandidType, Deserialize)]
pub struct DetachCanisterRequest {
canister_id: CanisterId,
}
#[derive(CandidType)]
pub enum DetachCanisterResponse {
Ok,
CanisterNotFound,
AccountNotFound,
}
#[derive(CandidType, Deserialize)]
pub struct AddPendingNotifySwapRequest {
pub swap_canister_id: CanisterId,
pub buyer: PrincipalId,
pub buyer_sub_account: Option<Subaccount>,
}
#[derive(CandidType)]
pub enum AddPendingTransactionResponse {
Ok,
NotAuthorized,
}
impl AccountsStore {
pub fn get_account(&self, caller: PrincipalId) -> Option<AccountDetails> {
let account_identifier = AccountIdentifier::from(caller);
if let Some(account) = self.accounts_db.db_get_account(&account_identifier.to_vec()) {
// If the principal is empty, return None so that the browser will call add_account
// which will allow us to set the principal.
let principal = account.principal?;
let sub_accounts = account
.sub_accounts
.iter()
.sorted_unstable_by_key(|(_, sub_account)| sub_account.name.clone())
.map(|(id, sa)| SubAccountDetails {
name: sa.name.clone(),
sub_account: convert_byte_to_sub_account(*id),
account_identifier: sa.account_identifier,
})
.collect();
let hardware_wallet_accounts = account
.hardware_wallet_accounts
.iter()
.map(|a| HardwareWalletAccountDetails {
name: a.name.clone(),
principal: a.principal,
account_identifier: AccountIdentifier::from(a.principal),
})
.collect();
Some(AccountDetails {
principal,
account_identifier,
sub_accounts,
hardware_wallet_accounts,
})
} else {
None
}
}
// This will be called for new accounts and also for old accounts where the principal has not
// yet been stored, allowing us to set the principal (since originally we created accounts
// without storing each user's principal).
pub fn add_account(&mut self, caller: PrincipalId) -> bool {
self.assert_pre_migration_limit();
let account_identifier = AccountIdentifier::from(caller);
if let Some(account) = self.accounts_db.db_get_account(&account_identifier.to_vec()) {
if account.principal.is_none() {
// This is an old account that needs a one-off fix to set the principal and update the transactions.
let mut account = account.clone();
account.principal = Some(caller);
self.fix_transactions_for_early_user(&account, caller);
self.accounts_db
.db_insert_account(&account_identifier.to_vec(), account);
}
false
} else {
let new_account = Account::new(caller, account_identifier);
self.accounts_db
.db_insert_account(&account_identifier.to_vec(), new_account);
true
}
}
/// Migrates transactions for users who were created before we started storing the principal.
///
/// TODO: Monitor how many accounts still need to be migrated and remove this function when the number is 0.
fn fix_transactions_for_early_user(&mut self, account: &Account, caller: PrincipalId) {
let canister_ids: Vec<dfn_core::CanisterId> = account.canisters.iter().map(|c| c.canister_id).collect();
let transactions: Vec<TransactionIndex> = account.get_all_transactions_linked_to_principal_sorted();
// Now that we know the principal we can set the transaction types. The
// transactions must be sorted since some transaction types can only be
// determined based on earlier transactions (eg. we can only detect
// TopUpNeuron transactions that happen after StakeNeuron transactions).
for transaction_index in transactions {
let transaction = self.get_transaction(transaction_index).unwrap();
if transaction.transaction_type.is_none() {
let transaction_type = match transaction.transfer {
Burn { from: _, amount: _ } => TransactionType::Burn,
Mint { to: _, amount: _ } => TransactionType::Mint,
Transfer {
from,
to,
amount,
fee: _,
}
| TransferFrom {
spender: _,
from,
to,
amount,
fee: _,
} => {
let default_transaction_type = if matches!(transaction.transfer, Transfer { .. }) {
TransactionType::Transfer
} else {
TransactionType::TransferFrom
};
if self.accounts_db.db_get_account(&to.to_vec()).is_some() {
// If the recipient is a known account then the transaction must be either Transfer or TransferFrom,
// since for all the 'special' transaction types the recipient is not a user account
default_transaction_type
} else {
let memo = transaction.memo;
let transaction_type = self.get_transaction_type(
from,
to,
amount,
memo,
&caller,
&canister_ids,
default_transaction_type,
);
let block_height = transaction.block_height;
self.process_transaction_type(
transaction_type,
caller,
from,
to,
memo,
amount,
block_height,
);
transaction_type
}
}
Approve { .. } => TransactionType::Approve,
};
self.get_transaction_mut(transaction_index).unwrap().transaction_type = Some(transaction_type);
}
}
}
pub fn create_sub_account(&mut self, caller: PrincipalId, sub_account_name: String) -> CreateSubAccountResponse {
self.assert_pre_migration_limit();
let account_identifier = AccountIdentifier::from(caller);
if !Self::validate_account_name(&sub_account_name) {
CreateSubAccountResponse::NameTooLong
} else if let Some(mut account) = self.accounts_db.db_get_account(&account_identifier.to_vec()) {
let response = if account.sub_accounts.len() < (u8::MAX as usize) {
let sub_account_id = (1..u8::MAX).find(|i| !account.sub_accounts.contains_key(i)).unwrap();
let sub_account = convert_byte_to_sub_account(sub_account_id);
let sub_account_identifier = AccountIdentifier::new(caller, Some(sub_account));
let named_sub_account = NamedSubAccount::new(sub_account_name.clone(), sub_account_identifier);
account.sub_accounts.insert(sub_account_id, named_sub_account);
self.accounts_db
.db_insert_account(&account_identifier.to_vec(), account);
CreateSubAccountResponse::Ok(SubAccountDetails {
name: sub_account_name,
sub_account,
account_identifier: sub_account_identifier,
})
} else {
CreateSubAccountResponse::SubAccountLimitExceeded
};
if let CreateSubAccountResponse::Ok(SubAccountDetails {
name: _,
sub_account,
account_identifier: sub_account_identifier,
}) = response
{
let sub_account_id = sub_account.0[31];
self.hardware_wallets_and_sub_accounts.insert(
sub_account_identifier,
AccountWrapper::SubAccount(account_identifier, sub_account_id),
);
self.accounts_db_stats.sub_accounts_count += 1;
}
response
} else {
CreateSubAccountResponse::AccountNotFound
}
}
pub fn rename_sub_account(
&mut self,
caller: PrincipalId,
request: RenameSubAccountRequest,
) -> RenameSubAccountResponse {
let account_identifier = AccountIdentifier::from(caller).to_vec();
if !Self::validate_account_name(&request.new_name) {
RenameSubAccountResponse::NameTooLong
} else if let Some(mut account) = self.accounts_db.db_get_account(&account_identifier.to_vec()) {
if let Some(sub_account) = account
.sub_accounts
.values_mut()
.find(|sub_account| sub_account.account_identifier == request.account_identifier)
{
sub_account.name = request.new_name;
self.accounts_db
.db_insert_account(&account_identifier.to_vec(), account);
RenameSubAccountResponse::Ok
} else {
RenameSubAccountResponse::SubAccountNotFound
}
} else {
RenameSubAccountResponse::AccountNotFound
}
}
pub fn register_hardware_wallet(
&mut self,
caller: PrincipalId,
request: RegisterHardwareWalletRequest,
) -> RegisterHardwareWalletResponse {
let account_identifier = AccountIdentifier::from(caller);
if !Self::validate_account_name(&request.name) {
RegisterHardwareWalletResponse::NameTooLong
} else if self.accounts_db.db_get_account(&account_identifier.to_vec()).is_some() {
let hardware_wallet_account_identifier = AccountIdentifier::from(request.principal);
let mut account = self
.accounts_db
.db_get_account(&account_identifier.to_vec())
.unwrap()
.clone();
if account.hardware_wallet_accounts.len() == (u8::MAX as usize) {
RegisterHardwareWalletResponse::HardwareWalletLimitExceeded
} else if account
.hardware_wallet_accounts
.iter()
.any(|hw| hw.principal == request.principal)
{
RegisterHardwareWalletResponse::HardwareWalletAlreadyRegistered
} else {
account.hardware_wallet_accounts.push(NamedHardwareWalletAccount {
name: request.name,
principal: request.principal,
transactions: Vec::new(),
});
account
.hardware_wallet_accounts
.sort_unstable_by_key(|hw| hw.name.clone());
self.accounts_db
.db_insert_account(&account_identifier.to_vec(), account);
self.accounts_db_stats.hardware_wallet_accounts_count += 1;
self.link_hardware_wallet_to_account(account_identifier, hardware_wallet_account_identifier);
RegisterHardwareWalletResponse::Ok
}
} else {
RegisterHardwareWalletResponse::AccountNotFound
}
}
// Adds a transactions to be handled by `get_transaction_type` when adding transactions
// Used to add the Swap Canister Id for decentralized sale participations to the transaction
// It's needed to notify the Swap Canister afterwards in the periodic_tasks_runner
pub fn add_pending_transaction(
&mut self,
from: AccountIdentifier,
to: AccountIdentifier,
transaction_type: TransactionType,
) -> AddPendingTransactionResponse {
let now_millis = time_millis();
if self.pending_transactions.len() > 1_000 {
self.prune_old_pending_transactions(now_millis);
}
if self.pending_transactions_limit_reached() {
// We should never hit this
// Just to be safe and the pending transaction is always added
self.remove_last_pending_transaction();
}
self.pending_transactions
.insert((from, to), (transaction_type, now_millis));
AddPendingTransactionResponse::Ok
}
pub fn check_pending_transaction_buyer(&mut self, caller: PrincipalId, buyer: PrincipalId) -> bool {
// TODO: To support hardware wallets, check that the buyer is either the caller's principal or the principal of a hardware wallet linked to the caller's account.
caller == buyer
}
fn prune_old_pending_transactions(&mut self, now_millis: u64) {
const HOUR_IN_MILLISECONDS: u64 = 1_000 * 60 * 60;
let one_hour_ago = now_millis - HOUR_IN_MILLISECONDS;
// Keep pending transactions of the last hour only
self.pending_transactions
.retain(|_, (_, timestamp)| *timestamp > one_hour_ago);
}
fn remove_last_pending_transaction(&mut self) {
if let Some((k, _)) = self
.pending_transactions
.iter()
.max_by(|(_, (_, timestamp1)), (_, (_, timestamp2))| timestamp1.cmp(timestamp2))
{
self.remove_pending_transaction(*k);
}
}
fn remove_pending_transaction(&mut self, (from, to): (AccountIdentifier, AccountIdentifier)) {
self.pending_transactions.remove(&(from, to));
}
// Get pending transaction
pub fn get_pending_transaction(&self, from: AccountIdentifier, to: AccountIdentifier) -> Option<TransactionType> {
self.pending_transactions
.get(&(from, to))
.map(|&(transaction_type, _)| transaction_type)
}
pub fn complete_pending_transaction(&mut self, from: AccountIdentifier, to: AccountIdentifier) {
self.remove_pending_transaction((from, to));
}
pub fn pending_transactions_limit_reached(&self) -> bool {
// Valid pending transactions are very short lived.
// If there are many, it's because it's filled with invalid pending transactions.
const PENDING_TRANSACTIONS_LIMIT: usize = 10_000;
self.pending_transactions.len() >= PENDING_TRANSACTIONS_LIMIT
}
pub fn append_transaction(
&mut self,
transfer: Operation,
memo: Memo,
block_height: BlockIndex,
timestamp: TimeStamp,
) -> Result<bool, String> {
if let Some(block_height_synced_up_to) = self.get_block_height_synced_up_to() {
let expected_block_height = block_height_synced_up_to + 1;
if block_height != block_height_synced_up_to + 1 {
return Err(format!(
"Expected block height {}. Got block height {}",
expected_block_height, block_height
));
}
}
let transaction_index = self.get_next_transaction_index();
let mut should_store_transaction = false;
let mut transaction_type: Option<TransactionType> = None;
match transfer {
Burn { from, amount: _ } => {
if self.try_add_transaction_to_account(from, transaction_index) {
should_store_transaction = true;
transaction_type = Some(TransactionType::Burn);
}
}
Mint { to, amount: _ } => {
if self.try_add_transaction_to_account(to, transaction_index) {
should_store_transaction = true;
transaction_type = Some(TransactionType::Mint);
}
}
Transfer {
from,
to,
amount,
fee: _,
}
| TransferFrom {
from,
to,
spender: _,
amount,
fee: _,
} => {
let default_transaction_type = if matches!(transfer, Transfer { .. }) {
TransactionType::Transfer
} else {
TransactionType::TransferFrom
};
if self.try_add_transaction_to_account(to, transaction_index) {
self.try_add_transaction_to_account(from, transaction_index);
should_store_transaction = true;
transaction_type = Some(default_transaction_type);
} else if self.try_add_transaction_to_account(from, transaction_index) {
should_store_transaction = true;
if let Some(principal) = self.try_get_principal(&from) {
let canister_ids: Vec<CanisterId> =
self.get_canisters(principal).iter().map(|c| c.canister_id).collect();
transaction_type = Some(self.get_transaction_type(
from,
to,
amount,
memo,
&principal,
&canister_ids,
default_transaction_type,
));
self.process_transaction_type(
transaction_type.unwrap(),
principal,
from,
to,
memo,
amount,
block_height,
);
}
} else if let Some(neuron_details) = self.neuron_accounts.get(&to) {
// Handle the case where people top up their neuron from an external account
self.multi_part_transactions_processor.push(
block_height,
MultiPartTransactionToBeProcessed::TopUpNeuron(neuron_details.principal, neuron_details.memo),
);
}
}
Approve { .. } => {} // TODO do we want to show Approvals in the NNS Dapp?
}
if should_store_transaction {
self.transactions.push_back(Transaction::new(
transaction_index,
block_height,
timestamp,
memo,
transfer,
transaction_type,
));
}
self.block_height_synced_up_to = Some(block_height);
Ok(should_store_transaction)
}
pub fn mark_ledger_sync_complete(&mut self) {
self.last_ledger_sync_timestamp_nanos = dfn_core::api::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_nanos() as u64;
}
pub fn init_block_height_synced_up_to(&mut self, block_height: BlockIndex) {
if self.block_height_synced_up_to.is_some() {
panic!("This can only be called to initialize the 'block_height_synced_up_to' value");
}
self.block_height_synced_up_to = Some(block_height);
}
pub fn get_transactions(&self, caller: PrincipalId, request: GetTransactionsRequest) -> GetTransactionsResponse {
let account_identifier = AccountIdentifier::from(caller);
let empty_transaction_response = GetTransactionsResponse {
transactions: vec![],
total: 0,
};
let account = self.accounts_db.db_get_account(&account_identifier.to_vec());
let transactions: &Vec<u64> = match &account {
None => {
return empty_transaction_response;
}
Some(account) => {
if account_identifier == request.account_identifier {
&account.default_account_transactions
} else if let Some(hardware_wallet_account) = account
.hardware_wallet_accounts
.iter()
.find(|a| request.account_identifier == AccountIdentifier::from(a.principal))
{
&hardware_wallet_account.transactions
} else if let Some(sub_account) = account
.sub_accounts
.values()
.find(|a| a.account_identifier == request.account_identifier)
{
&sub_account.transactions
} else {
return empty_transaction_response;
}
}
};
let results: Vec<TransactionResult> = transactions
.iter()
.rev()
.skip(request.offset as usize)
.take(request.page_size as usize)
.map(|transaction_index| {
let transaction = self.get_transaction(*transaction_index).unwrap();
let transaction_type = transaction.transaction_type;
let used_transaction_type = if let Some(TransactionType::TransferFrom) = transaction_type {
Some(TransactionType::Transfer)
} else {
transaction_type
};
TransactionResult {
block_height: transaction.block_height,
timestamp: transaction.timestamp,
memo: transaction.memo,
transfer: match transaction.transfer {
Burn { amount, from: _ } => TransferResult::Burn { amount },
Mint { amount, to: _ } => TransferResult::Mint { amount },
Transfer { from, to, amount, fee }
| TransferFrom {
from,
to,
spender: _,
amount,
fee,
} => {
if from == request.account_identifier {
TransferResult::Send { to, amount, fee }
} else {
TransferResult::Receive { from, amount, fee }
}
}
Approve {
from,
spender,
allowance,
expires_at,
fee,
} => TransferResult::Approve {
from,
spender,
allowance,
expires_at,
fee,
},
},
transaction_type: used_transaction_type,
}
})
.collect();
GetTransactionsResponse {
transactions: results,
total: transactions.len() as u32,
}
}
fn find_canister_index(account: &Account, canister_id: CanisterId) -> Option<usize> {
account
.canisters
.iter()
.enumerate()
.find(|(_, canister)| canister.canister_id == canister_id)
.map(|(index, _)| index)
}
pub fn attach_canister(&mut self, caller: PrincipalId, request: AttachCanisterRequest) -> AttachCanisterResponse {
if !Self::validate_canister_name(&request.name) {
AttachCanisterResponse::NameTooLong
} else {
let account_identifier = AccountIdentifier::from(caller).to_vec();
if let Some(mut account) = self.accounts_db.db_get_account(&account_identifier.to_vec()) {
let mut index_to_remove: Option<usize> = None;
for (index, c) in account.canisters.iter().enumerate() {
if !request.name.is_empty() && c.name == request.name {
return AttachCanisterResponse::NameAlreadyTaken;
}
// The periodic_task_runner might attach the canister before this call.
// The canister attached by the periodic_task_runner has name `""`
if c.canister_id == request.canister_id {
if c.name.is_empty() && !request.name.is_empty() {
index_to_remove = Some(index);
} else {
return AttachCanisterResponse::CanisterAlreadyAttached;
// Note: It might be nice to tell the user the name of the existing canister.
}
}
}
if let Some(index) = index_to_remove {
// Remove the previous attached canister before reattaching.
account.canisters.remove(index);
}
if account.canisters.len() >= u8::MAX as usize {
return AttachCanisterResponse::CanisterLimitExceeded;
}
account.canisters.push(NamedCanister {
name: request.name,
canister_id: request.canister_id,
});
account.canisters.sort();
self.accounts_db
.db_insert_account(&account_identifier.to_vec(), account);
AttachCanisterResponse::Ok
} else {
AttachCanisterResponse::AccountNotFound
}
}
}
pub fn rename_canister(&mut self, caller: PrincipalId, request: RenameCanisterRequest) -> RenameCanisterResponse {
if !Self::validate_canister_name(&request.name) {
RenameCanisterResponse::NameTooLong
} else {
let account_identifier = AccountIdentifier::from(caller).to_vec();
if let Some(mut account) = self.accounts_db.db_get_account(&account_identifier.to_vec()) {
if !request.name.is_empty() && account.canisters.iter().any(|c| c.name == request.name) {
return RenameCanisterResponse::NameAlreadyTaken;
}
if let Some(index) = Self::find_canister_index(&account, request.canister_id) {
account.canisters.remove(index);
account.canisters.push(NamedCanister {
name: request.name,
canister_id: request.canister_id,
});
account.canisters.sort();
self.accounts_db
.db_insert_account(&account_identifier.to_vec(), account);
RenameCanisterResponse::Ok
} else {
RenameCanisterResponse::CanisterNotFound
}
} else {
RenameCanisterResponse::AccountNotFound
}
}
}
pub fn detach_canister(&mut self, caller: PrincipalId, request: DetachCanisterRequest) -> DetachCanisterResponse {
let account_identifier = AccountIdentifier::from(caller).to_vec();
if let Some(mut account) = self.accounts_db.db_get_account(&account_identifier.to_vec()) {
if let Some(index) = Self::find_canister_index(&account, request.canister_id) {
account.canisters.remove(index);
self.accounts_db
.db_insert_account(&account_identifier.to_vec(), account);
DetachCanisterResponse::Ok
} else {
DetachCanisterResponse::CanisterNotFound
}
} else {
DetachCanisterResponse::AccountNotFound
}
}
pub fn get_canisters(&self, caller: PrincipalId) -> Vec<NamedCanister> {
let account_identifier = AccountIdentifier::from(caller);
if let Some(account) = self.accounts_db.db_get_account(&account_identifier.to_vec()) {
account.canisters.to_vec()
} else {
Vec::new()
}
}
// We skip the checks here since in this scenario we must store the canister otherwise the user
// won't be able to retrieve its Id.
pub fn attach_newly_created_canister(&mut self, principal: PrincipalId, canister_id: CanisterId) {
let account_identifier = AccountIdentifier::from(principal).to_vec();
if let Some(mut account) = self.accounts_db.db_get_account(&account_identifier.to_vec()) {
// We only attach if it doesn't already exist
if Self::find_canister_index(&account, canister_id).is_none() {