-
Notifications
You must be signed in to change notification settings - Fork 28
/
boltdb.go
1497 lines (1364 loc) · 39.8 KB
/
boltdb.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
// Copyright (c) 2019-2021 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package pool
import (
"bytes"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"strconv"
"time"
bolt "go.etcd.io/bbolt"
errs "github.com/decred/dcrpool/errors"
)
var (
// poolBkt is the main bucket of mining pool, all other buckets
// are nested within it.
poolBkt = []byte("poolbkt")
// accountBkt stores all registered accounts for the mining pool.
accountBkt = []byte("accountbkt")
// shareBkt stores all client shares for the mining pool.
shareBkt = []byte("sharebkt")
// jobBkt stores jobs delivered to clients, it is periodically pruned by the
// current chain tip height.
jobBkt = []byte("jobbkt")
// workBkt stores work submissions from pool clients and confirmed mined
// work from the pool, it is periodically pruned by the current chain tip
// adjusted by the max reorg height and by chain reorgs.
workBkt = []byte("workbkt")
// paymentBkt stores all payments. Confirmed processed payments are
// archived periodically.
paymentBkt = []byte("paymentbkt")
// paymentArchiveBkt stores all processed payments for auditing purposes.
// Confirmed processed payments are sourced from the payment bucket and
// archived.
paymentArchiveBkt = []byte("paymentarchivebkt")
// hashDataBkt stores client identification and hashrate information.
hashDataBkt = []byte("hashdatabkt")
// versionK is the key of the current version of the database.
versionK = []byte("version")
// lastPaymentCreatedOn is the key of the last time a payment was
// persisted.
lastPaymentCreatedOn = []byte("lastpaymentcreatedon")
// lastPaymentPaidOn is the key of the last time a payment was
// paid.
lastPaymentPaidOn = []byte("lastpaymentpaidon")
// lastPaymentHeight is the key of the last payment height.
lastPaymentHeight = []byte("lastpaymentheight")
// soloPool is the solo pool mode key.
soloPool = []byte("solopool")
// csrfSecret is the CSRF secret key.
csrfSecret = []byte("csrfsecret")
// PoolFeesK is the key used to track pool fee payouts.
PoolFeesK = "fees"
// BoltBackupFile is the database backup file name.
BoltBackupFile = "backup.kv"
)
// openBoltDB creates a connection to the provided bolt storage, the returned
// connection storage should always be closed after use.
func openBoltDB(storage string) (*BoltDB, error) {
const funcName = "openBoltDB"
db, err := bolt.Open(storage, 0600,
&bolt.Options{Timeout: 1 * time.Second})
if err != nil {
desc := fmt.Sprintf("%s: unable to open db file: %v", funcName, err)
return nil, errs.DBError(errs.DBOpen, desc)
}
return &BoltDB{db}, nil
}
// createNestedBucket creates a nested child bucket of the provided parent.
func createNestedBucket(parent *bolt.Bucket, child []byte) error {
const funcName = "createNestedBucket"
_, err := parent.CreateBucketIfNotExists(child)
if err != nil {
desc := fmt.Sprintf("%s: unable to create %s bucket: %v",
funcName, string(child), err)
return errs.DBError(errs.CreateStorage, desc)
}
return nil
}
// createBuckets creates all storage buckets of the mining pool.
func createBuckets(db *BoltDB) error {
const funcName = "createBuckets"
err := db.DB.Update(func(tx *bolt.Tx) error {
var err error
pbkt := tx.Bucket(poolBkt)
if pbkt == nil {
pbkt, err = tx.CreateBucketIfNotExists(poolBkt)
if err != nil {
desc := fmt.Sprintf("%s: unable to create %s bucket: %v",
funcName, string(poolBkt), err)
return errs.DBError(errs.CreateStorage, desc)
}
vbytes := make([]byte, 4)
binary.LittleEndian.PutUint32(vbytes, BoltDBVersion)
err = pbkt.Put(versionK, vbytes)
if err != nil {
desc := fmt.Sprintf("%s: unable to persist version: %v",
funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
}
err = createNestedBucket(pbkt, accountBkt)
if err != nil {
return err
}
err = createNestedBucket(pbkt, shareBkt)
if err != nil {
return err
}
err = createNestedBucket(pbkt, workBkt)
if err != nil {
return err
}
err = createNestedBucket(pbkt, jobBkt)
if err != nil {
return err
}
err = createNestedBucket(pbkt, paymentBkt)
if err != nil {
return err
}
err = createNestedBucket(pbkt, paymentArchiveBkt)
if err != nil {
return err
}
return createNestedBucket(pbkt, hashDataBkt)
})
return err
}
// Backup saves a copy of the db to file. The file will be saved in the same
// directory as the current db file.
func (db *BoltDB) Backup(backupFileName string) error {
backupPath := filepath.Join(filepath.Dir(db.DB.Path()), backupFileName)
return db.DB.View(func(tx *bolt.Tx) error {
err := tx.CopyFile(backupPath, 0600)
if err != nil {
desc := fmt.Sprintf("unable to backup db: %v", err)
return errs.PoolError(errs.Backup, desc)
}
return nil
})
}
// InitBoltDB handles the creation and upgrading of a bolt database.
func InitBoltDB(dbFile string) (*BoltDB, error) {
db, err := openBoltDB(dbFile)
if err != nil {
return nil, err
}
err = createBuckets(db)
if err != nil {
return nil, err
}
err = upgradeDB(db)
if err != nil {
return nil, err
}
return db, nil
}
// deleteEntry removes the specified key and its associated value from
// the provided bucket.
func deleteEntry(db *BoltDB, bucket []byte, key string) error {
const funcName = "deleteEntry"
return db.DB.Update(func(tx *bolt.Tx) error {
pbkt := tx.Bucket(poolBkt)
if pbkt == nil {
desc := fmt.Sprintf("%s: bucket %s not found", funcName,
string(poolBkt))
return errs.DBError(errs.StorageNotFound, desc)
}
b := pbkt.Bucket(bucket)
err := b.Delete([]byte(key))
if err != nil {
desc := fmt.Sprintf("%s: unable to delete entry with "+
"key %s from bucket %s", funcName, key, string(poolBkt))
return errs.DBError(errs.DeleteEntry, desc)
}
return nil
})
}
// fetchBucket is a helper function for getting the requested bucket.
func fetchBucket(tx *bolt.Tx, bucketID []byte) (*bolt.Bucket, error) {
const funcName = "fetchBucket"
pbkt, err := fetchPoolBucket(tx)
if err != nil {
return nil, err
}
bkt := pbkt.Bucket(bucketID)
if bkt == nil {
desc := fmt.Sprintf("%s: bucket %s not found", funcName,
string(bucketID))
return nil, errs.DBError(errs.StorageNotFound, desc)
}
return bkt, nil
}
// fetchPoolBucket is a helper function for getting the pool bucket.
func fetchPoolBucket(tx *bolt.Tx) (*bolt.Bucket, error) {
funcName := "fetchPoolBucket"
pbkt := tx.Bucket(poolBkt)
if pbkt == nil {
desc := fmt.Sprintf("%s: bucket %s not found", funcName,
string(poolBkt))
return nil, errs.DBError(errs.StorageNotFound, desc)
}
return pbkt, nil
}
// bigEndianBytesToNano returns nanosecond time from the provided
// big endian bytes.
func bigEndianBytesToNano(b []byte) uint64 {
return binary.BigEndian.Uint64(b)
}
// nanoToBigEndianBytes returns an 8-byte big endian representation of
// the provided nanosecond time.
func nanoToBigEndianBytes(nano int64) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(nano))
return b
}
// fetchPoolMode retrives the pool mode from the database. PoolMode is stored as
// a uint32 for historical reasons. 0 indicates Public, 1 indicates Solo.
func (db *BoltDB) fetchPoolMode() (uint32, error) {
var mode uint32
err := db.DB.View(func(tx *bolt.Tx) error {
pbkt, err := fetchPoolBucket(tx)
if err != nil {
return err
}
b := pbkt.Get(soloPool)
if b == nil {
return errs.DBError(errs.ValueNotFound, "no pool mode found")
}
mode = binary.LittleEndian.Uint32(b)
return nil
})
if err != nil {
return 0, err
}
return mode, nil
}
// persistPoolMode stores the pool mode in the database. PoolMode is stored as a
// uint32 for historical reasons. 0 indicates Public, 1 indicates Solo.
func (db *BoltDB) persistPoolMode(mode uint32) error {
return db.DB.Update(func(tx *bolt.Tx) error {
pbkt := tx.Bucket(poolBkt)
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, mode)
return pbkt.Put(soloPool, b)
})
}
// fetchCSRFSecret retrieves the bytes used for the CSRF secret from the database.
func (db *BoltDB) fetchCSRFSecret() ([]byte, error) {
var secret []byte
err := db.DB.View(func(tx *bolt.Tx) error {
pbkt := tx.Bucket(poolBkt)
if pbkt == nil {
desc := fmt.Sprintf("bucket %s not found", string(poolBkt))
return errs.DBError(errs.StorageNotFound, desc)
}
v := pbkt.Get(csrfSecret)
if v == nil {
return errs.DBError(errs.ValueNotFound, "No csrf secret found")
}
// Make a copy of the secret to return after the db transaction is
// completed.
secret = make([]byte, len(v))
copy(secret, v)
return nil
})
if err != nil {
return nil, err
}
return secret, nil
}
// persistCSRFSecret stores the bytes used for the CSRF secret in the database.
func (db *BoltDB) persistCSRFSecret(secret []byte) error {
return db.DB.Update(func(tx *bolt.Tx) error {
pbkt := tx.Bucket(poolBkt)
if pbkt == nil {
desc := fmt.Sprintf("bucket %s not found", string(poolBkt))
return errs.DBError(errs.StorageNotFound, desc)
}
return pbkt.Put(csrfSecret, secret)
})
}
// persistLastPaymentInfo stores the last payment height and paidOn timestamp
// in the database.
func (db *BoltDB) persistLastPaymentInfo(height uint32, paidOn int64) error {
funcName := "persistLastPaymentInfo"
return db.DB.Update(func(tx *bolt.Tx) error {
pbkt, err := fetchPoolBucket(tx)
if err != nil {
return err
}
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, height)
err = pbkt.Put(lastPaymentHeight, b)
if err != nil {
desc := fmt.Sprintf("%s: unable to persist last payment height: %v",
funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
err = pbkt.Put(lastPaymentPaidOn, nanoToBigEndianBytes(paidOn))
if err != nil {
desc := fmt.Sprintf("%s: unable to persist last payment "+
"paid on time: %v", funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
return nil
})
}
// loadLastPaymentInfo retrieves the last payment height and paidOn timestamp
// from the database.
func (db *BoltDB) loadLastPaymentInfo() (uint32, int64, error) {
funcName := "loadLastPaymentInfo"
var height uint32
var paidOn int64
err := db.DB.View(func(tx *bolt.Tx) error {
pbkt, err := fetchPoolBucket(tx)
if err != nil {
return err
}
lastPaymentHeightB := pbkt.Get(lastPaymentHeight)
lastPaymentPaidOnB := pbkt.Get(lastPaymentPaidOn)
if lastPaymentHeightB == nil || lastPaymentPaidOnB == nil {
desc := fmt.Sprintf("%s: last payment info not initialized", funcName)
return errs.DBError(errs.ValueNotFound, desc)
}
height = binary.LittleEndian.Uint32(lastPaymentHeightB)
paidOn = int64(bigEndianBytesToNano(lastPaymentPaidOnB))
return nil
})
if err != nil {
return 0, 0, err
}
return height, paidOn, nil
}
// persistLastPaymentCreatedOn stores the last payment createdOn timestamp in
// the database.
func (db *BoltDB) persistLastPaymentCreatedOn(createdOn int64) error {
funcName := "persistLastPaymentCreatedOn"
return db.DB.Update(func(tx *bolt.Tx) error {
pbkt, err := fetchPoolBucket(tx)
if err != nil {
return err
}
err = pbkt.Put(lastPaymentCreatedOn, nanoToBigEndianBytes(createdOn))
if err != nil {
desc := fmt.Sprintf("%s: unable to persist last payment "+
"created-on time: %v", funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
return nil
})
}
// loadLastPaymentCreatedOn retrieves the last payment createdOn timestamp from
// the database.
func (db *BoltDB) loadLastPaymentCreatedOn() (int64, error) {
funcName := "loadLastPaymentCreatedOn"
var createdOn int64
err := db.DB.View(func(tx *bolt.Tx) error {
pbkt, err := fetchPoolBucket(tx)
if err != nil {
return err
}
lastPaymentCreatedOnB := pbkt.Get(lastPaymentCreatedOn)
if lastPaymentCreatedOnB == nil {
desc := fmt.Sprintf("%s: last payment created-on not initialized",
funcName)
return errs.DBError(errs.ValueNotFound, desc)
}
createdOn = int64(bigEndianBytesToNano(lastPaymentCreatedOnB))
return nil
})
if err != nil {
return 0, err
}
return createdOn, nil
}
// Close closes the Bolt database.
func (db *BoltDB) Close() error {
return db.DB.Close()
}
// purge wipes all persisted data. This is intended for use with testnet and
// simnet testing purposes only.
func (db *BoltDB) purge() error {
funcName := "purge"
return db.DB.Update(func(tx *bolt.Tx) error {
pbkt, err := fetchPoolBucket(tx)
if err != nil {
return err
}
// Delete all metadata.
err = pbkt.Delete(csrfSecret)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete csrf secret: %v",
funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
err = pbkt.Delete(soloPool)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete solo pool status: %v",
funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
err = pbkt.Delete(lastPaymentHeight)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete last payment "+
"height: %v", funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
err = pbkt.Delete(lastPaymentPaidOn)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete last payment "+
"paid on: %v", funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
err = pbkt.Delete(lastPaymentCreatedOn)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete last payment "+
"created on: %v", funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
err = pbkt.Delete(versionK)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete db "+
"version: %v", funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
// Delete all pool buckets.
err = pbkt.DeleteBucket(paymentArchiveBkt)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete payment archive "+
"bucket: %v", funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
err = pbkt.DeleteBucket(paymentBkt)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete payment bucket: %v",
funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
err = pbkt.DeleteBucket(workBkt)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete work bucket: %v",
funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
err = pbkt.DeleteBucket(jobBkt)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete job bucket: %v",
funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
err = pbkt.DeleteBucket(shareBkt)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete share bucket: %v",
funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
err = pbkt.DeleteBucket(accountBkt)
if err != nil {
desc := fmt.Sprintf("%s: unable to delete account bucket: %v",
funcName, err)
return errs.DBError(errs.DeleteEntry, desc)
}
return nil
})
}
// httpBackup streams a backup of the entire database over the provided HTTP
// response writer.
func (db *BoltDB) httpBackup(w http.ResponseWriter) error {
err := db.DB.View(func(tx *bolt.Tx) error {
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", `attachment; filename="backup.db"`)
w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
_, err := tx.WriteTo(w)
return err
})
return err
}
// fetchAcceptedWork fetches the accepted work referenced by the provided id.
func (db *BoltDB) fetchAcceptedWork(id string) (*AcceptedWork, error) {
const funcName = "fetchAcceptedWork"
var work AcceptedWork
err := db.DB.View(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, workBkt)
if err != nil {
return err
}
v := bkt.Get([]byte(id))
if v == nil {
desc := fmt.Sprintf("%s: no value for key %s", funcName, id)
return errs.DBError(errs.ValueNotFound, desc)
}
err = json.Unmarshal(v, &work)
if err != nil {
desc := fmt.Sprintf("%s: unable to unmarshal accepted work: %v",
funcName, err)
return errs.DBError(errs.Parse, desc)
}
return nil
})
if err != nil {
return nil, err
}
return &work, err
}
// persistAcceptedWork saves the accepted work to the database.
func (db *BoltDB) persistAcceptedWork(work *AcceptedWork) error {
const funcName = "persistAcceptedWork"
return db.DB.Update(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, workBkt)
if err != nil {
return err
}
// Do not persist already existing accepted work.
id := []byte(work.UUID)
v := bkt.Get(id)
if v != nil {
desc := fmt.Sprintf("%s: work %s already exists", funcName,
work.UUID)
return errs.DBError(errs.ValueFound, desc)
}
workBytes, err := json.Marshal(work)
if err != nil {
desc := fmt.Sprintf("%s: unable to marshal accepted "+
"work bytes: %v", funcName, err)
return errs.DBError(errs.Parse, desc)
}
err = bkt.Put(id, workBytes)
if err != nil {
desc := fmt.Sprintf("%s: unable to persist accepted work: %v",
funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
return nil
})
}
// updateAcceptedWork persists modifications to an existing work.
func (db *BoltDB) updateAcceptedWork(work *AcceptedWork) error {
const funcName = "updateAcceptedWork"
return db.DB.Update(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, workBkt)
if err != nil {
return err
}
// Assert the work provided exists before updating.
id := []byte(work.UUID)
v := bkt.Get(id)
if v == nil {
desc := fmt.Sprintf("%s: work %s not found", funcName, work.UUID)
return errs.DBError(errs.ValueNotFound, desc)
}
workBytes, err := json.Marshal(work)
if err != nil {
desc := fmt.Sprintf("%s: unable to marshal accepted "+
"work bytes: %v", funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
err = bkt.Put(id, workBytes)
if err != nil {
desc := fmt.Sprintf("%s: unable to persist accepted work: %v",
funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
return nil
})
}
// deleteAcceptedWork removes the associated accepted work from the database.
func (db *BoltDB) deleteAcceptedWork(id string) error {
return deleteEntry(db, workBkt, id)
}
// listMinedWork returns work data associated with all blocks mined by the pool
// regardless of whether they are confirmed or not.
//
// List is ordered, most recent comes first.
func (db *BoltDB) listMinedWork() ([]*AcceptedWork, error) {
const funcName = "listMinedWork"
minedWork := make([]*AcceptedWork, 0)
err := db.DB.View(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, workBkt)
if err != nil {
return err
}
cursor := bkt.Cursor()
for k, v := cursor.Last(); k != nil; k, v = cursor.Prev() {
var work AcceptedWork
err := json.Unmarshal(v, &work)
if err != nil {
desc := fmt.Sprintf("%s: unable to unmarshal accepted "+
"work: %v", funcName, err)
return errs.PoolError(errs.Parse, desc)
}
minedWork = append(minedWork, &work)
}
return nil
})
if err != nil {
return nil, err
}
return minedWork, nil
}
// fetchUnconfirmedWork returns all work which is not confirmed as mined with
// height less than the provided height.
func (db *BoltDB) fetchUnconfirmedWork(height uint32) ([]*AcceptedWork, error) {
toReturn := make([]*AcceptedWork, 0)
err := db.DB.View(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, workBkt)
if err != nil {
return err
}
heightBE := heightToBigEndianBytes(height)
cursor := bkt.Cursor()
for k, v := cursor.First(); k != nil; k, v = cursor.Next() {
heightB, err := hex.DecodeString(string(k[:8]))
if err != nil {
return err
}
if bytes.Compare(heightBE, heightB) > 0 {
var work AcceptedWork
err := json.Unmarshal(v, &work)
if err != nil {
return err
}
if !work.Confirmed {
toReturn = append(toReturn, &work)
}
}
}
return nil
})
if err != nil {
return nil, err
}
return toReturn, nil
}
// fetchAccount fetches the account referenced by the provided id.
func (db *BoltDB) fetchAccount(id string) (*Account, error) {
const funcName = "fetchAccount"
var account Account
err := db.DB.View(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, accountBkt)
if err != nil {
return err
}
v := bkt.Get([]byte(id))
if v == nil {
desc := fmt.Sprintf("%s: no account found for id %s", funcName, id)
return errs.DBError(errs.ValueNotFound, desc)
}
err = json.Unmarshal(v, &account)
if err != nil {
desc := fmt.Sprintf("%s: unable to unmarshal account: %v",
funcName, err)
return errs.DBError(errs.Parse, desc)
}
return nil
})
if err != nil {
return nil, err
}
return &account, err
}
// persistAccount saves the account to the database. Before persisting the
// account, it sets the createdOn timestamp.
func (db *BoltDB) persistAccount(acc *Account) error {
const funcName = "persistAccount"
return db.DB.Update(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, accountBkt)
if err != nil {
return err
}
// Do not persist already existing account.
if bkt.Get([]byte(acc.UUID)) != nil {
desc := fmt.Sprintf("%s: account %s already exists", funcName,
acc.UUID)
return errs.DBError(errs.ValueFound, desc)
}
acc.CreatedOn = uint64(time.Now().Unix())
accBytes, err := json.Marshal(acc)
if err != nil {
desc := fmt.Sprintf("%s: unable to marshal account bytes: %v",
funcName, err)
return errs.DBError(errs.Parse, desc)
}
err = bkt.Put([]byte(acc.UUID), accBytes)
if err != nil {
desc := fmt.Sprintf("%s: unable to persist account entry: %v",
funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
return nil
})
}
// deleteAccount purges the referenced account from the database.
func (db *BoltDB) deleteAccount(id string) error {
return deleteEntry(db, accountBkt, id)
}
// fetchJob fetches the job referenced by the provided id.
func (db *BoltDB) fetchJob(id string) (*Job, error) {
const funcName = "fetchJob"
var job Job
err := db.DB.View(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, jobBkt)
if err != nil {
return err
}
v := bkt.Get([]byte(id))
if v == nil {
desc := fmt.Sprintf("%s: no job found for id %s", funcName, id)
return errs.DBError(errs.ValueNotFound, desc)
}
err = json.Unmarshal(v, &job)
if err != nil {
desc := fmt.Sprintf("%s: unable to unmarshal job bytes: %v",
funcName, err)
return errs.DBError(errs.Parse, desc)
}
return nil
})
if err != nil {
return nil, err
}
return &job, err
}
// persistJob saves the job to the database.
func (db *BoltDB) persistJob(job *Job) error {
const funcName = "persistJob"
return db.DB.Update(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, jobBkt)
if err != nil {
return err
}
// Do not persist already existing job.
if bkt.Get([]byte(job.UUID)) != nil {
desc := fmt.Sprintf("%s: job %s already exists", funcName,
job.UUID)
return errs.DBError(errs.ValueFound, desc)
}
jobBytes, err := json.Marshal(job)
if err != nil {
desc := fmt.Sprintf("%s: unable to marshal job bytes: %v",
funcName, err)
return errs.DBError(errs.Parse, desc)
}
err = bkt.Put([]byte(job.UUID), jobBytes)
if err != nil {
desc := fmt.Sprintf("%s: unable to persist job entry: %v",
funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
return nil
})
}
// deleteJob removes the associated job from the database.
func (db *BoltDB) deleteJob(id string) error {
return deleteEntry(db, jobBkt, id)
}
// deleteJobsBeforeHeight removes all jobs with heights less than the provided
// height.
func (db *BoltDB) deleteJobsBeforeHeight(height uint32) error {
return db.DB.Update(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, jobBkt)
if err != nil {
return err
}
heightBE := heightToBigEndianBytes(height)
toDelete := [][]byte{}
c := bkt.Cursor()
for k, _ := c.First(); k != nil; k, _ = c.Next() {
heightB, err := hex.DecodeString(string(k[:8]))
if err != nil {
return err
}
if bytes.Compare(heightB, heightBE) < 0 {
toDelete = append(toDelete, k)
}
}
for _, entry := range toDelete {
err := bkt.Delete(entry)
if err != nil {
return err
}
}
return nil
})
}
// fetchPayment fetches the payment referenced by the provided id.
func (db *BoltDB) fetchPayment(id string) (*Payment, error) {
const funcName = "fetchPayment"
var payment Payment
err := db.DB.View(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, paymentBkt)
if err != nil {
return err
}
v := bkt.Get([]byte(id))
if v == nil {
desc := fmt.Sprintf("%s: no payment found for id %s", funcName, id)
return errs.DBError(errs.ValueNotFound, desc)
}
err = json.Unmarshal(v, &payment)
if err != nil {
desc := fmt.Sprintf("%s: unable to unmarshal payment: %v",
funcName, err)
return errs.DBError(errs.Parse, desc)
}
return nil
})
if err != nil {
return nil, err
}
return &payment, err
}
// PersistPayment saves a payment to the database.
func (db *BoltDB) PersistPayment(pmt *Payment) error {
const funcName = "PersistPayment"
return db.DB.Update(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, paymentBkt)
if err != nil {
return err
}
b, err := json.Marshal(pmt)
if err != nil {
desc := fmt.Sprintf("%s: unable to marshal payment bytes: %v",
funcName, err)
return errs.DBError(errs.Parse, desc)
}
err = bkt.Put([]byte(pmt.UUID), b)
if err != nil {
desc := fmt.Sprintf("%s: unable to persist payment bytes: %v",
funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
return nil
})
}
// updatePayment persists the updated payment to the database.
func (db *BoltDB) updatePayment(pmt *Payment) error {
return db.PersistPayment(pmt)
}
// deletePayment purges the referenced active payment from the database.
// Note that archived payments cannot be deleted.
func (db *BoltDB) deletePayment(id string) error {
return deleteEntry(db, paymentBkt, id)
}
// ArchivePayment removes the associated payment from active payments
// and archives it.
func (db *BoltDB) ArchivePayment(pmt *Payment) error {
const funcName = "ArchivePayment"
return db.DB.Update(func(tx *bolt.Tx) error {
pbkt, err := fetchBucket(tx, paymentBkt)
if err != nil {
return err
}
abkt, err := fetchBucket(tx, paymentArchiveBkt)
if err != nil {
return err
}
// Remove the active payment record.
err = pbkt.Delete([]byte(pmt.UUID))
if err != nil {
return err
}
// Create a new payment to add to the archive.
aPmt := NewPayment(pmt.Account, pmt.Source, pmt.Amount, pmt.Height,
pmt.EstimatedMaturity)
aPmt.TransactionID = pmt.TransactionID
aPmt.PaidOnHeight = pmt.PaidOnHeight
aPmtB, err := json.Marshal(aPmt)
if err != nil {
desc := fmt.Sprintf("%s: unable to marshal payment bytes: %v",
funcName, err)
return errs.DBError(errs.Parse, desc)
}
err = abkt.Put([]byte(aPmt.UUID), aPmtB)
if err != nil {
desc := fmt.Sprintf("%s: unable to archive payment entry: %v",
funcName, err)
return errs.DBError(errs.PersistEntry, desc)
}
return nil
})
}
// fetchPaymentsAtHeight returns all payments sourcing from orphaned blocks at
// the provided height.
func (db *BoltDB) fetchPaymentsAtHeight(height uint32) ([]*Payment, error) {
toReturn := make([]*Payment, 0)
err := db.DB.Update(func(tx *bolt.Tx) error {
bkt, err := fetchBucket(tx, paymentBkt)
if err != nil {
return err
}
cursor := bkt.Cursor()
for k, v := cursor.First(); k != nil; k, v = cursor.Next() {
var payment Payment
err := json.Unmarshal(v, &payment)
if err != nil {
return err
}