-
Notifications
You must be signed in to change notification settings - Fork 241
/
database.go
1673 lines (1485 loc) · 44.5 KB
/
database.go
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
package accounts
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/multiaccounts/common"
"github.com/status-im/status-go/multiaccounts/settings"
notificationssettings "github.com/status-im/status-go/multiaccounts/settings_notifications"
sociallinkssettings "github.com/status-im/status-go/multiaccounts/settings_social_links"
walletsettings "github.com/status-im/status-go/multiaccounts/settings_wallet"
"github.com/status-im/status-go/nodecfg"
"github.com/status-im/status-go/params"
)
const (
statusChatPath = "m/43'/60'/1581'/0'/0"
statusWalletRootPath = "m/44'/60'/0'/0/"
zeroAddress = "0x0000000000000000000000000000000000000000"
SyncedFromBackup = "backup" // means a keypair is coming from backed up data
ThirtyDaysInMilliseconds = 30 * 24 * 60 * 60 * 1000
)
var (
errDbPassedParameterIsNil = errors.New("accounts: passed parameter is nil")
errDbTransactionIsNil = errors.New("accounts: database transaction is nil")
ErrDbKeypairNotFound = errors.New("accounts: keypair is not found")
ErrCannotRemoveProfileKeypair = errors.New("accounts: cannot remove profile keypair")
ErrDbAccountNotFound = errors.New("accounts: account is not found")
ErrCannotRemoveProfileAccount = errors.New("accounts: cannot remove profile account")
ErrCannotRemoveDefaultWalletAccount = errors.New("accounts: cannot remove default wallet account")
ErrAccountWrongPosition = errors.New("accounts: trying to set wrong position to account")
ErrNotTheSameNumberOdAccountsToApplyReordering = errors.New("accounts: there is different number of accounts between received sync message and db accounts")
ErrNotTheSameAccountsToApplyReordering = errors.New("accounts: there are differences between accounts in received sync message and db accounts")
ErrMovingAccountToWrongPosition = errors.New("accounts: trying to move account to a wrong position")
ErrKeypairDifferentAccountsKeyUID = errors.New("cannot store keypair with different accounts' key uid than keypair's key uid")
ErrKeypairWithoutAccounts = errors.New("cannot store keypair without accounts")
)
type Keypair struct {
KeyUID string `json:"key-uid"`
Name string `json:"name"`
Type KeypairType `json:"type"`
DerivedFrom string `json:"derived-from"`
LastUsedDerivationIndex uint64 `json:"last-used-derivation-index,omitempty"`
SyncedFrom string `json:"synced-from,omitempty"` // keeps an info which device this keypair is added from can be one of two values defined in constants or device name (custom)
Clock uint64 `json:"clock,omitempty"`
Accounts []*Account `json:"accounts,omitempty"`
Keycards []*Keycard `json:"keycards,omitempty"`
Removed bool `json:"removed,omitempty"`
}
type Account struct {
Address types.Address `json:"address"`
KeyUID string `json:"key-uid"`
Wallet bool `json:"wallet"`
AddressWasNotShown bool `json:"address-was-not-shown,omitempty"`
Chat bool `json:"chat"`
Type AccountType `json:"type,omitempty"`
Path string `json:"path,omitempty"`
PublicKey types.HexBytes `json:"public-key,omitempty"`
Name string `json:"name"`
Emoji string `json:"emoji"`
ColorID common.CustomizationColor `json:"colorId,omitempty"`
Hidden bool `json:"hidden"`
Clock uint64 `json:"clock,omitempty"`
Removed bool `json:"removed,omitempty"`
Operable AccountOperable `json:"operable"` // describes an account's operability (check AccountOperable type constants for details)
CreatedAt int64 `json:"createdAt"`
Position int64 `json:"position"`
ProdPreferredChainIDs string `json:"prodPreferredChainIds"`
TestPreferredChainIDs string `json:"testPreferredChainIds"`
}
type KeypairType string
type AccountType string
type AccountOperable string
func (a KeypairType) String() string {
return string(a)
}
func (a AccountType) String() string {
return string(a)
}
func (a AccountOperable) String() string {
return string(a)
}
const (
KeypairTypeProfile KeypairType = "profile"
KeypairTypeKey KeypairType = "key"
KeypairTypeSeed KeypairType = "seed"
)
const (
AccountTypeGenerated AccountType = "generated"
AccountTypeKey AccountType = "key"
AccountTypeSeed AccountType = "seed"
AccountTypeWatch AccountType = "watch"
)
const (
AccountNonOperable AccountOperable = "no" // an account is non operable it is not a keycard account and there is no keystore file for it and no keystore file for the address it is derived from
AccountPartiallyOperable AccountOperable = "partially" // an account is partially operable if it is not a keycard account and there is created keystore file for the address it is derived from
AccountFullyOperable AccountOperable = "fully" // an account is fully operable if it is not a keycard account and there is a keystore file for it
ProdPreferredChainIDsDefault = "1:10:42161"
TestPreferredChainIDsDefault = "5:420:421613"
TestSepoliaPreferredChainIDsDefault = "11155111:11155420:421614"
)
// Returns true if an account is a wallet account that logged in user has a control over, otherwise returns false.
func (a *Account) IsWalletNonWatchOnlyAccount() bool {
return !a.Chat && len(a.Type) > 0 && a.Type != AccountTypeWatch
}
// Returns true if an account is a wallet account that is ready for sending transactions, otherwise returns false.
func (a *Account) IsWalletAccountReadyForTransaction() bool {
return a.IsWalletNonWatchOnlyAccount() && a.Operable != AccountNonOperable
}
func (a *Account) MarshalJSON() ([]byte, error) {
item := struct {
Address types.Address `json:"address"`
MixedcaseAddress string `json:"mixedcase-address"`
KeyUID string `json:"key-uid"`
Wallet bool `json:"wallet"`
Chat bool `json:"chat"`
Type AccountType `json:"type"`
Path string `json:"path"`
PublicKey types.HexBytes `json:"public-key"`
Name string `json:"name"`
Emoji string `json:"emoji"`
ColorID common.CustomizationColor `json:"colorId"`
Hidden bool `json:"hidden"`
Clock uint64 `json:"clock"`
Removed bool `json:"removed"`
Operable AccountOperable `json:"operable"`
CreatedAt int64 `json:"createdAt"`
Position int64 `json:"position"`
ProdPreferredChainIDs string `json:"prodPreferredChainIds"`
TestPreferredChainIDs string `json:"testPreferredChainIds"`
}{
Address: a.Address,
MixedcaseAddress: a.Address.Hex(),
KeyUID: a.KeyUID,
Wallet: a.Wallet,
Chat: a.Chat,
Type: a.Type,
Path: a.Path,
PublicKey: a.PublicKey,
Name: a.Name,
Emoji: a.Emoji,
ColorID: a.ColorID,
Hidden: a.Hidden,
Clock: a.Clock,
Removed: a.Removed,
Operable: a.Operable,
CreatedAt: a.CreatedAt,
Position: a.Position,
ProdPreferredChainIDs: a.ProdPreferredChainIDs,
TestPreferredChainIDs: a.TestPreferredChainIDs,
}
return json.Marshal(item)
}
func (a *Keypair) MarshalJSON() ([]byte, error) {
item := struct {
KeyUID string `json:"key-uid"`
Name string `json:"name"`
Type KeypairType `json:"type"`
DerivedFrom string `json:"derived-from"`
LastUsedDerivationIndex uint64 `json:"last-used-derivation-index"`
SyncedFrom string `json:"synced-from"`
Clock uint64 `json:"clock"`
Accounts []*Account `json:"accounts"`
Keycards []*Keycard `json:"keycards"`
Removed bool `json:"removed"`
}{
KeyUID: a.KeyUID,
Name: a.Name,
Type: a.Type,
DerivedFrom: a.DerivedFrom,
LastUsedDerivationIndex: a.LastUsedDerivationIndex,
SyncedFrom: a.SyncedFrom,
Clock: a.Clock,
Accounts: a.Accounts,
Keycards: a.Keycards,
Removed: a.Removed,
}
return json.Marshal(item)
}
func (a *Keypair) CopyKeypair() *Keypair {
kp := &Keypair{
Clock: a.Clock,
KeyUID: a.KeyUID,
Name: a.Name,
Type: a.Type,
DerivedFrom: a.DerivedFrom,
LastUsedDerivationIndex: a.LastUsedDerivationIndex,
SyncedFrom: a.SyncedFrom,
Accounts: make([]*Account, len(a.Accounts)),
Keycards: make([]*Keycard, len(a.Keycards)),
Removed: a.Removed,
}
for i, acc := range a.Accounts {
kp.Accounts[i] = &Account{
Address: acc.Address,
KeyUID: acc.KeyUID,
Wallet: acc.Wallet,
Chat: acc.Chat,
Type: acc.Type,
Path: acc.Path,
PublicKey: acc.PublicKey,
Name: acc.Name,
Emoji: acc.Emoji,
ColorID: acc.ColorID,
Hidden: acc.Hidden,
Clock: acc.Clock,
Removed: acc.Removed,
Operable: acc.Operable,
CreatedAt: acc.CreatedAt,
Position: acc.Position,
ProdPreferredChainIDs: acc.ProdPreferredChainIDs,
TestPreferredChainIDs: acc.TestPreferredChainIDs,
}
}
for i, kc := range a.Keycards {
kp.Keycards[i] = &Keycard{
KeycardUID: kc.KeycardUID,
KeycardName: kc.KeycardName,
KeycardLocked: kc.KeycardLocked,
AccountsAddresses: kc.AccountsAddresses,
KeyUID: kc.KeyUID,
}
}
return kp
}
func (a *Keypair) GetChatPublicKey() types.HexBytes {
for _, acc := range a.Accounts {
if acc.Chat {
return acc.PublicKey
}
}
return nil
}
func (a *Keypair) MigratedToKeycard() bool {
return len(a.Keycards) > 0
}
// Returns operability of a keypair:
// - if any of keypair's account is not operable, then a keyapir is considered as non operable
// - if any of keypair's account is partially operable, then a keyapir is considered as partially operable
// - if all accounts are fully operable, then a keyapir is considered as fully operable
func (a *Keypair) Operability() AccountOperable {
for _, acc := range a.Accounts {
if acc.Operable == AccountNonOperable {
return AccountNonOperable
}
if acc.Operable == AccountPartiallyOperable {
return AccountPartiallyOperable
}
}
return AccountFullyOperable
}
// Database sql wrapper for operations with browser objects.
type Database struct {
settings.DatabaseSettingsManager
*notificationssettings.NotificationsSettings
*sociallinkssettings.SocialLinksSettings
*walletsettings.WalletSettings
db *sql.DB
}
// NewDB returns a new instance of *Database
func NewDB(db *sql.DB) (*Database, error) {
sDB, err := settings.MakeNewDB(db)
if err != nil {
return nil, err
}
sn := notificationssettings.NewNotificationsSettings(db)
ssl := sociallinkssettings.NewSocialLinksSettings(db)
sw := walletsettings.NewWalletSettings(db)
return &Database{sDB, sn, ssl, sw, db}, nil
}
// DB Gets db sql.DB
func (db *Database) DB() *sql.DB {
return db.db
}
// Close closes database.
func (db *Database) Close() error {
return db.db.Close()
}
func GetAccountTypeForKeypairType(kpType KeypairType) AccountType {
switch kpType {
case KeypairTypeProfile:
return AccountTypeGenerated
case KeypairTypeKey:
return AccountTypeKey
case KeypairTypeSeed:
return AccountTypeSeed
default:
return AccountTypeWatch
}
}
func (db *Database) processRows(rows *sql.Rows) ([]*Keypair, []*Account, error) {
keypairMap := make(map[string]*Keypair)
allAccounts := []*Account{}
var (
kpKeyUID sql.NullString
kpName sql.NullString
kpType sql.NullString
kpDerivedFrom sql.NullString
kpLastUsedDerivationIndex sql.NullInt64
kpSyncedFrom sql.NullString
kpClock sql.NullInt64
kpRemoved sql.NullBool
)
var (
accAddress sql.NullString
accKeyUID sql.NullString
accPath sql.NullString
accName sql.NullString
accColorID sql.NullString
accEmoji sql.NullString
accWallet sql.NullBool
accChat sql.NullBool
accHidden sql.NullBool
accOperable sql.NullString
accClock sql.NullInt64
accCreatedAt sql.NullTime
accPosition sql.NullInt64
accRemoved sql.NullBool
accProdPreferredChainIDs sql.NullString
accTestPreferredChainIDs sql.NullString
accAddressWasNotShown sql.NullBool
)
for rows.Next() {
kp := &Keypair{}
acc := &Account{}
pubkey := []byte{}
err := rows.Scan(
&kpKeyUID, &kpName, &kpType, &kpDerivedFrom, &kpLastUsedDerivationIndex, &kpSyncedFrom, &kpClock, &kpRemoved,
&accAddress, &accKeyUID, &pubkey, &accPath, &accName, &accColorID, &accEmoji,
&accWallet, &accChat, &accHidden, &accOperable, &accClock, &accCreatedAt, &accPosition, &accRemoved,
&accProdPreferredChainIDs, &accTestPreferredChainIDs, &accAddressWasNotShown)
if err != nil {
return nil, nil, err
}
// check keypair fields
if kpKeyUID.Valid {
kp.KeyUID = kpKeyUID.String
}
if kpName.Valid {
kp.Name = kpName.String
}
if kpType.Valid {
kp.Type = KeypairType(kpType.String)
}
if kpDerivedFrom.Valid {
kp.DerivedFrom = kpDerivedFrom.String
}
if kpLastUsedDerivationIndex.Valid {
kp.LastUsedDerivationIndex = uint64(kpLastUsedDerivationIndex.Int64)
}
if kpSyncedFrom.Valid {
kp.SyncedFrom = kpSyncedFrom.String
}
if kpClock.Valid {
kp.Clock = uint64(kpClock.Int64)
}
if kpRemoved.Valid {
kp.Removed = kpRemoved.Bool
}
// check keypair accounts fields
if accAddress.Valid {
acc.Address = types.BytesToAddress([]byte(accAddress.String))
}
if accKeyUID.Valid {
acc.KeyUID = accKeyUID.String
}
if accPath.Valid {
acc.Path = accPath.String
}
if accName.Valid {
acc.Name = accName.String
}
if accColorID.Valid {
acc.ColorID = common.CustomizationColor(accColorID.String)
}
if accEmoji.Valid {
acc.Emoji = accEmoji.String
}
if accWallet.Valid {
acc.Wallet = accWallet.Bool
}
if accChat.Valid {
acc.Chat = accChat.Bool
}
if accHidden.Valid {
acc.Hidden = accHidden.Bool
}
if accOperable.Valid {
acc.Operable = AccountOperable(accOperable.String)
}
if accClock.Valid {
acc.Clock = uint64(accClock.Int64)
}
if accCreatedAt.Valid {
acc.CreatedAt = accCreatedAt.Time.UnixMilli()
}
if accPosition.Valid {
acc.Position = accPosition.Int64
}
if accProdPreferredChainIDs.Valid {
acc.ProdPreferredChainIDs = accProdPreferredChainIDs.String
}
if accTestPreferredChainIDs.Valid {
acc.TestPreferredChainIDs = accTestPreferredChainIDs.String
}
if accAddressWasNotShown.Valid {
acc.AddressWasNotShown = accAddressWasNotShown.Bool
}
if lth := len(pubkey); lth > 0 {
acc.PublicKey = make(types.HexBytes, lth)
copy(acc.PublicKey, pubkey)
}
if accRemoved.Valid {
acc.Removed = accRemoved.Bool
}
acc.Type = GetAccountTypeForKeypairType(kp.Type)
if kp.KeyUID != "" {
if _, ok := keypairMap[kp.KeyUID]; !ok {
keypairMap[kp.KeyUID] = kp
}
keypairMap[kp.KeyUID].Accounts = append(keypairMap[kp.KeyUID].Accounts, acc)
}
allAccounts = append(allAccounts, acc)
}
if err := rows.Err(); err != nil {
return nil, nil, err
}
// Convert map to list
keypairs := make([]*Keypair, 0, len(keypairMap))
for _, keypair := range keypairMap {
keypairs = append(keypairs, keypair)
}
return keypairs, allAccounts, nil
}
// If `includeRemoved` is false and `keyUID` is not empty, then keypairs which are not flagged as removed and match the `keyUID` will be returned.
// If `includeRemoved` is true and `keyUID` is not empty, then keypairs which match the `keyUID` will be returned (regardless how they are flagged).
// If `includeRemoved` is false and `keyUID` is empty, then all keypairs which are not flagged as removed will be returned.
// If `includeRemoved` is true and `keyUID` is empty, then all keypairs will be returned (regardless how they are flagged).
func (db *Database) getKeypairs(tx *sql.Tx, keyUID string, includeRemoved bool) ([]*Keypair, error) {
var (
rows *sql.Rows
err error
mainQueryWhere string
subQueryWhere string
)
if tx == nil {
tx, err = db.db.Begin()
if err != nil {
return nil, err
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
_ = tx.Rollback()
}()
}
if keyUID != "" {
mainQueryWhere = "WHERE k.key_uid = ?"
if !includeRemoved {
mainQueryWhere += " AND k.removed = 0"
}
} else if !includeRemoved {
mainQueryWhere = "WHERE k.removed = 0"
}
if !includeRemoved {
subQueryWhere = "WHERE removed = 0"
}
query := fmt.Sprintf( // nolint: gosec
`
SELECT
k.*,
ka.address,
ka.key_uid,
ka.pubkey,
ka.path,
ka.name,
ka.color,
ka.emoji,
ka.wallet,
ka.chat,
ka.hidden,
ka.operable,
ka.clock,
ka.created_at,
ka.position,
ka.removed,
ka.prod_preferred_chain_ids,
ka.test_preferred_chain_ids,
ka.address_was_not_shown
FROM
keypairs k
LEFT JOIN
(
SELECT *
FROM
keypairs_accounts
%s
) AS ka
ON
k.key_uid = ka.key_uid
%s
ORDER BY
ka.position`, subQueryWhere, mainQueryWhere)
stmt, err := tx.Prepare(query)
if err != nil {
return nil, err
}
defer stmt.Close()
if keyUID != "" {
rows, err = stmt.Query(keyUID)
} else {
rows, err = stmt.Query()
}
if err != nil {
return nil, err
}
defer rows.Close()
keypairs, _, err := db.processRows(rows)
if err != nil {
return nil, err
}
for _, kp := range keypairs {
keycards, err := db.getKeycards(tx, kp.KeyUID, "")
if err != nil {
return nil, err
}
kp.Keycards = keycards
}
return keypairs, nil
}
func (db *Database) getKeypairByKeyUID(tx *sql.Tx, keyUID string, includeRemoved bool) (*Keypair, error) {
keypairs, err := db.getKeypairs(tx, keyUID, includeRemoved)
if err != nil && err != sql.ErrNoRows {
return nil, err
}
if len(keypairs) == 0 {
return nil, ErrDbKeypairNotFound
}
return keypairs[0], nil
}
// If `includeRemoved` is false and `address` is not zero address, then accounts which are not flagged as removed and match the `address` will be returned.
// If `includeRemoved` is true and `address` is not zero address, then accounts which match the `address` will be returned (regardless how they are flagged).
// If `includeRemoved` is false and `address` is zero address, then all accounts which are not flagged as removed will be returned.
// If `includeRemoved` is true and `address` is zero address, then all accounts will be returned (regardless how they are flagged).
func (db *Database) getAccounts(tx *sql.Tx, address types.Address, includeRemoved bool) ([]*Account, error) {
var (
rows *sql.Rows
err error
where string
)
filterByAddress := address.String() != zeroAddress
if filterByAddress {
where = "WHERE ka.address = ?"
if !includeRemoved {
where += " AND ka.removed = 0"
}
} else if !includeRemoved {
where = "WHERE ka.removed = 0"
}
query := fmt.Sprintf( // nolint: gosec
`
SELECT
k.*,
ka.address,
ka.key_uid,
ka.pubkey,
ka.path,
ka.name,
ka.color,
ka.emoji,
ka.wallet,
ka.chat,
ka.hidden,
ka.operable,
ka.clock,
ka.created_at,
ka.position,
ka.removed,
ka.prod_preferred_chain_ids,
ka.test_preferred_chain_ids,
ka.address_was_not_shown
FROM
keypairs_accounts ka
LEFT JOIN
keypairs k
ON
ka.key_uid = k.key_uid
%s
ORDER BY
ka.position`, where)
if tx == nil {
if filterByAddress {
rows, err = db.db.Query(query, address)
} else {
rows, err = db.db.Query(query)
}
if err != nil {
return nil, err
}
} else {
stmt, err := tx.Prepare(query)
if err != nil {
return nil, err
}
defer stmt.Close()
if filterByAddress {
rows, err = stmt.Query(address)
} else {
rows, err = stmt.Query()
}
if err != nil {
return nil, err
}
}
defer rows.Close()
_, allAccounts, err := db.processRows(rows)
if err != nil {
return nil, err
}
return allAccounts, nil
}
func (db *Database) getAccountByAddress(tx *sql.Tx, address types.Address) (*Account, error) {
accounts, err := db.getAccounts(tx, address, false)
if err != nil && err != sql.ErrNoRows {
return nil, err
}
if len(accounts) == 0 {
return nil, ErrDbAccountNotFound
}
return accounts[0], nil
}
func (db *Database) markAccountRemoved(tx *sql.Tx, address types.Address, clock uint64) error {
if tx == nil {
return errDbTransactionIsNil
}
_, err := db.getAccountByAddress(tx, address)
if err != nil {
return err
}
query, err := tx.Prepare(`
UPDATE
keypairs_accounts
SET
removed = 1,
clock = ?
WHERE
address = ?
`)
if err != nil {
return err
}
defer query.Close()
_, err = query.Exec(clock, address)
return err
}
// Marking keypair as removed, will delete related keycards.
func (db *Database) markKeypairRemoved(tx *sql.Tx, keyUID string, clock uint64) error {
if tx == nil {
return errDbTransactionIsNil
}
keypair, err := db.getKeypairByKeyUID(tx, keyUID, false)
if err != nil {
return err
}
for _, acc := range keypair.Accounts {
if acc.Removed {
continue
}
err = db.markAccountRemoved(tx, acc.Address, clock)
if err != nil {
return err
}
}
query := `
UPDATE
keypairs
SET
removed = 1,
clock = ?
WHERE
key_uid = ?
`
stmt, err := tx.Prepare(query)
if err != nil {
return err
}
defer stmt.Close()
_, err = stmt.Exec(clock, keyUID)
if err != nil {
return err
}
err = db.deleteAllKeycardsWithKeyUID(tx, keyUID)
return err
}
// Returns active keypairs (excluding removed and excluding removed accounts).
func (db *Database) GetActiveKeypairs() ([]*Keypair, error) {
return db.getKeypairs(nil, "", false)
}
// Returns all keypairs (including removed and removed accounts).
func (db *Database) GetAllKeypairs() ([]*Keypair, error) {
return db.getKeypairs(nil, "", true)
}
// Returns keypair if it is not marked as removed and its accounts which are not marked as removed.
func (db *Database) GetKeypairByKeyUID(keyUID string) (*Keypair, error) {
return db.getKeypairByKeyUID(nil, keyUID, false)
}
// Returns active accounts (excluding removed).
func (db *Database) GetActiveAccounts() ([]*Account, error) {
return db.getAccounts(nil, types.Address{}, false)
}
// Returns all accounts (including removed).
func (db *Database) GetAllAccounts() ([]*Account, error) {
return db.getAccounts(nil, types.Address{}, true)
}
// Returns account if it is not marked as removed.
func (db *Database) GetAccountByAddress(address types.Address) (*Account, error) {
return db.getAccountByAddress(nil, address)
}
// Returns active watch only accounts (excluding removed).
func (db *Database) GetActiveWatchOnlyAccounts() (res []*Account, err error) {
accounts, err := db.getAccounts(nil, types.Address{}, false)
if err != nil {
return nil, err
}
for _, acc := range accounts {
if acc.Type == AccountTypeWatch {
res = append(res, acc)
}
}
return
}
// Returns all watch only accounts (including removed).
func (db *Database) GetAllWatchOnlyAccounts() (res []*Account, err error) {
accounts, err := db.getAccounts(nil, types.Address{}, true)
if err != nil {
return nil, err
}
for _, acc := range accounts {
if acc.Type == AccountTypeWatch {
res = append(res, acc)
}
}
return
}
func (db *Database) IsAnyAccountPartiallyOrFullyOperableForKeyUID(keyUID string) (bool, error) {
kp, err := db.getKeypairByKeyUID(nil, keyUID, false)
if err != nil {
return false, err
}
for _, acc := range kp.Accounts {
if acc.Operable != AccountNonOperable {
return true, nil
}
}
return false, nil
}
func (db *Database) RemoveKeypair(keyUID string, clock uint64) error {
tx, err := db.db.Begin()
if err != nil {
return err
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
_ = tx.Rollback()
}()
return db.markKeypairRemoved(tx, keyUID, clock)
}
func (db *Database) RemoveAccount(address types.Address, clock uint64) error {
tx, err := db.db.Begin()
if err != nil {
return err
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
_ = tx.Rollback()
}()
acc, err := db.getAccountByAddress(tx, address)
if err != nil {
return err
}
kp, err := db.getKeypairByKeyUID(tx, acc.KeyUID, false)
if err != nil && err != ErrDbKeypairNotFound {
return err
}
if kp != nil {
lastAccOfKepairToBeRemoved := true
for _, kpAcc := range kp.Accounts {
if !kpAcc.Removed && kpAcc.Address != address {
lastAccOfKepairToBeRemoved = false
}
}
if lastAccOfKepairToBeRemoved {
return db.markKeypairRemoved(tx, acc.KeyUID, clock)
}
}
err = db.markAccountRemoved(tx, address, clock)
if err != nil {
return err
}
// Update keypair clock if any but the watch only account was deleted.
if kp != nil {
err = db.updateKeypairClock(tx, acc.KeyUID, clock)
return err
}
return nil
}
func updateKeypairLastUsedIndex(tx *sql.Tx, keyUID string, index uint64, clock uint64, updateKeypairClock bool) error {
if tx == nil {
return errDbTransactionIsNil
}
var (
err error
setClock string
)
if updateKeypairClock {
setClock = ", clock = ?"
}
query := fmt.Sprintf( // nolint: gosec
`
UPDATE
keypairs
SET
last_used_derivation_index = ?
%s
WHERE
key_uid = ?`, setClock)
if setClock != "" {
_, err = tx.Exec(query, index, clock, keyUID)
} else {
_, err = tx.Exec(query, index, keyUID)
}
return err
}
func (db *Database) updateKeypairClock(tx *sql.Tx, keyUID string, clock uint64) error {
if tx == nil {
return errDbTransactionIsNil
}
_, err := tx.Exec(`
UPDATE
keypairs
SET
clock = ?
WHERE
key_uid = ?`,
clock, keyUID)
return err
}
func (db *Database) saveOrUpdateAccounts(tx *sql.Tx, accounts []*Account, updateKeypairClock, isSepoliaEnabled bool) (err error) {
if tx == nil {
return errDbTransactionIsNil
}
for _, acc := range accounts {
var relatedKeypair *Keypair
// only watch only accounts have an empty `KeyUID` field
var keyUID *string
if acc.KeyUID != "" {
relatedKeypair, err = db.getKeypairByKeyUID(tx, acc.KeyUID, true)
if err != nil {
if err == sql.ErrNoRows {
// all accounts, except watch only accounts, must have a row in `keypairs` table with the same key uid
continue
}
return err
}
keyUID = &acc.KeyUID
}
var exists bool
err = tx.QueryRow("SELECT EXISTS (SELECT 1 FROM keypairs_accounts WHERE address = ? AND removed = 0)", acc.Address).Scan(&exists)
if err != nil {
return err
}
// Apply default values if account is new and not a watch only
if !exists && acc.Type != AccountTypeWatch {
if acc.ProdPreferredChainIDs == "" {
acc.ProdPreferredChainIDs = ProdPreferredChainIDsDefault
}
if acc.TestPreferredChainIDs == "" {
if isSepoliaEnabled {
acc.TestPreferredChainIDs = TestSepoliaPreferredChainIDsDefault
} else {
acc.TestPreferredChainIDs = TestPreferredChainIDsDefault