-
Notifications
You must be signed in to change notification settings - Fork 244
/
geth_backend.go
1720 lines (1454 loc) · 46.3 KB
/
geth_backend.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 api
import (
"context"
"database/sql"
"errors"
"fmt"
"math/big"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/imdario/mergo"
"github.com/ethereum/go-ethereum/common/hexutil"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
signercore "github.com/ethereum/go-ethereum/signer/core/apitypes"
"github.com/status-im/status-go/account"
"github.com/status-im/status-go/account/generator"
"github.com/status-im/status-go/appdatabase"
"github.com/status-im/status-go/connection"
"github.com/status-im/status-go/eth-node/crypto"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/images"
"github.com/status-im/status-go/logutils"
"github.com/status-im/status-go/multiaccounts"
"github.com/status-im/status-go/multiaccounts/accounts"
"github.com/status-im/status-go/multiaccounts/settings"
"github.com/status-im/status-go/node"
"github.com/status-im/status-go/nodecfg"
"github.com/status-im/status-go/params"
"github.com/status-im/status-go/protocol"
"github.com/status-im/status-go/protocol/requests"
"github.com/status-im/status-go/rpc"
"github.com/status-im/status-go/services/ext"
"github.com/status-im/status-go/services/personal"
"github.com/status-im/status-go/services/typeddata"
"github.com/status-im/status-go/signal"
"github.com/status-im/status-go/sqlite"
"github.com/status-im/status-go/transactions"
)
var (
// ErrWhisperClearIdentitiesFailure clearing whisper identities has failed.
ErrWhisperClearIdentitiesFailure = errors.New("failed to clear whisper identities")
// ErrWhisperIdentityInjectionFailure injecting whisper identities has failed.
ErrWhisperIdentityInjectionFailure = errors.New("failed to inject identity into Whisper")
// ErrWakuIdentityInjectionFailure injecting whisper identities has failed.
ErrWakuIdentityInjectionFailure = errors.New("failed to inject identity into waku")
// ErrUnsupportedRPCMethod is for methods not supported by the RPC interface
ErrUnsupportedRPCMethod = errors.New("method is unsupported by RPC interface")
// ErrRPCClientUnavailable is returned if an RPC client can't be retrieved.
// This is a normal situation when a node is stopped.
ErrRPCClientUnavailable = errors.New("JSON-RPC client is unavailable")
// ErrDBNotAvailable is returned if a method is called before the DB is available for usage
ErrDBNotAvailable = errors.New("DB is unavailable")
// ErrConfigNotAvailable is returned if a method is called before the nodeconfig is set
ErrConfigNotAvailable = errors.New("NodeConfig is not available")
)
var _ StatusBackend = (*GethStatusBackend)(nil)
// GethStatusBackend implements the Status.im service over go-ethereum
type GethStatusBackend struct {
mu sync.Mutex
// rootDataDir is the same for all networks.
rootDataDir string
appDB *sql.DB
config *params.NodeConfig
statusNode *node.StatusNode
personalAPI *personal.PublicAPI
multiaccountsDB *multiaccounts.Database
account *multiaccounts.Account
accountManager *account.GethManager
transactor *transactions.Transactor
connectionState connection.State
appState appState
selectedAccountKeyID string
log log.Logger
allowAllRPC bool // used only for tests, disables api method restrictions
}
// NewGethStatusBackend create a new GethStatusBackend instance
func NewGethStatusBackend() *GethStatusBackend {
defer log.Info("Status backend initialized", "backend", "geth", "version", params.Version, "commit", params.GitCommit, "IpfsGatewayURL", params.IpfsGatewayURL)
backend := &GethStatusBackend{}
backend.initialize()
return backend
}
func (b *GethStatusBackend) initialize() {
accountManager := account.NewGethManager()
transactor := transactions.NewTransactor()
personalAPI := personal.NewAPI()
statusNode := node.New(transactor)
b.statusNode = statusNode
b.accountManager = accountManager
b.transactor = transactor
b.personalAPI = personalAPI
b.statusNode.SetMultiaccountsDB(b.multiaccountsDB)
b.log = log.New("package", "status-go/api.GethStatusBackend")
}
// StatusNode returns reference to node manager
func (b *GethStatusBackend) StatusNode() *node.StatusNode {
return b.statusNode
}
// AccountManager returns reference to account manager
func (b *GethStatusBackend) AccountManager() *account.GethManager {
return b.accountManager
}
// Transactor returns reference to a status transactor
func (b *GethStatusBackend) Transactor() *transactions.Transactor {
return b.transactor
}
// SelectedAccountKeyID returns a Whisper key ID of the selected chat key pair.
func (b *GethStatusBackend) SelectedAccountKeyID() string {
return b.selectedAccountKeyID
}
// IsNodeRunning confirm that node is running
func (b *GethStatusBackend) IsNodeRunning() bool {
return b.statusNode.IsRunning()
}
// StartNode start Status node, fails if node is already started
func (b *GethStatusBackend) StartNode(config *params.NodeConfig) error {
b.mu.Lock()
defer b.mu.Unlock()
if err := b.startNode(config); err != nil {
signal.SendNodeCrashed(err)
return err
}
return nil
}
func (b *GethStatusBackend) UpdateRootDataDir(datadir string) {
b.mu.Lock()
defer b.mu.Unlock()
b.rootDataDir = datadir
}
func (b *GethStatusBackend) GetMultiaccountDB() *multiaccounts.Database {
return b.multiaccountsDB
}
func (b *GethStatusBackend) InitializeAccounts(rootDirectory string) error {
b.UpdateRootDataDir(rootDirectory)
manager := b.AccountManager()
keystoreDir := filepath.Join(rootDirectory, keystoreRelativePath)
if err := manager.InitKeystore(keystoreDir); err != nil {
return err
}
return b.OpenAccounts()
}
func (b *GethStatusBackend) OpenAccounts() error {
b.mu.Lock()
defer b.mu.Unlock()
if b.multiaccountsDB != nil {
return nil
}
db, err := multiaccounts.InitializeDB(filepath.Join(b.rootDataDir, "accounts.sql"))
if err != nil {
b.log.Error("failed to initialize accounts db", "err", err)
return err
}
b.multiaccountsDB = db
// Probably we should iron out a bit better how to create/dispose of the status-service
b.statusNode.SetMultiaccountsDB(db)
return nil
}
func (b *GethStatusBackend) GetAccounts() ([]multiaccounts.Account, error) {
b.mu.Lock()
defer b.mu.Unlock()
if b.multiaccountsDB == nil {
return nil, errors.New("accounts db wasn't initialized")
}
return b.multiaccountsDB.GetAccounts()
}
func (b *GethStatusBackend) SaveAccount(account multiaccounts.Account) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.multiaccountsDB == nil {
return errors.New("accounts db wasn't initialized")
}
return b.multiaccountsDB.SaveAccount(account)
}
func (b *GethStatusBackend) DeleteMultiaccount(keyUID string, keyStoreDir string) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.multiaccountsDB == nil {
return errors.New("accounts db wasn't initialized")
}
err := b.multiaccountsDB.DeleteAccount(keyUID)
if err != nil {
return err
}
dbFiles := []string{
filepath.Join(b.rootDataDir, fmt.Sprintf("app-%x.sql", keyUID)),
filepath.Join(b.rootDataDir, fmt.Sprintf("app-%x.sql-shm", keyUID)),
filepath.Join(b.rootDataDir, fmt.Sprintf("app-%x.sql-wal", keyUID)),
filepath.Join(b.rootDataDir, fmt.Sprintf("%s.db", keyUID)),
filepath.Join(b.rootDataDir, fmt.Sprintf("%s.db-shm", keyUID)),
filepath.Join(b.rootDataDir, fmt.Sprintf("%s.db-wal", keyUID)),
}
for _, path := range dbFiles {
if _, err := os.Stat(path); err == nil {
err = os.Remove(path)
if err != nil {
return err
}
}
}
if b.account != nil && b.account.KeyUID == keyUID {
// reset active account
b.account = nil
}
return os.RemoveAll(keyStoreDir)
}
func (b *GethStatusBackend) DeleteImportedKey(address, password, keyStoreDir string) error {
b.mu.Lock()
defer b.mu.Unlock()
err := filepath.Walk(keyStoreDir, func(path string, fileInfo os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.Contains(fileInfo.Name(), address) {
_, err := b.accountManager.VerifyAccountPassword(keyStoreDir, "0x"+address, password)
if err != nil {
b.log.Error("failed to verify account", "account", address, "error", err)
return err
}
return os.Remove(path)
}
return nil
})
return err
}
func (b *GethStatusBackend) ensureAppDBOpened(account multiaccounts.Account, password string) (err error) {
b.mu.Lock()
defer b.mu.Unlock()
if b.appDB != nil {
return nil
}
if len(b.rootDataDir) == 0 {
return errors.New("root datadir wasn't provided")
}
// Migrate file path to fix issue https://github.com/status-im/status-go/issues/2027
oldPath := filepath.Join(b.rootDataDir, fmt.Sprintf("app-%x.sql", account.KeyUID))
newPath := filepath.Join(b.rootDataDir, fmt.Sprintf("%s.db", account.KeyUID))
_, err = os.Stat(oldPath)
if err == nil {
err := os.Rename(oldPath, newPath)
if err != nil {
return err
}
// rename journals as well, but ignore errors
_ = os.Rename(oldPath+"-shm", newPath+"-shm")
_ = os.Rename(oldPath+"-wal", newPath+"-wal")
}
b.appDB, err = appdatabase.InitializeDB(newPath, password, account.KDFIterations)
if err != nil {
b.log.Error("failed to initialize db", "err", err)
return err
}
b.statusNode.SetAppDB(b.appDB)
return nil
}
func (b *GethStatusBackend) setupLogSettings() error {
logSettings := logutils.LogSettings{
Enabled: b.config.LogEnabled,
MobileSystem: b.config.LogMobileSystem,
Level: b.config.LogLevel,
File: b.config.LogFile,
MaxSize: b.config.LogMaxSize,
MaxBackups: b.config.LogMaxBackups,
CompressRotated: b.config.LogCompressRotated,
}
if err := logutils.OverrideRootLogWithConfig(logSettings, false); err != nil {
return err
}
return nil
}
// StartNodeWithKey instead of loading addresses from database this method derives address from key
// and uses it in application.
// TODO: we should use a proper struct with optional values instead of duplicating the regular functions
// with small variants for keycard, this created too many bugs
func (b *GethStatusBackend) startNodeWithKey(acc multiaccounts.Account, password string, keyHex string) error {
if acc.KDFIterations == 0 {
kdfIterations, err := b.multiaccountsDB.GetAccountKDFIterationsNumber(acc.KeyUID)
if err != nil {
return err
}
acc.KDFIterations = kdfIterations
}
err := b.ensureAppDBOpened(acc, password)
if err != nil {
return err
}
err = b.loadNodeConfig(nil)
if err != nil {
return err
}
err = b.setupLogSettings()
if err != nil {
return err
}
b.account = &acc
accountsDB, err := accounts.NewDB(b.appDB)
if err != nil {
return err
}
walletAddr, err := accountsDB.GetWalletAddress()
if err != nil {
return err
}
watchAddrs, err := accountsDB.GetAddresses()
if err != nil {
return err
}
chatKey, err := ethcrypto.HexToECDSA(keyHex)
if err != nil {
return err
}
err = b.StartNode(b.config)
if err != nil {
return err
}
if err := b.accountManager.SetChatAccount(chatKey); err != nil {
return err
}
_, err = b.accountManager.SelectedChatAccount()
if err != nil {
return err
}
b.accountManager.SetAccountAddresses(walletAddr, watchAddrs...)
err = b.injectAccountsIntoServices()
if err != nil {
return err
}
err = b.multiaccountsDB.UpdateAccountTimestamp(acc.KeyUID, time.Now().Unix())
if err != nil {
return err
}
return nil
}
func (b *GethStatusBackend) StartNodeWithKey(acc multiaccounts.Account, password string, keyHex string) error {
err := b.startNodeWithKey(acc, password, keyHex)
if err != nil {
// Stop node for clean up
_ = b.StopNode()
}
signal.SendLoggedIn(err)
return err
}
func (b *GethStatusBackend) OverwriteNodeConfigValues(conf *params.NodeConfig, n *params.NodeConfig) (*params.NodeConfig, error) {
if err := mergo.Merge(conf, n, mergo.WithOverride); err != nil {
return nil, err
}
conf.Networks = n.Networks
if err := b.saveNodeConfig(conf); err != nil {
return nil, err
}
return conf, nil
}
func (b *GethStatusBackend) startNodeWithAccount(acc multiaccounts.Account, password string, inputNodeCfg *params.NodeConfig) error {
err := b.ensureAppDBOpened(acc, password)
if err != nil {
return err
}
err = b.loadNodeConfig(inputNodeCfg)
if err != nil {
return err
}
err = b.setupLogSettings()
if err != nil {
return err
}
b.account = &acc
accountsDB, err := accounts.NewDB(b.appDB)
if err != nil {
return err
}
chatAddr, err := accountsDB.GetChatAddress()
if err != nil {
return err
}
walletAddr, err := accountsDB.GetWalletAddress()
if err != nil {
return err
}
watchAddrs, err := accountsDB.GetWalletAddresses()
if err != nil {
return err
}
login := account.LoginParams{
Password: password,
ChatAddress: chatAddr,
WatchAddresses: watchAddrs,
MainAccount: walletAddr,
}
err = b.StartNode(b.config)
if err != nil {
b.log.Info("failed to start node")
return err
}
err = b.SelectAccount(login)
if err != nil {
return err
}
err = b.multiaccountsDB.UpdateAccountTimestamp(acc.KeyUID, time.Now().Unix())
if err != nil {
b.log.Info("failed to update account")
return err
}
return nil
}
func (b *GethStatusBackend) MigrateKeyStoreDir(acc multiaccounts.Account, password, oldDir, newDir string) error {
err := b.ensureAppDBOpened(acc, password)
if err != nil {
return err
}
accountDB, err := accounts.NewDB(b.appDB)
if err != nil {
return err
}
accounts, err := accountDB.GetAccounts()
if err != nil {
return err
}
settings, err := accountDB.GetSettings()
if err != nil {
return err
}
addresses := []string{settings.EIP1581Address.Hex(), settings.WalletRootAddress.Hex()}
for _, account := range accounts {
addresses = append(addresses, account.Address.Hex())
}
err = b.accountManager.MigrateKeyStoreDir(oldDir, newDir, addresses)
if err != nil {
return err
}
return nil
}
func (b *GethStatusBackend) Login(keyUID, password string) error {
return b.startNodeWithAccount(multiaccounts.Account{KeyUID: keyUID}, password, nil)
}
func (b *GethStatusBackend) StartNodeWithAccount(acc multiaccounts.Account, password string, nodecfg *params.NodeConfig) error {
err := b.startNodeWithAccount(acc, password, nodecfg)
if err != nil {
// Stop node for clean up
_ = b.StopNode()
}
signal.SendLoggedIn(err)
return err
}
func (b *GethStatusBackend) ExportUnencryptedDatabase(acc multiaccounts.Account, password, directory string) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.appDB != nil {
return nil
}
if len(b.rootDataDir) == 0 {
return errors.New("root datadir wasn't provided")
}
// Migrate file path to fix issue https://github.com/status-im/status-go/issues/2027
oldPath := filepath.Join(b.rootDataDir, fmt.Sprintf("app-%x.sql", acc.KeyUID))
newPath := filepath.Join(b.rootDataDir, fmt.Sprintf("%s.db", acc.KeyUID))
_, err := os.Stat(oldPath)
if err == nil {
err := os.Rename(oldPath, newPath)
if err != nil {
return err
}
// rename journals as well, but ignore errors
_ = os.Rename(oldPath+"-shm", newPath+"-shm")
_ = os.Rename(oldPath+"-wal", newPath+"-wal")
}
err = appdatabase.DecryptDatabase(newPath, directory, password, acc.KDFIterations)
if err != nil {
b.log.Error("failed to initialize db", "err", err)
return err
}
return nil
}
func (b *GethStatusBackend) ImportUnencryptedDatabase(acc multiaccounts.Account, password, databasePath string) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.appDB != nil {
return nil
}
if len(b.rootDataDir) == 0 {
return errors.New("root datadir wasn't provided")
}
path := filepath.Join(b.rootDataDir, fmt.Sprintf("%s.db", acc.KeyUID))
err := appdatabase.EncryptDatabase(databasePath, path, password, acc.KDFIterations)
if err != nil {
b.log.Error("failed to initialize db", "err", err)
return err
}
return nil
}
func (b *GethStatusBackend) ChangeDatabasePassword(keyUID string, password string, newPassword string) error {
dbPath := filepath.Join(b.rootDataDir, fmt.Sprintf("%s.db", keyUID))
config := b.StatusNode().Config()
keyDir := ""
if config == nil {
keyDir = b.accountManager.Keydir
} else {
keyDir = config.KeyStoreDir
}
if keyDir != "" {
err := b.accountManager.ReEncryptKeyStoreDir(keyDir, password, newPassword)
if err != nil {
return fmt.Errorf("ReEncryptKeyStoreDir error: %v", err)
}
}
kdfIterations, err := b.multiaccountsDB.GetAccountKDFIterationsNumber(keyUID)
if err != nil {
return err
}
err = appdatabase.ChangeDatabasePassword(dbPath, password, kdfIterations, newPassword)
if err != nil {
if config != nil {
keyDir := config.KeyStoreDir
// couldn't change db password so undo keystore changes to mainitain consistency
_ = b.accountManager.ReEncryptKeyStoreDir(keyDir, newPassword, password)
}
return err
}
return nil
}
func (b *GethStatusBackend) tryToDeleteAccount(address types.Address, password, newPassword string) error {
err := b.accountManager.DeleteAccount(address, newPassword)
if err != nil {
err = b.accountManager.DeleteAccount(address, password)
if err != nil && err.Error() != "no key for given address or file" {
b.log.Error("error on deleting account", "err", err)
return err
}
}
return nil
}
func (b *GethStatusBackend) ConvertToKeycardAccount(account multiaccounts.Account, s settings.Settings, password string, newPassword string) error {
err := b.multiaccountsDB.UpdateAccountKeycardPairing(account.KeyUID, account.KeycardPairing)
if err != nil {
return err
}
err = b.ensureAppDBOpened(account, password)
if err != nil {
return err
}
accountDB, err := accounts.NewDB(b.appDB)
if err != nil {
return err
}
err = accountDB.SaveSettingField(settings.KeycardInstanceUID, s.KeycardInstanceUID)
if err != nil {
return err
}
err = accountDB.SaveSettingField(settings.KeycardPairedOn, s.KeycardPairedOn)
if err != nil {
return err
}
err = accountDB.SaveSettingField(settings.KeycardPairing, s.KeycardPairing)
if err != nil {
return err
}
err = accountDB.SaveSettingField(settings.Mnemonic, nil)
if err != nil {
return err
}
knownAccounts, err := accountDB.GetAccounts()
if err != nil {
return err
}
masterAddress, err := accountDB.GetMasterAddress()
if err != nil {
return err
}
dappsAddress, err := accountDB.GetDappsAddress()
if err != nil {
return err
}
eip1581Address, err := accountDB.GetEIP1581Address()
if err != nil {
return err
}
walletRootAddress, err := accountDB.GetWalletRootAddress()
if err != nil {
return err
}
err = b.closeAppDB()
if err != nil {
return err
}
err = b.ChangeDatabasePassword(account.KeyUID, password, newPassword)
if err != nil {
return err
}
// We need to delete all accounts for the keypair which is being migrated
// no need to check for the error below cause if this action fails from
// whichever reason the account is still successfully migrated
for _, acc := range knownAccounts {
if account.KeyUID == acc.KeyUID {
err = b.tryToDeleteAccount(acc.Address, password, newPassword)
if err != nil {
return err
}
}
}
err = b.tryToDeleteAccount(masterAddress, password, newPassword)
if err != nil {
return err
}
err = b.tryToDeleteAccount(dappsAddress, password, newPassword)
if err != nil {
return err
}
err = b.tryToDeleteAccount(eip1581Address, password, newPassword)
if err != nil {
return err
}
err = b.tryToDeleteAccount(walletRootAddress, password, newPassword)
if err != nil {
return err
}
return nil
}
func (b *GethStatusBackend) RestoreAccountAndLogin(request *requests.RestoreAccount) error {
if err := request.Validate(); err != nil {
return err
}
return b.generateOrImportAccount(request.Mnemonic, &request.CreateAccount)
}
func (b *GethStatusBackend) generateOrImportAccount(mnemonic string, request *requests.CreateAccount) error {
if err := b.accountManager.InitKeystore(filepath.Join(request.BackupDisabledDataDir, keystoreRelativePath)); err != nil {
return err
}
b.UpdateRootDataDir(request.BackupDisabledDataDir)
err := b.OpenAccounts()
if err != nil {
b.log.Error("failed open accounts", err)
return err
}
accountGenerator := b.accountManager.AccountsGenerator()
var info generator.GeneratedAccountInfo
if mnemonic == "" {
// generate 1(n) account with default mnemonic length and no passphrase
generatedAccountInfos, err := accountGenerator.Generate(defaultMnemonicLength, 1, "")
info = generatedAccountInfos[0]
if err != nil {
return err
}
} else {
info, err = accountGenerator.ImportMnemonic(mnemonic, "")
if err != nil {
return err
}
}
derivedAddresses, err := accountGenerator.DeriveAddresses(info.ID, paths)
if err != nil {
return err
}
_, err = accountGenerator.StoreDerivedAccounts(info.ID, request.Password, paths)
if err != nil {
return err
}
account := multiaccounts.Account{
KeyUID: info.KeyUID,
Name: request.DisplayName,
KDFIterations: sqlite.ReducedKDFIterationsNumber,
}
settings, err := defaultSettings(info, derivedAddresses, nil)
if err != nil {
return err
}
settings.DisplayName = request.DisplayName
// If restoring an account, we don't set the mnemonic
if mnemonic == "" {
settings.Mnemonic = &info.Mnemonic
}
nodeConfig, err := defaultNodeConfig(settings.InstallationID, request)
if err != nil {
return err
}
walletDerivedAccount := derivedAddresses[pathDefaultWallet]
walletAccount := &accounts.Account{
PublicKey: types.Hex2Bytes(walletDerivedAccount.PublicKey),
KeyUID: info.KeyUID,
Address: types.HexToAddress(walletDerivedAccount.Address),
Color: "",
Wallet: true,
Path: pathDefaultWallet,
Name: walletAccountDefaultName,
}
chatDerivedAccount := derivedAddresses[pathDefaultChat]
chatAccount := &accounts.Account{
PublicKey: types.Hex2Bytes(chatDerivedAccount.PublicKey),
KeyUID: info.KeyUID,
Address: types.HexToAddress(chatDerivedAccount.Address),
Name: request.DisplayName,
Chat: true,
Path: pathDefaultChat,
}
accounts := []*accounts.Account{walletAccount, chatAccount}
err = b.StartNodeWithAccountAndInitialConfig(account, request.Password, *settings, nodeConfig, accounts)
if err != nil {
b.log.Error("start node", err)
return err
}
if request.ImagePath != "" {
iis, err := images.GenerateIdentityImages(request.ImagePath, 0, 0, 1000, 1000)
if err != nil {
return err
}
err = b.multiaccountsDB.StoreIdentityImages(info.KeyUID, iis, false)
if err != nil {
return err
}
}
return nil
}
func (b *GethStatusBackend) CreateAccountAndLogin(request *requests.CreateAccount) error {
if err := request.Validate(); err != nil {
return err
}
return b.generateOrImportAccount("", request)
}
func (b *GethStatusBackend) ConvertToRegularAccount(mnemonic string, currPassword string, newPassword string) error {
mnemonicNoExtraSpaces := strings.Join(strings.Fields(mnemonic), " ")
accountInfo, err := b.accountManager.AccountsGenerator().ImportMnemonic(mnemonicNoExtraSpaces, "")
if err != nil {
return err
}
kdfIterations, err := b.multiaccountsDB.GetAccountKDFIterationsNumber(accountInfo.KeyUID)
if err != nil {
return err
}
err = b.ensureAppDBOpened(multiaccounts.Account{KeyUID: accountInfo.KeyUID, KDFIterations: kdfIterations}, newPassword)
if err != nil {
return err
}
db, err := accounts.NewDB(b.appDB)
if err != nil {
return err
}
knownAccounts, err := db.GetAccounts()
if err != nil {
return err
}
// We add these two paths, cause others will be added via `StoreAccount` function call
const pathWalletRoot = "m/44'/60'/0'/0"
const pathEIP1581 = "m/43'/60'/1581'"
var paths []string
paths = append(paths, pathWalletRoot, pathEIP1581)
for _, acc := range knownAccounts {
if accountInfo.KeyUID == acc.KeyUID {
paths = append(paths, acc.Path)
}
}
_, err = b.accountManager.AccountsGenerator().StoreAccount(accountInfo.ID, currPassword)
if err != nil {
return err
}
_, err = b.accountManager.AccountsGenerator().StoreDerivedAccounts(accountInfo.ID, currPassword, paths)
if err != nil {
return err
}
err = b.multiaccountsDB.UpdateAccountKeycardPairing(accountInfo.KeyUID, "")
if err != nil {
return err
}
err = db.DeleteKeypair(accountInfo.KeyUID)
if err != nil {
return err
}
err = db.SaveSettingField(settings.KeycardInstanceUID, "")
if err != nil {
return err
}
err = db.SaveSettingField(settings.KeycardPairedOn, 0)
if err != nil {
return err
}
err = db.SaveSettingField(settings.KeycardPairing, "")
if err != nil {
return err
}
err = b.closeAppDB()
if err != nil {
return err
}
return b.ChangeDatabasePassword(accountInfo.KeyUID, currPassword, newPassword)
}
func (b *GethStatusBackend) VerifyDatabasePassword(keyUID string, password string) error {
kdfIterations, err := b.multiaccountsDB.GetAccountKDFIterationsNumber(keyUID)
if err != nil {
return err
}
err = b.ensureAppDBOpened(multiaccounts.Account{KeyUID: keyUID, KDFIterations: kdfIterations}, password)
if err != nil {
return err
}
accountsDB, err := accounts.NewDB(b.appDB)
if err != nil {
return err
}
_, err = accountsDB.GetWalletAddress()
if err != nil {
return err
}
err = b.closeAppDB()
if err != nil {
return err
}
return nil
}
func (b *GethStatusBackend) SaveAccountAndStartNodeWithKey(acc multiaccounts.Account, password string, settings settings.Settings, nodecfg *params.NodeConfig, subaccs []*accounts.Account, keyHex string) error {
err := b.SaveAccount(acc)
if err != nil {
return err
}
err = b.ensureAppDBOpened(acc, password)
if err != nil {
return err
}
err = b.saveAccountsAndSettings(settings, nodecfg, subaccs)
if err != nil {
return err
}
return b.StartNodeWithKey(acc, password, keyHex)
}
// StartNodeWithAccountAndInitialConfig is used after account and config was generated.
// In current setup account name and config is generated on the client side. Once/if it will be generated on
// status-go side this flow can be simplified.
func (b *GethStatusBackend) StartNodeWithAccountAndInitialConfig(
account multiaccounts.Account,
password string,
settings settings.Settings,
nodecfg *params.NodeConfig,
subaccs []*accounts.Account,
) error {
err := b.SaveAccount(account)
if err != nil {
return err
}
err = b.ensureAppDBOpened(account, password)
if err != nil {
return err
}
err = b.saveAccountsAndSettings(settings, nodecfg, subaccs)
if err != nil {
return err
}
return b.StartNodeWithAccount(account, password, nodecfg)
}
func (b *GethStatusBackend) saveAccountsAndSettings(settings settings.Settings, nodecfg *params.NodeConfig, subaccs []*accounts.Account) error {
b.mu.Lock()
defer b.mu.Unlock()
accdb, err := accounts.NewDB(b.appDB)
if err != nil {
return err
}
err = accdb.CreateSettings(settings, *nodecfg)
if err != nil {
return err
}