-
Notifications
You must be signed in to change notification settings - Fork 4
/
store.go
706 lines (592 loc) · 20.6 KB
/
store.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
package observer
import (
"context"
"database/sql"
"encoding/hex"
"fmt"
"strings"
"time"
"github.com/MixinNetwork/safe/apps/bitcoin"
"github.com/MixinNetwork/safe/apps/ethereum"
"github.com/MixinNetwork/safe/common"
"github.com/MixinNetwork/safe/keeper"
"github.com/MixinNetwork/safe/keeper/store"
"github.com/btcsuite/btcd/btcec/v2"
)
type Asset struct {
AssetId string
MixinId string
AssetKey string
Symbol string
Name string
Decimals uint32
Chain byte
CreatedAt time.Time
}
type Deposit struct {
TransactionHash string
OutputIndex int64
AssetId string
AssetAddress string
Amount string
Receiver string
Sender string
State int
Chain byte
Holder string
Category byte
CreatedAt time.Time
UpdatedAt time.Time
}
type Transaction struct {
TransactionHash string
RawTransaction string
Chain byte
Holder string
Signer string
State byte
SpentHash sql.NullString
SpentRaw sql.NullString
CreatedAt time.Time
UpdatedAt time.Time
}
type Output struct {
TransactionHash string
Index uint32
Address string
Satoshi int64
Chain byte
State byte
SpentBy sql.NullString
RawTransaction sql.NullString
CreatedAt time.Time
UpdatedAt time.Time
}
type Recovery struct {
Address string
Chain byte
Holder string
Observer string
RawTransaction string
TransactionHash string
State int
CreatedAt time.Time
UpdatedAt time.Time
}
var assetCols = []string{"asset_id", "mixin_id", "asset_key", "symbol", "name", "decimals", "chain", "created_at"}
var depositsCols = []string{"transaction_hash", "output_index", "asset_id", "asset_address", "amount", "receiver", "sender", "state", "chain", "holder", "category", "created_at", "updated_at"}
func (d *Deposit) values() []any {
return []any{d.TransactionHash, d.OutputIndex, d.AssetId, d.AssetAddress, d.Amount, d.Receiver, d.Sender, d.State, d.Chain, d.Holder, d.Category, d.CreatedAt, d.UpdatedAt}
}
var transactionCols = []string{"transaction_hash", "raw_transaction", "chain", "holder", "signer", "state", "spent_hash", "spent_raw", "created_at", "updated_at"}
func (t *Transaction) values() []any {
return []any{t.TransactionHash, t.RawTransaction, t.Chain, t.Holder, t.Signer, t.State, t.SpentHash, t.SpentRaw, t.CreatedAt, t.UpdatedAt}
}
var outputCols = []string{"transaction_hash", "output_index", "address", "satoshi", "chain", "state", "spent_by", "raw_transaction", "created_at", "updated_at"}
func (o *Output) values() []any {
return []any{o.TransactionHash, o.Index, o.Address, o.Satoshi, o.Chain, o.State, o.SpentBy, o.RawTransaction, o.CreatedAt, o.UpdatedAt}
}
var recoveryCols = []string{"address", "chain", "holder", "observer", "raw_transaction", "transaction_hash", "state", "created_at", "updated_at"}
func (r *Recovery) values() []any {
return []any{r.Address, r.Chain, r.Holder, r.Observer, r.RawTransaction, r.TransactionHash, r.State, r.CreatedAt, r.UpdatedAt}
}
func (r *Recovery) getState() string {
switch r.State {
case common.RequestStateInitial:
return "initial"
case common.RequestStatePending:
return "pending"
case common.RequestStateDone:
return "done"
case common.RequestStateFailed:
return "failed"
}
panic(r.State)
}
func (t *Transaction) Signers(ctx context.Context, node *Node, safe *store.Safe) []string {
signers := make([]string, 0)
if t.State == common.RequestStateFailed {
return signers
}
opk, spk := safe.Observer, safe.Signer
switch safe.Chain {
case keeper.SafeChainBitcoin, keeper.SafeChainLitecoin:
var err error
opk, err = node.deriveBIP32WithKeeperPath(ctx, safe.Observer, safe.Path)
if err != nil {
panic(err)
}
spk, err = node.deriveBIP32WithKeeperPath(ctx, t.Signer, safe.Path)
if err != nil {
panic(err)
}
}
pubs := []string{t.Holder, spk, opk}
for idx, pub := range pubs {
isSigned := false
switch safe.Chain {
case keeper.SafeChainBitcoin, keeper.SafeChainLitecoin:
isSigned = bitcoin.CheckTransactionPartiallySignedBy(t.RawTransaction, pub)
case keeper.SafeChainMVM, keeper.SafeChainPolygon:
isSigned = ethereum.CheckTransactionPartiallySignedBy(t.RawTransaction, pub)
default:
panic(safe.Chain)
}
if isSigned {
switch idx {
case 0:
signers = append(signers, "holder")
case 1:
signers = append(signers, "signer")
case 2:
signers = append(signers, "observer")
}
}
}
return signers
}
func (s *SQLite3Store) WriteAccountProposalIfNotExists(ctx context.Context, address string, createdAt time.Time) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
existed, err := s.checkExistence(ctx, tx, "SELECT created_at FROM accounts WHERE address=?", address)
if err != nil || existed {
return err
}
err = s.execOne(ctx, tx, buildInsertionSQL("accounts", []string{"address", "created_at"}), address, createdAt)
if err != nil {
return fmt.Errorf("INSERT accounts %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) CheckAccountProposed(ctx context.Context, addr string) (bool, error) {
rows, err := s.db.QueryContext(ctx, "SELECT created_at FROM accounts WHERE address=?", addr)
if err != nil {
return false, err
}
defer rows.Close()
return rows.Next(), nil
}
func (s *SQLite3Store) ListDeposits(ctx context.Context, chain int, holder string, state int, offset int64) ([]*Deposit, error) {
query := fmt.Sprintf("SELECT %s FROM deposits WHERE chain=? AND state=? AND updated_at>=? ORDER BY created_at ASC LIMIT 100", strings.Join(depositsCols, ","))
params := []any{chain, state, time.Unix(0, offset)}
if holder != "" {
query = fmt.Sprintf("SELECT %s FROM deposits WHERE holder=? AND chain=? AND state=? AND updated_at>=? ORDER BY created_at ASC LIMIT 100", strings.Join(depositsCols, ","))
params = []any{holder, chain, state, time.Unix(0, offset)}
}
rows, err := s.db.QueryContext(ctx, query, params...)
if err != nil {
return nil, err
}
defer rows.Close()
var deposits []*Deposit
for rows.Next() {
var d Deposit
err := rows.Scan(&d.TransactionHash, &d.OutputIndex, &d.AssetId, &d.AssetAddress, &d.Amount, &d.Receiver, &d.Sender, &d.State, &d.Chain, &d.Holder, &d.Category, &d.CreatedAt, &d.UpdatedAt)
if err != nil {
return nil, err
}
deposits = append(deposits, &d)
}
return deposits, nil
}
func (s *SQLite3Store) QueryDepositSentHashes(ctx context.Context, deposits []*Deposit) (map[string]string, error) {
sent := make(map[string]string)
for _, d := range deposits {
query := "SELECT transaction_hash FROM transactions WHERE spent_hash=?"
row := s.db.QueryRowContext(ctx, query, d.TransactionHash)
var hash string
err := row.Scan(&hash)
if err == sql.ErrNoRows {
continue
} else if err != nil {
return nil, err
}
sent[d.TransactionHash] = hash
}
return sent, nil
}
func (s *SQLite3Store) WritePendingDepositIfNotExists(ctx context.Context, d *Deposit) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if d.State != common.RequestStateInitial {
panic(d.State)
}
existed, err := s.checkExistence(ctx, tx, "SELECT amount FROM deposits WHERE transaction_hash=? AND output_index=?", d.TransactionHash, d.OutputIndex)
if err != nil || existed {
return err
}
err = s.execOne(ctx, tx, buildInsertionSQL("deposits", depositsCols), d.values()...)
if err != nil {
return fmt.Errorf("INSERT deposits %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) ConfirmPendingDeposit(ctx context.Context, transactionHash string, outputIndex int64) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
query := "UPDATE deposits SET state=?, updated_at=? WHERE transaction_hash=? AND output_index=? AND state=?"
err = s.execOne(ctx, tx, query, common.RequestStateDone, time.Now().UTC(), transactionHash, outputIndex, common.RequestStateInitial)
if err != nil {
return fmt.Errorf("UPDATE deposits %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) ConfirmFullySignedTransactionApproval(ctx context.Context, hash, spentHash, spentRaw string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
query := "UPDATE transactions SET spent_hash=?, spent_raw=?, updated_at=? WHERE transaction_hash=? AND state=? AND spent_hash IS NULL"
err = s.execOne(ctx, tx, query, spentHash, spentRaw, time.Now().UTC(), hash, common.RequestStateDone)
if err != nil {
return fmt.Errorf("UPDATE transactions %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) RefundFullySignedTransactionApproval(ctx context.Context, hash string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
query := "UPDATE transactions SET state=?, updated_at=? WHERE transaction_hash=? AND state=? AND spent_hash IS NULL"
err = s.execOne(ctx, tx, query, common.RequestStateFailed, time.Now().UTC(), hash, common.RequestStateDone)
if err != nil {
return fmt.Errorf("UPDATE transactions %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) ListFullySignedTransactionApprovals(ctx context.Context, chain byte) ([]*Transaction, error) {
query := fmt.Sprintf("SELECT %s FROM transactions WHERE chain=? AND state=? AND spent_hash IS NULL ORDER BY created_at ASC", strings.Join(transactionCols, ","))
rows, err := s.db.QueryContext(ctx, query, chain, common.RequestStateDone)
if err != nil {
return nil, err
}
defer rows.Close()
var approvals []*Transaction
for rows.Next() {
var t Transaction
err = rows.Scan(&t.TransactionHash, &t.RawTransaction, &t.Chain, &t.Holder, &t.Signer, &t.State, &t.SpentHash, &t.SpentRaw, &t.CreatedAt, &t.UpdatedAt)
if err != nil {
return nil, err
}
approvals = append(approvals, &t)
}
return approvals, nil
}
func (s *SQLite3Store) ListPendingTransactionApprovals(ctx context.Context, chain byte) ([]*Transaction, error) {
query := fmt.Sprintf("SELECT %s FROM transactions WHERE chain=? AND state=? ORDER BY created_at ASC", strings.Join(transactionCols, ","))
rows, err := s.db.QueryContext(ctx, query, chain, common.RequestStatePending)
if err != nil {
return nil, err
}
defer rows.Close()
var approvals []*Transaction
for rows.Next() {
var t Transaction
err = rows.Scan(&t.TransactionHash, &t.RawTransaction, &t.Chain, &t.Holder, &t.Signer, &t.State, &t.SpentHash, &t.SpentRaw, &t.CreatedAt, &t.UpdatedAt)
if err != nil {
return nil, err
}
approvals = append(approvals, &t)
}
return approvals, nil
}
func (s *SQLite3Store) CountUnfinishedTransactionApprovalsForHolder(ctx context.Context, holder string) (int, error) {
query := "SELECT COUNT(*) FROM transactions WHERE holder=? AND state IN (?, ?) ORDER BY created_at ASC"
row := s.db.QueryRowContext(ctx, query, holder, common.RequestStateInitial, common.RequestStatePending)
var count int
err := row.Scan(&count)
if err == sql.ErrNoRows {
return 0, nil
}
return count, err
}
func (s *SQLite3Store) WriteTransactionApprovalIfNotExists(ctx context.Context, approval *Transaction) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
existed, err := s.checkExistence(ctx, tx, "SELECT raw_transaction FROM transactions WHERE transaction_hash=?", approval.TransactionHash)
if err != nil || existed {
return err
}
err = s.execOne(ctx, tx, buildInsertionSQL("transactions", transactionCols), approval.values()...)
if err != nil {
return fmt.Errorf("INSERT transactions %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) RevokeTransactionApproval(ctx context.Context, transactionHash string, sigBase64 string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
err = s.execOne(ctx, tx, "UPDATE transactions SET raw_transaction=?, state=?, updated_at=? WHERE transaction_hash=? AND state=?",
sigBase64, common.RequestStateFailed, time.Now().UTC(), transactionHash, common.RequestStateInitial)
if err != nil {
return fmt.Errorf("UPDATE transactions %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) AddTransactionPartials(ctx context.Context, transactionHash string, raw string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
err = s.execOne(ctx, tx, "UPDATE transactions SET raw_transaction=?, updated_at=? WHERE transaction_hash=? AND state=?",
raw, time.Now().UTC(), transactionHash, common.RequestStateInitial)
if err != nil {
return fmt.Errorf("UPDATE transactions %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) MarkTransactionApprovalPaid(ctx context.Context, transactionHash string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
err = s.execOne(ctx, tx, "UPDATE transactions SET state=?, updated_at=? WHERE transaction_hash=? AND state=?",
common.RequestStatePending, time.Now().UTC(), transactionHash, common.RequestStateInitial)
if err != nil {
return fmt.Errorf("UPDATE transactions %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) UpdateTransactionApprovalRequestTime(ctx context.Context, transactionHash string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
err = s.execOne(ctx, tx, "UPDATE transactions SET updated_at=? WHERE transaction_hash=? AND state=?",
time.Now().UTC(), transactionHash, common.RequestStatePending)
if err != nil {
return fmt.Errorf("UPDATE transactions %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) FinishTransactionSignatures(ctx context.Context, transactionHash string, raw string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
err = s.execOne(ctx, tx, "UPDATE transactions SET raw_transaction=?, state=?, updated_at=? WHERE transaction_hash=?",
raw, common.RequestStateDone, time.Now().UTC(), transactionHash)
if err != nil {
return fmt.Errorf("UPDATE transactions %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) ReadTransactionApproval(ctx context.Context, hash string) (*Transaction, error) {
query := fmt.Sprintf("SELECT %s FROM transactions WHERE transaction_hash=? OR spent_hash=?", strings.Join(transactionCols, ","))
row := s.db.QueryRowContext(ctx, query, hash, hash)
var t Transaction
err := row.Scan(&t.TransactionHash, &t.RawTransaction, &t.Chain, &t.Holder, &t.Signer, &t.State, &t.SpentHash, &t.SpentRaw, &t.CreatedAt, &t.UpdatedAt)
if err == sql.ErrNoRows {
return nil, nil
}
return &t, err
}
func (s *SQLite3Store) WriteAccountantKeys(ctx context.Context, crv byte, keys map[string]*btcec.PrivateKey) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
for addr, priv := range keys {
pub := hex.EncodeToString(priv.PubKey().SerializeCompressed())
cols := []string{"public_key", "private_key", "address", "curve", "created_at"}
vals := []any{pub, hex.EncodeToString(priv.Serialize()), addr, crv, time.Now().UTC()}
err = s.execOne(ctx, tx, buildInsertionSQL("accountants", cols), vals...)
if err != nil {
return fmt.Errorf("INSERT accountants %v", err)
}
}
return tx.Commit()
}
func (s *SQLite3Store) ReadAccountantPrivateKey(ctx context.Context, address string) (string, error) {
query := "SELECT private_key FROM accountants WHERE address=?"
row := s.db.QueryRowContext(ctx, query, address)
var key string
err := row.Scan(&key)
if err == sql.ErrNoRows {
return "", nil
}
return key, err
}
func (s *SQLite3Store) WriteObserverKeys(ctx context.Context, crv byte, publics map[string]string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
for pub, code := range publics {
cols := []string{"public_key", "curve", "chain_code", "created_at"}
vals := []any{pub, crv, code, time.Now().UTC()}
err = s.execOne(ctx, tx, buildInsertionSQL("observers", cols), vals...)
if err != nil {
return fmt.Errorf("INSERT observers %v", err)
}
}
return tx.Commit()
}
func (s *SQLite3Store) ReadObserverKey(ctx context.Context, crv byte) (string, []byte, error) {
var public, chainCode string
row := s.db.QueryRowContext(ctx, "SELECT public_key,chain_code FROM observers WHERE curve=? LIMIT 1", crv)
err := row.Scan(&public, &chainCode)
if err == sql.ErrNoRows {
return "", nil, nil
}
return public, common.DecodeHexOrPanic(chainCode), err
}
func (s *SQLite3Store) DeleteObserverKey(ctx context.Context, pub string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
err = s.execOne(ctx, tx, "DELETE FROM observers WHERE public_key=?", pub)
if err != nil {
return fmt.Errorf("DELETE observers %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) ReadAssetMeta(ctx context.Context, id string) (*Asset, error) {
query := fmt.Sprintf("SELECT %s FROM assets WHERE asset_id=? OR mixin_id=?", strings.Join(assetCols, ","))
row := s.db.QueryRowContext(ctx, query, id, id)
var a Asset
err := row.Scan(&a.AssetId, &a.MixinId, &a.AssetKey, &a.Symbol, &a.Name, &a.Decimals, &a.Chain, &a.CreatedAt)
if err == sql.ErrNoRows {
return nil, nil
}
return &a, err
}
func (s *SQLite3Store) WriteAssetMeta(ctx context.Context, asset *Asset) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
vals := []any{asset.AssetId, asset.MixinId, asset.AssetKey, asset.Symbol, asset.Name, asset.Decimals, asset.Chain, asset.CreatedAt}
err = s.execOne(ctx, tx, buildInsertionSQL("assets", assetCols), vals...)
if err != nil {
return fmt.Errorf("INSERT assets %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) WriteInitialRecovery(ctx context.Context, recovery *Recovery) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
vals := recovery.values()
err = s.execOne(ctx, tx, buildInsertionSQL("recoveries", recoveryCols), vals...)
if err != nil {
return fmt.Errorf("INSERT recoveries %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) UpdateRecoveryState(ctx context.Context, address, raw string, state int) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
existed, err := s.checkExistence(ctx, tx, "SELECT state FROM recoveries WHERE address=?", address)
if err != nil || !existed {
return err
}
switch state {
case common.RequestStatePending:
err = s.execOne(ctx, tx, "UPDATE recoveries SET state=?, raw_transaction=?, updated_at=? WHERE address=? AND state=?",
state, raw, time.Now().UTC(), address, common.RequestStateInitial)
case common.RequestStateDone:
err = s.execOne(ctx, tx, "UPDATE recoveries SET state=?, raw_transaction=?, updated_at=? WHERE address=? AND state IN (?, ?)",
state, raw, time.Now().UTC(), address, common.RequestStateInitial, common.RequestStatePending)
default:
panic(state)
}
if err != nil {
return fmt.Errorf("UPDATE recoveries %v", err)
}
return tx.Commit()
}
func (s *SQLite3Store) ReadRecovery(ctx context.Context, address string) (*Recovery, error) {
query := fmt.Sprintf("SELECT %s FROM recoveries WHERE address=?", strings.Join(recoveryCols, ","))
row := s.db.QueryRowContext(ctx, query, address)
var r Recovery
err := row.Scan(&r.Address, &r.Chain, &r.Holder, &r.Observer, &r.RawTransaction, &r.TransactionHash, &r.State, &r.CreatedAt, &r.UpdatedAt)
if err == sql.ErrNoRows {
return nil, nil
}
return &r, err
}
func (s *SQLite3Store) ListInitialRecoveries(ctx context.Context, offset int64) ([]*Recovery, error) {
query := fmt.Sprintf("SELECT %s FROM recoveries WHERE state=? AND created_at>=? ORDER BY created_at ASC LIMIT 100", strings.Join(recoveryCols, ","))
rows, err := s.db.QueryContext(ctx, query, common.RequestStateInitial, time.Unix(0, offset))
if err != nil {
return nil, err
}
defer rows.Close()
var recoveries []*Recovery
for rows.Next() {
var r Recovery
err = rows.Scan(&r.Address, &r.Chain, &r.Holder, &r.Observer, &r.RawTransaction, &r.TransactionHash, &r.State, &r.CreatedAt, &r.UpdatedAt)
if err != nil {
return nil, err
}
recoveries = append(recoveries, &r)
}
return recoveries, nil
}