forked from decred/dcrwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
1315 lines (1065 loc) · 37.8 KB
/
db.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) 2015 Conformal Systems LLC <info@conformal.com>
* Copyright (c) 2015 The Decred developers
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package wstakemgr
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"time"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrutil"
"github.com/decred/dcrwallet/walletdb"
)
const (
// LatestStakeMgrVersion is the most recent tx store version.
LatestStakeMgrVersion = 1
// Size of various types in bytes.
boolSize = 1
int8Size = 1
int16Size = 2
int32Size = 4
int64Size = 8
hashSize = 32
// Size of a serialized ssgenRecord.
// hash + uint32 + hash + uint16 + uint64
ssgenRecordSize = 32 + 4 + 32 + 2 + 8
// Size of a serialized ssrtxRecord.
// hash + uint32 + hash + uint64
ssrtxRecordSize = 32 + 4 + 32 + 8
// stakePoolUserTicketSize is the size
// of a serialized stake pool user
// ticket.
// hash + uint32 + uint8 + uint32 + hash
stakePoolUserTicketSize = 32 + 4 + 1 + 4 + 32
// stakePoolTicketsPrefixSize is the length of
// stakePoolTicketsPrefix.
stakePoolTicketsPrefixSize = 5
// stakePoolInvalidPrefixSize is the length of
// stakePoolInvalidPrefix.
stakePoolInvalidPrefixSize = 5
// scriptHashLen is the length of a HASH160
// hash.
scriptHashSize = 20
)
var (
// sstxTicket2PKHPrefix is the PkScript byte prefix for an SStx
// P2PKH ticket output. The entire prefix is 0xba76a914, but we
// only use the first 3 bytes.
sstxTicket2PKHPrefix = []byte{0xba, 0x76, 0xa9}
// sstxTicket2SHPrefix is the PkScript byte prefix for an SStx
// P2SH ticket output.
sstxTicket2SHPrefix = []byte{0xba, 0xa9, 0x14}
// stakePoolTicketsPrefix is the byte slice prefix for valid
// tickets in the stake pool for a given user.
stakePoolTicketsPrefix = []byte("tickt")
// stakePoolInvalidPrefix is the byte slice prefix for invalid
// tickets in the stake pool for a given user.
stakePoolInvalidPrefix = []byte("invld")
)
// byteOrder refers to the endianness used to encode data.
var byteOrder = binary.LittleEndian
// maybeConvertDbError converts the passed error to a TxStoreError with an
// error code of ErrDatabase if it is not already a TxStoreError. This is
// useful for potential errors returned from managed transaction an other parts
// of the walletdb database.
func maybeConvertDbError(err error) error {
// When the error is already a TxStoreError, just return it.
if _, ok := err.(StakeStoreError); ok {
return err
}
return stakeStoreError(ErrDatabase, err.Error(), err)
}
// Key names for various database fields.
// sstxRecords
// key: sstx tx hash
// val: sstxRecord
// ssgenRecords
// key: sstx tx hash
// val: serialized slice of ssgenRecords
//
var (
// Bucket names.
mainBucketName = []byte("main")
sstxRecordsBucketName = []byte("sstxrecords")
ssgenRecordsBucketName = []byte("ssgenrecords")
ssrtxRecordsBucketName = []byte("ssrtxrecords")
metaBucketName = []byte("meta")
// Db related key names (main bucket).
stakeStoreVersionName = []byte("stakestorever")
stakeStoreCreateDateName = []byte("stakestorecreated")
)
// int8ToBytes converts an 8 bit signed integer into a 1-byte slice.
func int8ToBytes(number int8) []byte {
var w bytes.Buffer
var buf [1]byte
buf[0] = byte(number)
w.Write(buf[:])
return w.Bytes()
}
// int8FromBytes converts a 1 byte byte slice to a signed 8 bit integer.
func int8FromBytes(slice []byte) int8 {
var number int8
buf := bytes.NewBuffer(slice[:])
binary.Read(buf, byteOrder, &number)
return number
}
// uint32ToBytes converts a 32 bit unsigned integer into a 4-byte slice in
// little-endian order: 1 -> [1 0 0 0].
func uint32ToBytes(number uint32) []byte {
buf := make([]byte, 4)
byteOrder.PutUint32(buf, number)
return buf
}
// deserializeSStxRecord deserializes the passed serialized tx record information.
func deserializeSStxRecord(serializedSStxRecord []byte) (*sstxRecord, error) {
record := new(sstxRecord)
curPos := 0
// Read MsgTx size (as a uint64).
msgTxLen := int(byteOrder.Uint64(
serializedSStxRecord[curPos : curPos+int64Size]))
curPos += int64Size
// Pretend to read the pkScrLoc for the 0th output pkScript.
curPos += int32Size
// Read the intended voteBits and extended voteBits length (uint8).
record.voteBitsSet = false
voteBitsLen := uint8(serializedSStxRecord[curPos])
if voteBitsLen != 0 {
record.voteBitsSet = true
}
curPos += int8Size
// Read the assumed 2 byte VoteBits and pretend to read the
// extended votebits (75 bytes).
record.voteBits = byteOrder.Uint16(
serializedSStxRecord[curPos : curPos+int16Size])
curPos += stake.MaxSingleBytePushLength
// Prepare a buffer for the msgTx.
buf := bytes.NewBuffer(serializedSStxRecord[curPos : curPos+msgTxLen])
curPos += msgTxLen
// Deserialize transaction.
msgTx := new(wire.MsgTx)
err := msgTx.Deserialize(buf)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
// Create and save the dcrutil.Tx of the read MsgTx and set its index.
tx := dcrutil.NewTx((*wire.MsgTx)(msgTx))
tx.SetIndex(dcrutil.TxIndexUnknown)
tx.SetTree(dcrutil.TxTreeStake)
record.tx = tx
// Read received unix time (int64).
received := int64(byteOrder.Uint64(
serializedSStxRecord[curPos : curPos+int64Size]))
curPos += int64Size
record.ts = time.Unix(received, 0)
return record, nil
}
// deserializeSStxTicketScriptHash deserializes and returns a 20 byte script
// hash for a ticket's 0th output.
func deserializeSStxTicketScriptHash(serializedSStxRecord []byte) ([]byte, error) {
dataLen := len(serializedSStxRecord)
curPos := 0
// Skip transaction size.
curPos += int64Size
// Load the pkScript index.
pkScrLoc := int(byteOrder.Uint32(
serializedSStxRecord[curPos : curPos+int32Size]))
curPos += int32Size
// Skip intended votebits length (uint8).
curPos += int8Size
// Skip intended votebits (75 bytes).
curPos += stake.MaxSingleBytePushLength
// Figure out the actual location of the script.
actualLoc := curPos + pkScrLoc
if actualLoc+3 >= dataLen {
return nil, stakeStoreError(ErrDatabase,
"bad serialized sstx record size", nil)
}
// Pop off the script prefix, then pop off the 20 bytes
// HASH160 pubkey or script hash.
prefixBytes := serializedSStxRecord[actualLoc : actualLoc+3]
scriptHash := make([]byte, 20, 20)
switch {
case bytes.Equal(prefixBytes, sstxTicket2PKHPrefix):
scrHashLoc := actualLoc + 4
if scrHashLoc+20 >= dataLen {
return nil, stakeStoreError(ErrDatabase,
"bad serialized sstx record size for pubkey hash", nil)
}
copy(scriptHash, serializedSStxRecord[scrHashLoc:scrHashLoc+20])
case bytes.Equal(prefixBytes, sstxTicket2SHPrefix):
scrHashLoc := actualLoc + 3
if scrHashLoc+20 >= dataLen {
return nil, stakeStoreError(ErrDatabase,
"bad serialized sstx record size for script hash", nil)
}
copy(scriptHash, serializedSStxRecord[scrHashLoc:scrHashLoc+20])
}
return scriptHash, nil
}
// serializeSSTxRecord returns the serialization of the passed txrecord row.
func serializeSStxRecord(record *sstxRecord, voteBits uint16) ([]byte, error) {
msgTx := record.tx.MsgTx()
msgTxSize := int64(msgTx.SerializeSize())
size := 0
// tx tree is implicit (stake)
// size of msgTx (recast to int64)
size += int64Size
// byte index of the ticket pk script
size += int32Size
// intended votebits length (uint8)
size += int8Size
// intended votebits (75 bytes)
size += stake.MaxSingleBytePushLength
// msgTx size is variable.
size += int(msgTxSize)
// timestamp (int64)
size += int64Size
buf := make([]byte, size)
curPos := 0
// Write msgTx size (as a uint64).
byteOrder.PutUint64(buf[curPos:curPos+int64Size], uint64(msgTxSize))
curPos += int64Size
// Write the pkScript loc for the ticket output as a uint32.
pkScrLoc := msgTx.PkScriptLocs()
byteOrder.PutUint32(buf[curPos:curPos+int32Size], uint32(pkScrLoc[0]))
curPos += int32Size
// Write the intended votebits length (uint8). Hardcode the uint16
// size for now. TODO Allow for extended voteBits.
buf[curPos] = byte(int16Size)
curPos += int8Size
// Write the first two bytes for the intended votebits (75 bytes max).
byteOrder.PutUint16(buf[curPos:curPos+int16Size], voteBits)
curPos += stake.MaxSingleBytePushLength
// Serialize and write transaction.
var b bytes.Buffer
err := msgTx.Serialize(&b)
if err != nil {
return buf, err
}
copy(buf[curPos:curPos+int(msgTxSize)], b.Bytes())
curPos += int(msgTxSize)
// Write received unix time (int64).
byteOrder.PutUint64(buf[curPos:curPos+int64Size], uint64(record.ts.Unix()))
curPos += int64Size
return buf, nil
}
// deserializeSSGenRecord deserializes the passed serialized tx
// record information.
func deserializeSSGenRecord(serializedSSGenRecord []byte) (*ssgenRecord,
error) {
// Cursory check to make sure that the size of the
// record makes sense.
if len(serializedSSGenRecord)%ssgenRecordSize != 0 {
str := "serialized SSGen record was wrong size"
return nil, stakeStoreError(ErrDatabase, str, nil)
}
record := new(ssgenRecord)
curPos := 0
// Insert the block hash into the record.
copy(record.blockHash[:], serializedSSGenRecord[curPos:curPos+hashSize])
curPos += hashSize
// Insert the block height into the record.
record.blockHeight = byteOrder.Uint32(
serializedSSGenRecord[curPos : curPos+int32Size])
curPos += int32Size
// Insert the tx hash into the record.
copy(record.txHash[:], serializedSSGenRecord[curPos:curPos+hashSize])
curPos += hashSize
// Insert the votebits into the record.
record.voteBits = byteOrder.Uint16(
serializedSSGenRecord[curPos : curPos+int16Size])
curPos += int16Size
// Insert the timestamp into the record.
record.ts = time.Unix(
int64(byteOrder.Uint64(
serializedSSGenRecord[curPos:curPos+int64Size])),
0)
curPos += int64Size
return record, nil
}
// deserializeSSGenRecords deserializes the passed serialized tx
// record information.
func deserializeSSGenRecords(serializedSSGenRecords []byte) ([]*ssgenRecord,
error) {
// Cursory check to make sure that the number of records
// makes sense.
if len(serializedSSGenRecords)%ssgenRecordSize != 0 {
err := io.ErrUnexpectedEOF
return nil, err
}
numRecords := len(serializedSSGenRecords) / ssgenRecordSize
records := make([]*ssgenRecord, numRecords)
// Loop through all the ssgen records, deserialize them, and
// store them.
for i := 0; i < numRecords; i++ {
record, err := deserializeSSGenRecord(
serializedSSGenRecords[i*ssgenRecordSize : (i+1)*ssgenRecordSize])
if err != nil {
str := "problem serializing ssgen record"
return nil, stakeStoreError(ErrDatabase, str, err)
}
records[i] = record
}
return records, nil
}
// serializeSSGenRecord returns the serialization of a single SSGen
// record.
func serializeSSGenRecord(record *ssgenRecord) []byte {
buf := make([]byte, ssgenRecordSize)
curPos := 0
// Write the block hash.
copy(buf[curPos:curPos+hashSize], record.blockHash.Bytes())
curPos += hashSize
// Write the block height.
byteOrder.PutUint32(buf[curPos:curPos+int32Size], record.blockHeight)
curPos += int32Size
// Write the tx hash.
copy(buf[curPos:curPos+hashSize], record.txHash.Bytes())
curPos += hashSize
// Write the vote bits.
byteOrder.PutUint16(buf[curPos:curPos+int16Size], record.voteBits)
curPos += int16Size
// Write the timestamp.
byteOrder.PutUint64(buf[curPos:curPos+int64Size], uint64(record.ts.Unix()))
curPos += int64Size
return buf
}
// serializeSSGenRecords returns the serialization of the passed
// SSGen records slice.
func serializeSSGenRecords(records []*ssgenRecord) []byte {
numRecords := len(records)
buf := make([]byte, numRecords*ssgenRecordSize)
// Serialize and write each record into the slice sequentially.
for i := 0; i < numRecords; i++ {
recordBytes := serializeSSGenRecord(records[i])
copy(buf[i*ssgenRecordSize:(i+1)*ssgenRecordSize],
recordBytes)
}
return buf
}
// deserializeSSRtxRecord deserializes the passed serialized SSRtx
// record information.
func deserializeSSRtxRecord(serializedSSRtxRecord []byte) (*ssrtxRecord,
error) {
// Cursory check to make sure that the size of the
// record makes sense.
if len(serializedSSRtxRecord)%ssrtxRecordSize != 0 {
str := "serialized SSRtx record was wrong size"
return nil, stakeStoreError(ErrDatabase, str, nil)
}
record := new(ssrtxRecord)
curPos := 0
// Insert the block hash into the record.
copy(record.blockHash[:], serializedSSRtxRecord[curPos:curPos+hashSize])
curPos += hashSize
// Insert the block height into the record.
record.blockHeight = byteOrder.Uint32(
serializedSSRtxRecord[curPos : curPos+int32Size])
curPos += int32Size
// Insert the tx hash into the record.
copy(record.txHash[:], serializedSSRtxRecord[curPos:curPos+hashSize])
curPos += hashSize
// Insert the timestamp into the record.
record.ts = time.Unix(
int64(byteOrder.Uint64(
serializedSSRtxRecord[curPos:curPos+int64Size])),
0)
curPos += int64Size
return record, nil
}
// deserializeSSRtxRecords deserializes the passed serialized SSRtx
// records information.
func deserializeSSRtxRecords(serializedSSRtxRecords []byte) ([]*ssrtxRecord,
error) {
// Cursory check to make sure that the number of records
// makes sense.
if len(serializedSSRtxRecords)%ssrtxRecordSize != 0 {
err := io.ErrUnexpectedEOF
return nil, err
}
numRecords := len(serializedSSRtxRecords) / ssrtxRecordSize
records := make([]*ssrtxRecord, numRecords)
// Loop through all the ssgen records, deserialize them, and
// store them.
for i := 0; i < numRecords; i++ {
record, err := deserializeSSRtxRecord(
serializedSSRtxRecords[i*ssrtxRecordSize : (i+1)*ssrtxRecordSize])
if err != nil {
str := "problem serializing ssrtx record"
return nil, stakeStoreError(ErrDatabase, str, err)
}
records[i] = record
}
return records, nil
}
// serializeSSRtxRecord returns the serialization of the passed
// SSRtx record.
func serializeSSRtxRecord(record *ssrtxRecord) []byte {
buf := make([]byte, ssrtxRecordSize)
curPos := 0
// Write the block hash.
copy(buf[curPos:curPos+hashSize], record.blockHash.Bytes())
curPos += hashSize
// Write the block height.
byteOrder.PutUint32(buf[curPos:curPos+int32Size], record.blockHeight)
curPos += int32Size
// Write the tx hash.
copy(buf[curPos:curPos+hashSize], record.txHash.Bytes())
curPos += hashSize
// Write the timestamp.
byteOrder.PutUint64(buf[curPos:curPos+int64Size], uint64(record.ts.Unix()))
curPos += int64Size
return buf
}
// serializeSSRtxRecords returns the serialization of the passed
// SSRtx records.
func serializeSSRtxRecords(records []*ssrtxRecord) []byte {
numRecords := len(records)
buf := make([]byte, numRecords*ssrtxRecordSize)
// Serialize and write each record into the slice sequentially.
for i := 0; i < numRecords; i++ {
recordBytes := serializeSSRtxRecord(records[i])
copy(buf[i*ssrtxRecordSize:(i+1)*ssrtxRecordSize],
recordBytes)
}
return buf
}
// stakeStoreExists returns whether or not the stake store has already
// been created in the given database namespace.
func stakeStoreExists(namespace walletdb.Namespace) (bool, error) {
var exists bool
err := namespace.View(func(tx walletdb.Tx) error {
mainBucket := tx.RootBucket().Bucket(mainBucketName)
exists = mainBucket != nil
return nil
})
if err != nil {
str := fmt.Sprintf("failed to obtain database view: %v", err)
return false, stakeStoreError(ErrDatabase, str, err)
}
return exists, nil
}
// fetchSStxRecord retrieves a tx record from the sstx records bucket
// with the given hash.
func fetchSStxRecord(tx walletdb.Tx, hash *chainhash.Hash) (*sstxRecord, error) {
bucket := tx.RootBucket().Bucket(sstxRecordsBucketName)
key := hash.Bytes()
val := bucket.Get(key)
if val == nil {
str := fmt.Sprintf("missing sstx record for hash '%s'", hash.String())
return nil, stakeStoreError(ErrSStxNotFound, str, nil)
}
return deserializeSStxRecord(val)
}
// fetchSStxRecordSStxTicketScriptHash retrieves a ticket 0th output script or
// pubkeyhash from the sstx records bucket with the given hash.
func fetchSStxRecordSStxTicketScriptHash(tx walletdb.Tx,
hash *chainhash.Hash) ([]byte, error) {
bucket := tx.RootBucket().Bucket(sstxRecordsBucketName)
key := hash.Bytes()
val := bucket.Get(key)
if val == nil {
str := fmt.Sprintf("missing sstx record for hash '%s'", hash.String())
return nil, stakeStoreError(ErrSStxNotFound, str, nil)
}
return deserializeSStxTicketScriptHash(val)
}
// fetchSStxRecordVoteBits fetches an individual ticket's intended voteBits
// which are used to override the default voteBits when voting.
func fetchSStxRecordVoteBits(tx walletdb.Tx, hash *chainhash.Hash) (bool, uint16,
error) {
bucket := tx.RootBucket().Bucket(sstxRecordsBucketName)
key := hash.Bytes()
val := bucket.Get(key)
if val == nil {
str := fmt.Sprintf("missing sstx record for hash '%s'", hash.String())
return false, 0, stakeStoreError(ErrSStxNotFound, str, nil)
}
valLen := len(val)
valCopy := make([]byte, valLen, valLen)
copy(valCopy, val)
// Move the cursor to the voteBits position and rewrite it.
curPos := 0
curPos += int64Size
curPos += int32Size
// Read the intended votebits length (uint8). If it is unset, return now.
voteBitsLen := uint8(val[curPos])
if voteBitsLen == 0 {
return false, 0, nil
}
curPos += int8Size
// Read the first two bytes for the intended votebits.
voteBits := byteOrder.Uint16(valCopy[curPos : curPos+int16Size])
return true, voteBits, nil
}
// updateSStxRecordVoteBits updates an individual ticket's intended voteBits
// which are used to override the default voteBits when voting.
func updateSStxRecordVoteBits(tx walletdb.Tx, hash *chainhash.Hash,
voteBits uint16) error {
bucket := tx.RootBucket().Bucket(sstxRecordsBucketName)
key := hash.Bytes()
val := bucket.Get(key)
if val == nil {
str := fmt.Sprintf("missing sstx record for hash '%s'", hash.String())
return stakeStoreError(ErrSStxNotFound, str, nil)
}
valLen := len(val)
valCopy := make([]byte, valLen, valLen)
copy(valCopy, val)
// Move the cursor to the voteBits position and rewrite it.
curPos := 0
curPos += int64Size
curPos += int32Size
// Write the intended votebits length (uint8). Hardcode the uint16
// size for now. TODO Allow for extended voteBits.
valCopy[curPos] = byte(int16Size)
curPos += int8Size
// Write the first two bytes for the intended votebits.
byteOrder.PutUint16(valCopy[curPos:curPos+int16Size], voteBits)
err := bucket.Put(key, valCopy)
if err != nil {
str := fmt.Sprintf("failed to update sstxrecord votebits for '%s'", hash)
return stakeStoreError(ErrDatabase, str, err)
}
return nil
}
// updateSStxRecord updates a sstx record in the sstx records bucket.
func updateSStxRecord(tx walletdb.Tx, record *sstxRecord, voteBits uint16) error {
bucket := tx.RootBucket().Bucket(sstxRecordsBucketName)
// Write the serialized txrecord keyed by the tx hash.
serializedSStxRecord, err := serializeSStxRecord(record, voteBits)
if err != nil {
str := fmt.Sprintf("failed to serialize sstxrecord '%s'", record.tx.Sha())
return stakeStoreError(ErrDatabase, str, err)
}
err = bucket.Put(record.tx.Sha().Bytes(), serializedSStxRecord)
if err != nil {
str := fmt.Sprintf("failed to store sstxrecord '%s'", record.tx.Sha())
return stakeStoreError(ErrDatabase, str, err)
}
return nil
}
// putSStxRecord inserts a given SStx record to the SStxrecords bucket.
func putSStxRecord(tx walletdb.Tx, record *sstxRecord, voteBits uint16) error {
return updateSStxRecord(tx, record, voteBits)
}
// fetchSSGenRecords retrieves SSGen records from the SSGenRecords bucket with
// the given hash.
func fetchSSGenRecords(tx walletdb.Tx, hash *chainhash.Hash) ([]*ssgenRecord,
error) {
bucket := tx.RootBucket().Bucket(ssgenRecordsBucketName)
key := hash.Bytes()
val := bucket.Get(key)
if val == nil {
str := fmt.Sprintf("missing ssgen records for hash '%s'", hash.String())
return nil, stakeStoreError(ErrSSGensNotFound, str, nil)
}
return deserializeSSGenRecords(val)
}
// ssgenRecordExistsInRecords checks to see if a record already exists
// in a slice of ssgen records.
func ssgenRecordExistsInRecords(record *ssgenRecord,
records []*ssgenRecord) bool {
for _, r := range records {
if r.txHash.IsEqual(&record.txHash) {
return true
}
}
return false
}
// updateSSGenRecord updates an SSGen record in the SSGen records bucket.
func updateSSGenRecord(tx walletdb.Tx, hash *chainhash.Hash,
record *ssgenRecord) error {
// Fetch the current content of the key.
// Possible buggy behaviour: If deserialization fails,
// we won't detect it here. We assume we're throwing
// ErrSSGenNotFound.
oldRecords, _ := fetchSSGenRecords(tx, hash)
// Don't reinsert records we already have.
if ssgenRecordExistsInRecords(record, oldRecords) {
return nil
}
bucket := tx.RootBucket().Bucket(ssgenRecordsBucketName)
var records []*ssgenRecord
// Either create a slice if currently nothing exists for this
// key in the db, or append the entry to the slice.
if oldRecords == nil {
records = make([]*ssgenRecord, 1)
records[0] = record
} else {
records = append(oldRecords, record)
}
// Write the serialized SSGens keyed by the sstx hash.
serializedSSGenRecords := serializeSSGenRecords(records)
err := bucket.Put(hash.Bytes(), serializedSSGenRecords)
if err != nil {
str := fmt.Sprintf("failed to store ssgen records '%s'", hash)
return stakeStoreError(ErrDatabase, str, err)
}
return nil
}
// putSSGenRecord inserts a given SSGen record to the SSGenrecords bucket.
func putSSGenRecord(tx walletdb.Tx, hash *chainhash.Hash,
record *ssgenRecord) error {
return updateSSGenRecord(tx, hash, record)
}
// fetchSSRtxRecords retrieves SSRtx records from the SSRtxRecords bucket with
// the given hash.
func fetchSSRtxRecords(tx walletdb.Tx, hash *chainhash.Hash) ([]*ssrtxRecord,
error) {
bucket := tx.RootBucket().Bucket(ssrtxRecordsBucketName)
key := hash.Bytes()
val := bucket.Get(key)
if val == nil {
str := fmt.Sprintf("missing ssrtx records for hash '%s'", hash.String())
return nil, stakeStoreError(ErrSSRtxsNotFound, str, nil)
}
return deserializeSSRtxRecords(val)
}
// ssrtxRecordExistsInRecords checks to see if a record already exists
// in a slice of ssrtx records.
func ssrtxRecordExistsInRecords(record *ssrtxRecord,
records []*ssrtxRecord) bool {
for _, r := range records {
if r.txHash.IsEqual(&record.txHash) {
return true
}
}
return false
}
// updateSSRtxRecord updates an SSRtx record in the SSRtx records bucket.
func updateSSRtxRecord(tx walletdb.Tx, hash *chainhash.Hash,
record *ssrtxRecord) error {
// Fetch the current content of the key.
// Possible buggy behaviour: If deserialization fails,
// we won't detect it here. We assume we're throwing
// ErrSSRtxsNotFound.
oldRecords, _ := fetchSSRtxRecords(tx, hash)
// Don't reinsert records we already have.
if ssrtxRecordExistsInRecords(record, oldRecords) {
return nil
}
bucket := tx.RootBucket().Bucket(ssrtxRecordsBucketName)
var records []*ssrtxRecord
// Either create a slice if currently nothing exists for this
// key in the db, or append the entry to the slice.
if oldRecords == nil {
records = make([]*ssrtxRecord, 1)
records[0] = record
} else {
records = append(oldRecords, record)
}
// Write the serialized SSRtxs keyed by the sstx hash.
serializedSSRtxsRecords := serializeSSRtxRecords(records)
err := bucket.Put(hash.Bytes(), serializedSSRtxsRecords)
if err != nil {
str := fmt.Sprintf("failed to store ssrtx records '%s'", hash)
return stakeStoreError(ErrDatabase, str, err)
}
return nil
}
// putSSRtxRecord inserts a given SSRtxs record to the SSRtxs records bucket.
func putSSRtxRecord(tx walletdb.Tx, hash *chainhash.Hash,
record *ssrtxRecord) error {
return updateSSRtxRecord(tx, hash, record)
}
// deserializeUserTicket deserializes the passed serialized user
// ticket information.
func deserializeUserTicket(serializedTicket []byte) (*PoolTicket,
error) {
// Cursory check to make sure that the size of the
// ticket makes sense.
if len(serializedTicket)%stakePoolUserTicketSize != 0 {
str := "serialized pool ticket record was wrong size"
return nil, stakeStoreError(ErrDatabase, str, nil)
}
record := new(PoolTicket)
curPos := 0
// Insert the ticket hash into the record.
copy(record.Ticket[:], serializedTicket[curPos:curPos+hashSize])
curPos += hashSize
// Insert the ticket height into the record.
record.HeightTicket = byteOrder.Uint32(
serializedTicket[curPos : curPos+int32Size])
curPos += int32Size
// Insert the status into the record.
record.Status = TicketStatus(serializedTicket[curPos])
curPos += int8Size
// Insert the spent by height into the record.
record.HeightSpent = byteOrder.Uint32(
serializedTicket[curPos : curPos+int32Size])
curPos += int32Size
// Insert the spending hash into the record.
copy(record.SpentBy[:], serializedTicket[curPos:curPos+hashSize])
curPos += hashSize
return record, nil
}
// deserializeUserTickets deserializes the passed serialized pool
// users tickets information.
func deserializeUserTickets(serializedTickets []byte) ([]*PoolTicket,
error) {
// Cursory check to make sure that the number of records
// makes sense.
if len(serializedTickets)%stakePoolUserTicketSize != 0 {
err := io.ErrUnexpectedEOF
return nil, err
}
numRecords := len(serializedTickets) / stakePoolUserTicketSize
records := make([]*PoolTicket, numRecords)
// Loop through all the records, deserialize them, and
// store them.
for i := 0; i < numRecords; i++ {
record, err := deserializeUserTicket(
serializedTickets[i*stakePoolUserTicketSize : (i+
1)*stakePoolUserTicketSize])
if err != nil {
str := "problem deserializing stake pool user tickets"
return nil, stakeStoreError(ErrDatabase, str, err)
}
records[i] = record
}
return records, nil
}
// serializeUserTicket returns the serialization of a single stake pool
// user ticket.
func serializeUserTicket(record *PoolTicket) []byte {
buf := make([]byte, stakePoolUserTicketSize)
curPos := 0
// Write the ticket hash.
copy(buf[curPos:curPos+hashSize], record.Ticket[:])
curPos += hashSize
// Write the ticket block height.
byteOrder.PutUint32(buf[curPos:curPos+int32Size], record.HeightTicket)
curPos += int32Size
// Write the ticket status.
buf[curPos] = byte(record.Status)
curPos += int8Size
// Write the spending height.
byteOrder.PutUint32(buf[curPos:curPos+int32Size], record.HeightSpent)
curPos += int32Size
// Write the spending tx hash.
copy(buf[curPos:curPos+hashSize], record.SpentBy[:])
curPos += hashSize
return buf
}
// serializeUserTickets returns the serialization of the passed stake pool
// user tickets slice.
func serializeUserTickets(records []*PoolTicket) []byte {
numRecords := len(records)
buf := make([]byte, numRecords*stakePoolUserTicketSize)
// Serialize and write each record into the slice sequentially.
for i := 0; i < numRecords; i++ {
recordBytes := serializeUserTicket(records[i])
copy(buf[i*stakePoolUserTicketSize:(i+1)*stakePoolUserTicketSize],
recordBytes)
}
return buf
}
// fetchStakePoolUserTickets retrieves pool user tickets from the meta bucket with
// the given hash.
func fetchStakePoolUserTickets(tx walletdb.Tx,
scriptHash [20]byte) ([]*PoolTicket, error) {
bucket := tx.RootBucket().Bucket(metaBucketName)
key := make([]byte, stakePoolTicketsPrefixSize+scriptHashSize)
copy(key[0:stakePoolTicketsPrefixSize], stakePoolTicketsPrefix)
copy(key[stakePoolTicketsPrefixSize:stakePoolTicketsPrefixSize+scriptHashSize],
scriptHash[:])
val := bucket.Get(key)
if val == nil {
str := fmt.Sprintf("missing pool user ticket records for hash '%x'",
scriptHash)
return nil, stakeStoreError(ErrPoolUserTicketsNotFound, str, nil)
}
return deserializeUserTickets(val)
}
// duplicateExistsInUserTickets checks to see if an exact duplicated of a
// record already exists in a slice of user ticket records.