-
Notifications
You must be signed in to change notification settings - Fork 244
/
database.go
513 lines (465 loc) · 14 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
package accounts
import (
"database/sql"
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/multiaccounts/errors"
"github.com/status-im/status-go/multiaccounts/keypairs"
"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"
"github.com/status-im/status-go/nodecfg"
"github.com/status-im/status-go/params"
)
const (
uniqueChatConstraint = "UNIQUE constraint failed: accounts.chat"
uniqueWalletConstraint = "UNIQUE constraint failed: accounts.wallet"
statusWalletRootPath = "m/44'/60'/0'/0/"
)
type Account struct {
Address types.Address `json:"address"`
KeyUID string `json:"key-uid"`
Wallet bool `json:"wallet"`
Chat bool `json:"chat"`
Type AccountType `json:"type,omitempty"`
Storage string `json:"storage,omitempty"`
Path string `json:"path,omitempty"`
PublicKey types.HexBytes `json:"public-key,omitempty"`
Name string `json:"name"`
Emoji string `json:"emoji"`
Color string `json:"color"`
Hidden bool `json:"hidden"`
DerivedFrom string `json:"derived-from,omitempty"`
Clock uint64 `json:"clock,omitempty"`
Removed bool `json:"removed,omitempty"`
KeypairName string `json:"keypair-name"`
LastUsedDerivationIndex uint64 `json:"last-used-derivation-index"`
}
type AccountType string
func (a AccountType) String() string {
return string(a)
}
const (
AccountTypeGenerated AccountType = "generated"
AccountTypeKey AccountType = "key"
AccountTypeSeed AccountType = "seed"
AccountTypeWatch AccountType = "watch"
)
// IsOwnAccount returns true if this is an account we have the private key for
// NOTE: Wallet flag can't be used as it actually indicates that it's the default
// Wallet
func (a *Account) IsOwnAccount() bool {
return a.Wallet || a.Type == AccountTypeSeed || a.Type == AccountTypeGenerated || a.Type == AccountTypeKey
}
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,omitempty"`
Storage string `json:"storage,omitempty"`
Path string `json:"path,omitempty"`
PublicKey types.HexBytes `json:"public-key,omitempty"`
Name string `json:"name"`
Emoji string `json:"emoji"`
Color string `json:"color"`
Hidden bool `json:"hidden"`
DerivedFrom string `json:"derived-from,omitempty"`
Clock uint64 `json:"clock"`
Removed bool `json:"removed"`
KeypairName string `json:"keypair-name"`
LastUsedDerivationIndex uint64 `json:"last-used-derivation-index"`
}{
Address: a.Address,
MixedcaseAddress: a.Address.Hex(),
KeyUID: a.KeyUID,
Wallet: a.Wallet,
Chat: a.Chat,
Type: a.Type,
Storage: a.Storage,
Path: a.Path,
PublicKey: a.PublicKey,
Name: a.Name,
Emoji: a.Emoji,
Color: a.Color,
Hidden: a.Hidden,
DerivedFrom: a.DerivedFrom,
Clock: a.Clock,
Removed: a.Removed,
KeypairName: a.KeypairName,
LastUsedDerivationIndex: a.LastUsedDerivationIndex,
}
return json.Marshal(item)
}
// Database sql wrapper for operations with browser objects.
type Database struct {
*settings.Database
*notificationssettings.NotificationsSettings
*sociallinkssettings.SocialLinksSettings
*keypairs.KeyPairs
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)
kp := keypairs.NewKeyPairs(db)
err = updateKeypairNameAndLastDerivationIndexIfNeeded(db)
if err != nil {
return nil, err
}
return &Database{sDB, sn, ssl, kp, 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 updateKeypairNameAndLastUsedIndex(tx *sql.Tx, keyUID string, keypairName string, index uint64) (err error) {
if tx == nil {
return errors.ErrDbTransactionIsNil
}
_, err = tx.Exec(`
UPDATE
accounts
SET
keypair_name = ?,
last_used_derivation_index = ?
WHERE
key_uid = ?
AND
NOT chat`,
keypairName, index, keyUID)
return err
}
func updateKeypairNameAndLastDerivationIndexIfNeeded(db *sql.DB) error {
tx, err := db.Begin()
if err != nil {
return err
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
_ = tx.Rollback()
}()
var displayName string
err = tx.QueryRow("SELECT display_name FROM settings WHERE synthetic_id = 'id'").Scan(&displayName)
if err != nil && err != sql.ErrNoRows {
return err
}
if displayName == "" {
displayName = "Status"
}
var (
seedKeyPairIndex int
keyKeyPairIndex int
)
for {
// Except for the Status chat account, keypair must not be empty and it must be unique per keypair.
rows, err := tx.Query(`SELECT wallet, type, path, derived_from, key_uid FROM accounts WHERE keypair_name = "" AND NOT chat ORDER BY key_uid`)
if err != nil {
if err == sql.ErrNoRows {
return nil
}
return err
}
defer rows.Close()
var dbAccounts []*Account
for rows.Next() {
acc := &Account{}
err := rows.Scan(&acc.Wallet, &acc.Type, &acc.Path, &acc.DerivedFrom, &acc.KeyUID)
if err != nil {
return err
}
dbAccounts = append(dbAccounts, acc)
}
if err = rows.Err(); err != nil {
return err
}
resolveLastUsedIndex := func(keyUID string) uint64 {
lastUsedIndex := uint64(0)
for _, acc := range dbAccounts {
if acc.KeyUID == keyUID && strings.HasPrefix(acc.Path, statusWalletRootPath) {
index, err := strconv.ParseUint(acc.Path[len(statusWalletRootPath):], 0, 64)
if err != nil {
continue
}
if index > lastUsedIndex {
lastUsedIndex = index
}
}
}
return lastUsedIndex
}
if len(dbAccounts) > 0 {
acc := dbAccounts[0]
keypairName := displayName
if acc.Type == AccountTypeSeed {
seedKeyPairIndex++
keypairName = fmt.Sprintf(`Seed imported %d`, seedKeyPairIndex)
} else if acc.Type == AccountTypeKey {
keyKeyPairIndex++
keypairName = fmt.Sprintf(`Key imported %d`, keyKeyPairIndex)
}
err = updateKeypairNameAndLastUsedIndex(tx, acc.KeyUID, keypairName, resolveLastUsedIndex(acc.KeyUID))
if err != nil {
return err
}
} else {
return nil
}
}
}
func (db *Database) GetAccountsByKeyUID(keyUID string) ([]*Account, error) {
accounts, err := db.GetAccounts()
if err != nil {
return nil, err
}
filteredAccounts := make([]*Account, 0)
for _, account := range accounts {
if account.KeyUID == keyUID {
filteredAccounts = append(filteredAccounts, account)
}
}
return filteredAccounts, nil
}
func (db *Database) GetAccounts() ([]*Account, error) {
rows, err := db.db.Query(`
SELECT
address,
wallet,
chat,
type,
storage,
pubkey,
path,
name,
emoji,
color,
hidden,
derived_from,
clock,
key_uid,
keypair_name,
last_used_derivation_index
FROM
accounts
ORDER BY
created_at`)
if err != nil {
return nil, err
}
defer rows.Close()
accounts := []*Account{}
pubkey := []byte{}
for rows.Next() {
acc := &Account{}
err := rows.Scan(
&acc.Address, &acc.Wallet, &acc.Chat, &acc.Type, &acc.Storage, &pubkey, &acc.Path, &acc.Name, &acc.Emoji,
&acc.Color, &acc.Hidden, &acc.DerivedFrom, &acc.Clock, &acc.KeyUID, &acc.KeypairName, &acc.LastUsedDerivationIndex)
if err != nil {
return nil, err
}
if lth := len(pubkey); lth > 0 {
acc.PublicKey = make(types.HexBytes, lth)
copy(acc.PublicKey, pubkey)
}
accounts = append(accounts, acc)
}
return accounts, nil
}
func (db *Database) GetAccountByAddress(address types.Address) (rst *Account, err error) {
row := db.db.QueryRow(`
SELECT
address,
wallet,
chat,
type,
storage,
pubkey,
path,
name,
emoji,
color,
hidden,
derived_from,
clock,
key_uid,
keypair_name,
last_used_derivation_index
FROM
accounts
WHERE
address = ? COLLATE NOCASE`,
address)
acc := &Account{}
pubkey := []byte{}
err = row.Scan(
&acc.Address, &acc.Wallet, &acc.Chat, &acc.Type, &acc.Storage, &pubkey, &acc.Path, &acc.Name, &acc.Emoji,
&acc.Color, &acc.Hidden, &acc.DerivedFrom, &acc.Clock, &acc.KeyUID, &acc.KeypairName, &acc.LastUsedDerivationIndex)
if err != nil {
return nil, err
}
acc.PublicKey = pubkey
return acc, nil
}
func (db *Database) SaveAccounts(accounts []*Account) (err error) {
// Once mobile app introduces keypair we should check for the "KeypairName" and "DerivedFrom" field and return error
// if those fields are missing.
//
// Note:
// - Status chat account doesn't have "KeypairName" and "DerivedFrom" fields set
// - default Status wallet account has "KeypairName" and "DerivedFrom" fields set
// - accounts generated from the Status wallet master key have "KeypairName" and "DerivedFrom" fields set
// - accounts added importing private key don't have "DerivedFrom" (they have "KeypairName")
// - accounts added importing seed phrase or generated from already imported seed phrase have "KeypairName" and "DerivedFrom" fields set
// - watch only accounts don't have "KeypairName" and "DerivedFrom" fields set
var (
tx *sql.Tx
insert *sql.Stmt
delete *sql.Stmt
update *sql.Stmt
)
tx, err = db.db.Begin()
if err != nil {
return
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
_ = tx.Rollback()
}()
// NOTE(dshulyak) replace all record values using address (primary key)
// can't use `insert or replace` because of the additional constraints (wallet and chat)
insert, err = tx.Prepare("INSERT OR IGNORE INTO accounts (address, created_at, updated_at) VALUES (?, datetime('now'), datetime('now'))")
if err != nil {
return err
}
delete, err = tx.Prepare("DELETE FROM accounts WHERE address = ?")
update, err = tx.Prepare(`UPDATE accounts
SET
wallet = ?,
chat = ?,
type = ?,
storage = ?,
pubkey = ?,
path = ?,
name = ?,
emoji = ?,
color = ?,
hidden = ?,
derived_from = ?,
key_uid = ?,
updated_at = datetime('now'),
clock = ?,
keypair_name = ?,
last_used_derivation_index = ?
WHERE
address = ?`)
if err != nil {
return err
}
for i := range accounts {
acc := accounts[i]
if acc.Removed {
_, err = delete.Exec(acc.Address)
if err != nil {
return
}
continue
}
_, err = insert.Exec(acc.Address)
if err != nil {
return
}
_, err = update.Exec(acc.Wallet, acc.Chat, acc.Type, acc.Storage, acc.PublicKey, acc.Path, acc.Name, acc.Emoji, acc.Color,
acc.Hidden, acc.DerivedFrom, acc.KeyUID, acc.Clock, acc.KeypairName, acc.LastUsedDerivationIndex, acc.Address)
if err != nil {
switch err.Error() {
case uniqueChatConstraint:
err = errors.ErrChatNotUnique
case uniqueWalletConstraint:
err = errors.ErrWalletNotUnique
}
return
}
err = updateKeypairNameAndLastUsedIndex(tx, acc.KeyUID, acc.KeypairName, acc.LastUsedDerivationIndex)
if err != nil {
return
}
}
return
}
func (db *Database) DeleteAccount(address types.Address) error {
_, err := db.db.Exec("DELETE FROM accounts WHERE address = ?", address)
return err
}
func (db *Database) GetWalletAddress() (rst types.Address, err error) {
err = db.db.QueryRow("SELECT address FROM accounts WHERE wallet = 1").Scan(&rst)
return
}
func (db *Database) GetWalletAddresses() (rst []types.Address, err error) {
rows, err := db.db.Query("SELECT address FROM accounts WHERE chat = 0 ORDER BY created_at")
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
addr := types.Address{}
err = rows.Scan(&addr)
if err != nil {
return nil, err
}
rst = append(rst, addr)
}
return rst, nil
}
func (db *Database) GetChatAddress() (rst types.Address, err error) {
err = db.db.QueryRow("SELECT address FROM accounts WHERE chat = 1").Scan(&rst)
return
}
func (db *Database) GetAddresses() (rst []types.Address, err error) {
rows, err := db.db.Query("SELECT address FROM accounts ORDER BY created_at")
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
addr := types.Address{}
err = rows.Scan(&addr)
if err != nil {
return nil, err
}
rst = append(rst, addr)
}
return rst, nil
}
// AddressExists returns true if given address is stored in database.
func (db *Database) AddressExists(address types.Address) (exists bool, err error) {
err = db.db.QueryRow("SELECT EXISTS (SELECT 1 FROM accounts WHERE address = ?)", address).Scan(&exists)
return exists, err
}
// GetPath returns true if account with given address was recently key and doesn't have a key yet
func (db *Database) GetPath(address types.Address) (path string, err error) {
err = db.db.QueryRow("SELECT path FROM accounts WHERE address = ?", address).Scan(&path)
return path, err
}
func (db *Database) GetNodeConfig() (*params.NodeConfig, error) {
return nodecfg.GetNodeConfigFromDB(db.db)
}