/
chainio.go
1790 lines (1562 loc) · 60.1 KB
/
chainio.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-2016 The btcsuite developers
// Copyright (c) 2016-2023 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package blockchain
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"time"
"github.com/decred/dcrd/blockchain/stake/v5"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/database/v3"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/gcs/v4"
"github.com/decred/dcrd/gcs/v4/blockcf2"
"github.com/decred/dcrd/math/uint256"
"github.com/decred/dcrd/wire"
)
const (
// currentDatabaseVersion indicates the current database version.
currentDatabaseVersion = 14
// currentBlockIndexVersion indicates the current block index database
// version.
currentBlockIndexVersion = 3
// currentSpendJournalVersion indicates the current spend journal database
// version.
currentSpendJournalVersion = 3
// blockHdrSize is the size of a block header. This is simply the
// constant from wire and is only provided here for convenience since
// wire.MaxBlockHeaderPayload is quite long.
blockHdrSize = wire.MaxBlockHeaderPayload
)
var (
// byteOrder is the preferred byte order used for serializing numeric fields
// for storage in the database.
byteOrder = binary.LittleEndian
// bcdbInfoBucketName is the name of the database bucket used to house
// global versioning and date information for the blockchain database.
bcdbInfoBucketName = []byte("dbinfo")
// bcdbInfoVersionKeyName is the name of the database key used to house the
// database version. It is itself under the bcdbInfoBucketName bucket.
bcdbInfoVersionKeyName = []byte("version")
// bcdbInfoCompressionVerKeyName is the name of the database key used to
// house the database compression version. It is itself under the
// bcdbInfoBucketName bucket.
bcdbInfoCompressionVerKeyName = []byte("compver")
// bcdbInfoBlockIndexVerKeyName is the name of the database key used to
// house the database block index version. It is itself under the
// bcdbInfoBucketName bucket.
bcdbInfoBlockIndexVerKeyName = []byte("bidxver")
// bcdbInfoCreatedKeyName is the name of the database key used to house
// date the database was created. It is itself under the
// bcdbInfoBucketName bucket.
bcdbInfoCreatedKeyName = []byte("created")
// bcdbInfoSpendJournalVerKeyName is the name of the database key used to
// house the database spend journal version. It is itself under the
// bcdbInfoBucketName bucket.
bcdbInfoSpendJournalVerKeyName = []byte("stxover")
// chainStateKeyName is the name of the db key used to store the best chain
// state.
chainStateKeyName = []byte("chainstate")
// deploymentVerKeyName is the name of the db key used to store the
// deployment version.
deploymentVerKeyName = []byte("deploymentver")
// spendJournalBucketName is the name of the db bucket used to house
// transactions outputs that are spent in each block.
spendJournalBucketName = []byte("spendjournalv3")
// blockIndexBucketName is the name of the db bucket used to house the block
// index which consists of metadata for all known blocks both in the main
// chain and on side chains.
blockIndexBucketName = []byte("blockidxv3")
// gcsFilterBucketName is the name of the db bucket used to house GCS
// filters.
gcsFilterBucketName = []byte("gcsfilters")
// headerCmtsBucketName is the name of the db bucket used to house header
// commitment journal entries which consist of the hashes that the
// commitment root field of blocks commit to.
headerCmtsBucketName = []byte("hdrcmts")
// treasuryBucketName is the name of the db bucket that is used to house
// TADD/TSPEND additions and subtractions from the treasury account.
treasuryBucketName = []byte("treasury")
// treasuryTSpendBucketName is the name of the db bucket that is used to
// house TSpend transactions which were included in the blockchain.
treasuryTSpendBucketName = []byte("tspend")
)
// errNotInMainChain signifies that a block hash or height that is not in the
// main chain was requested.
type errNotInMainChain string
// Error implements the error interface.
func (e errNotInMainChain) Error() string {
return string(e)
}
// errDeserialize signifies that a problem was encountered when deserializing
// data.
type errDeserialize string
// Error implements the error interface.
func (e errDeserialize) Error() string {
return string(e)
}
// Is implements the interface to work with the standard library's errors.Is.
//
// It returns true in the following cases:
// - The target is errDeserialize
func (e errDeserialize) Is(target error) bool {
return isDeserializeErr(target)
}
// isDeserializeErr returns whether or not the passed error is an errDeserialize
// error.
func isDeserializeErr(err error) bool {
var e errDeserialize
return errors.As(err, &e)
}
// makeDbErr creates a database.Error given a set of arguments.
func makeDbErr(kind database.ErrorKind, desc string) database.Error {
return database.Error{Err: kind, Description: desc}
}
// -----------------------------------------------------------------------------
// The staking system requires some extra information to be stored for tickets
// to maintain consensus rules. The full set of minimal outputs are thus required
// in order for the chain to work correctly. A 'minimal output' is simply the
// script version, pubkey script, and amount.
// serializeSizeForMinimalOutputs calculates the number of bytes needed to
// serialize a transaction to its minimal outputs.
func serializeSizeForMinimalOutputs(tx *dcrutil.Tx) int {
sz := serializeSizeVLQ(uint64(len(tx.MsgTx().TxOut)))
for _, out := range tx.MsgTx().TxOut {
sz += serializeSizeVLQ(compressTxOutAmount(uint64(out.Value)))
sz += serializeSizeVLQ(uint64(out.Version))
sz += serializeSizeVLQ(uint64(len(out.PkScript)))
sz += len(out.PkScript)
}
return sz
}
// putTxToMinimalOutputs serializes a transaction to its minimal outputs.
// It returns the amount of data written. The function will panic if it writes
// beyond the bounds of the passed memory.
func putTxToMinimalOutputs(target []byte, tx *dcrutil.Tx) int {
offset := putVLQ(target, uint64(len(tx.MsgTx().TxOut)))
for _, out := range tx.MsgTx().TxOut {
offset += putVLQ(target[offset:], compressTxOutAmount(uint64(out.Value)))
offset += putVLQ(target[offset:], uint64(out.Version))
offset += putVLQ(target[offset:], uint64(len(out.PkScript)))
copy(target[offset:], out.PkScript)
offset += len(out.PkScript)
}
return offset
}
// deserializeToMinimalOutputs deserializes a series of minimal outputs to their
// decompressed, deserialized state and stores them in a slice. It also returns
// the amount of data read. The function will panic if it reads beyond the bounds
// of the passed memory.
func deserializeToMinimalOutputs(serialized []byte) ([]*stake.MinimalOutput, int) {
numOutputs, offset := deserializeVLQ(serialized)
minOuts := make([]*stake.MinimalOutput, int(numOutputs))
for i := 0; i < int(numOutputs); i++ {
amountComp, bytesRead := deserializeVLQ(serialized[offset:])
amount := decompressTxOutAmount(amountComp)
offset += bytesRead
version, bytesRead := deserializeVLQ(serialized[offset:])
offset += bytesRead
scriptSize, bytesRead := deserializeVLQ(serialized[offset:])
offset += bytesRead
pkScript := make([]byte, int(scriptSize))
copy(pkScript, serialized[offset:offset+int(scriptSize)])
offset += int(scriptSize)
minOuts[i] = &stake.MinimalOutput{
Value: int64(amount),
Version: uint16(version),
PkScript: pkScript,
}
}
return minOuts, offset
}
// readDeserializeSizeOfMinimalOutputs reads the size of the stored set of
// minimal outputs without allocating memory for the structs themselves.
func readDeserializeSizeOfMinimalOutputs(serialized []byte) (int, error) {
numOutputs, offset := deserializeVLQ(serialized)
if offset == 0 {
return offset, errDeserialize("unexpected end of " +
"data during decoding (num outputs)")
}
for i := 0; i < int(numOutputs); i++ {
// Amount
_, bytesRead := deserializeVLQ(serialized[offset:])
if bytesRead == 0 {
return offset, errDeserialize("unexpected end of " +
"data during decoding (output amount)")
}
offset += bytesRead
// Script version
_, bytesRead = deserializeVLQ(serialized[offset:])
if bytesRead == 0 {
return offset, errDeserialize("unexpected end of " +
"data during decoding (output script version)")
}
offset += bytesRead
// Script
var scriptSize uint64
scriptSize, bytesRead = deserializeVLQ(serialized[offset:])
if bytesRead == 0 {
return offset, errDeserialize("unexpected end of " +
"data during decoding (output script size)")
}
offset += bytesRead
if uint64(len(serialized[offset:])) < scriptSize {
return offset, errDeserialize("unexpected end of " +
"data during decoding (output script)")
}
offset += int(scriptSize)
}
return offset, nil
}
// -----------------------------------------------------------------------------
// The block index consists of an entry for every known block. It consists of
// information such as the block header and information about votes.
//
// The serialized key format is:
//
// <block height><block hash>
//
// Field Type Size
// block height uint32 4 bytes
// block hash chainhash.Hash chainhash.HashSize
//
// The serialized value format is:
//
// <block header><status><num votes><votes info>
//
// Field Type Size
// block header wire.BlockHeader 180 bytes
// status blockStatus 1 byte
// num votes VLQ variable
// vote info
// vote version VLQ variable
// vote bits VLQ variable
// -----------------------------------------------------------------------------
// blockIndexEntry represents a block index database entry.
type blockIndexEntry struct {
header wire.BlockHeader
status blockStatus
voteInfo []stake.VoteVersionTuple
}
// blockIndexKey generates the binary key for an entry in the block index
// bucket. The key is composed of the block height encoded as a big-endian
// 32-bit unsigned int followed by the 32 byte block hash. Big endian is used
// here so the entries can easily be iterated by height.
func blockIndexKey(blockHash *chainhash.Hash, blockHeight uint32) []byte {
indexKey := make([]byte, chainhash.HashSize+4)
binary.BigEndian.PutUint32(indexKey[0:4], blockHeight)
copy(indexKey[4:chainhash.HashSize+4], blockHash[:])
return indexKey
}
// blockIndexEntrySerializeSize returns the number of bytes it would take to
// serialize the passed block index entry according to the format described
// above.
func blockIndexEntrySerializeSize(entry *blockIndexEntry) int {
voteInfoSize := 0
for i := range entry.voteInfo {
voteInfoSize += serializeSizeVLQ(uint64(entry.voteInfo[i].Version)) +
serializeSizeVLQ(uint64(entry.voteInfo[i].Bits))
}
return blockHdrSize + 1 + serializeSizeVLQ(uint64(len(entry.voteInfo))) +
voteInfoSize
}
// putBlockIndexEntry serializes the passed block index entry according to the
// format described above directly into the passed target byte slice. The
// target byte slice must be at least large enough to handle the number of bytes
// returned by the blockIndexEntrySerializeSize function or it will panic.
func putBlockIndexEntry(target []byte, entry *blockIndexEntry) (int, error) {
// Serialize the entire block header.
w := bytes.NewBuffer(target[0:0])
if err := entry.header.Serialize(w); err != nil {
return 0, err
}
// Serialize the status.
offset := blockHdrSize
target[offset] = byte(entry.status)
offset++
// Serialize the number of votes and associated vote information.
offset += putVLQ(target[offset:], uint64(len(entry.voteInfo)))
for i := range entry.voteInfo {
offset += putVLQ(target[offset:], uint64(entry.voteInfo[i].Version))
offset += putVLQ(target[offset:], uint64(entry.voteInfo[i].Bits))
}
return offset, nil
}
// serializeBlockIndexEntry serializes the passed block index entry into a
// single byte slice according to the format described in detail above.
func serializeBlockIndexEntry(entry *blockIndexEntry) ([]byte, error) {
serialized := make([]byte, blockIndexEntrySerializeSize(entry))
_, err := putBlockIndexEntry(serialized, entry)
return serialized, err
}
// decodeBlockIndexEntry decodes the passed serialized block index entry into
// the passed struct according to the format described above. It returns the
// number of bytes read.
func decodeBlockIndexEntry(serialized []byte, entry *blockIndexEntry) (int, error) {
// Ensure there are enough bytes to decode header.
if len(serialized) < blockHdrSize {
return 0, errDeserialize("unexpected end of data while " +
"reading block header")
}
hB := serialized[0:blockHdrSize]
// Deserialize the header.
var header wire.BlockHeader
if err := header.Deserialize(bytes.NewReader(hB)); err != nil {
return 0, err
}
offset := blockHdrSize
// Deserialize the status.
if offset+1 > len(serialized) {
return offset, errDeserialize("unexpected end of data while " +
"reading status")
}
status := blockStatus(serialized[offset])
offset++
// Deserialize the number of tickets spent.
var votes []stake.VoteVersionTuple
numVotes, bytesRead := deserializeVLQ(serialized[offset:])
if bytesRead == 0 {
return offset, errDeserialize("unexpected end of data while " +
"reading num votes")
}
offset += bytesRead
if numVotes > 0 {
votes = make([]stake.VoteVersionTuple, numVotes)
for i := uint64(0); i < numVotes; i++ {
// Deserialize the vote version.
version, bytesRead := deserializeVLQ(serialized[offset:])
if bytesRead == 0 {
return offset, errDeserialize(fmt.Sprintf("unexpected "+
"end of data while reading vote #%d version",
i))
}
offset += bytesRead
// Deserialize the vote bits.
voteBits, bytesRead := deserializeVLQ(serialized[offset:])
if bytesRead == 0 {
return offset, errDeserialize(fmt.Sprintf("unexpected "+
"end of data while reading vote #%d bits",
i))
}
offset += bytesRead
votes[i].Version = uint32(version)
votes[i].Bits = uint16(voteBits)
}
}
entry.header = header
entry.status = status
entry.voteInfo = votes
return offset, nil
}
// deserializeBlockIndexEntry decodes the passed serialized byte slice into a
// block index entry according to the format described above.
func deserializeBlockIndexEntry(serialized []byte) (*blockIndexEntry, error) {
var entry blockIndexEntry
if _, err := decodeBlockIndexEntry(serialized, &entry); err != nil {
return nil, err
}
return &entry, nil
}
// dbPutBlockNode stores the information needed to reconstruct the provided
// block node in the block index according to the format described above.
func dbPutBlockNode(dbTx database.Tx, node *blockNode) error {
serialized, err := serializeBlockIndexEntry(&blockIndexEntry{
header: node.Header(),
status: node.status,
voteInfo: node.votes,
})
if err != nil {
return err
}
bucket := dbTx.Metadata().Bucket(blockIndexBucketName)
key := blockIndexKey(&node.hash, uint32(node.height))
return bucket.Put(key, serialized)
}
// dbMaybeStoreBlock stores the provided block in the database if it's not
// already there.
func dbMaybeStoreBlock(dbTx database.Tx, block *dcrutil.Block) error {
// Store the block in ffldb if not already done.
hasBlock, err := dbTx.HasBlock(block.Hash())
if err != nil {
return err
}
if hasBlock {
return nil
}
return dbTx.StoreBlock(block)
}
// -----------------------------------------------------------------------------
// The transaction spend journal consists of an entry for each block connected
// to the main chain which contains the transaction outputs the block spends
// serialized such that the order is the reverse of the order they were spent.
//
// This is required because reorganizing the chain necessarily entails
// disconnecting blocks to get back to the point of the fork which implies
// unspending all of the transaction outputs that each block previously spent.
// Since the utxo set, by definition, only contains unspent transaction outputs,
// the spent transaction outputs must be resurrected from somewhere. There is
// more than one way this could be done, however this is the most straight
// forward method that does not require having a transaction index and unpruned
// blockchain.
//
// NOTE: This format is NOT self describing. The additional details such as
// the number of entries (transaction inputs) are expected to come from the
// block itself and the utxo set. The rationale in doing this is to save a
// significant amount of space. This is also the reason the spent outputs are
// serialized in the reverse order they are spent because later transactions
// are allowed to spend outputs from earlier ones in the same block.
//
// The serialized format is:
//
// [<flags><script version><compressed pk script>],...
// OPTIONAL: <ticket min outs>
//
// Field Type Size
// flags VLQ byte
// scriptVersion uint16 2 bytes
// pkScript VLQ+[]byte variable
//
// OPTIONAL
// ticketMinOuts []byte variable
//
// The serialized flags format is:
// bit 0 - containing transaction is a coinbase
// bit 1 - containing transaction has an expiry
// bits 2-5 - transaction type
// bits 6-7 - unused
//
// The ticket min outs field contains minimally encoded outputs for all outputs
// of a ticket transaction. It is only encoded for ticket submission outputs.
//
// -----------------------------------------------------------------------------
// spentTxOut contains a spent transaction output and potentially additional
// contextual information such as whether or not it was contained in a coinbase
// transaction, whether or not the containing transaction has an expiry, and the
// transaction type.
//
// The struct is aligned for memory efficiency.
type spentTxOut struct {
amount int64
pkScript []byte
// ticketMinOuts is the minimal outputs for the ticket transaction that the
// output is contained in. This is only stored in ticket submission outputs
// and is nil for all other output types.
//
// Note that this is using a pointer rather than a slice in order to occupy
// less space when it is nil. It is nil in the vast majority of entries, so
// this provides a significant overall reduction in memory usage.
ticketMinOuts *ticketMinimalOutputs
blockHeight uint32
blockIndex uint32
scriptVersion uint16
// packedFlags contains additional info about the output as defined by
// txOutFlags. This approach is used in order to reduce memory usage since
// there will be a lot of these in memory.
packedFlags txOutFlags
}
// IsCoinBase returns whether or not the output was contained in a coinbase
// transaction.
func (stxo *spentTxOut) IsCoinBase() bool {
return stxo.packedFlags&txOutFlagCoinBase == txOutFlagCoinBase
}
// HasExpiry returns whether or not the output was contained in a transaction
// that included an expiry.
func (stxo *spentTxOut) HasExpiry() bool {
return stxo.packedFlags&txOutFlagHasExpiry == txOutFlagHasExpiry
}
// TransactionType returns the type of the transaction that the output is
// contained in.
func (stxo *spentTxOut) TransactionType() stake.TxType {
txType := (stxo.packedFlags & txOutFlagTxTypeBitmask) >> txOutFlagTxTypeShift
return stake.TxType(txType)
}
// spentTxOutSerializeSize returns the number of bytes it would take to
// serialize the passed stxo according to the format described above.
// The amount is never encoded into spent transaction outputs in Decred
// because they're already encoded into the transactions, so skip them when
// determining the serialization size.
func spentTxOutSerializeSize(stxo *spentTxOut) int {
flags := encodeFlags(stxo.IsCoinBase(), stxo.HasExpiry(),
stxo.TransactionType())
size := serializeSizeVLQ(uint64(flags))
const hasAmount = false
size += compressedTxOutSize(uint64(stxo.amount), stxo.scriptVersion,
stxo.pkScript, hasAmount)
if stxo.ticketMinOuts != nil {
size += len(stxo.ticketMinOuts.data)
}
return size
}
// putSpentTxOut serializes the passed stxo according to the format described
// above directly into the passed target byte slice. The target byte slice must
// be at least large enough to handle the number of bytes returned by the
// spentTxOutSerializeSize function or it will panic.
func putSpentTxOut(target []byte, stxo *spentTxOut) int {
flags := encodeFlags(stxo.IsCoinBase(), stxo.HasExpiry(),
stxo.TransactionType())
offset := putVLQ(target, uint64(flags))
const hasAmount = false
offset += putCompressedTxOut(target[offset:], 0, stxo.scriptVersion,
stxo.pkScript, hasAmount)
if stxo.ticketMinOuts != nil {
copy(target[offset:], stxo.ticketMinOuts.data)
offset += len(stxo.ticketMinOuts.data)
}
return offset
}
// decodeSpentTxOut decodes the passed serialized stxo entry, possibly followed
// by other data, into the passed stxo struct. It returns the number of bytes
// read.
func decodeSpentTxOut(serialized []byte, stxo *spentTxOut, amount int64,
height uint32, index uint32, txOutIndex uint32) (int, error) {
// Deserialize the flags.
flags, bytesRead := deserializeVLQ(serialized)
offset := bytesRead
if offset >= len(serialized) {
return offset, errDeserialize("unexpected end of data after flags")
}
// Decode the compressed txout. We pass false for the amount flag,
// since in Decred we only need pkScript at most due to fraud proofs
// already storing the decompressed amount.
_, scriptVersion, script, bytesRead, err :=
decodeCompressedTxOut(serialized[offset:], false)
offset += bytesRead
if err != nil {
return offset, errDeserialize(fmt.Sprintf("unable to decode "+
"txout: %v", err))
}
// Populate the stxo.
stxo.amount = amount
stxo.pkScript = script
stxo.blockHeight = height
stxo.blockIndex = index
stxo.scriptVersion = scriptVersion
stxo.packedFlags = txOutFlags(flags)
// Copy the minimal outputs if this was a ticket submission output.
if isTicketSubmissionOutput(stxo.TransactionType(), txOutIndex) {
sz, err := readDeserializeSizeOfMinimalOutputs(serialized[offset:])
if err != nil {
return offset + sz, errDeserialize(fmt.Sprintf("unable to decode "+
"ticket outputs: %v", err))
}
stxo.ticketMinOuts = &ticketMinimalOutputs{
data: make([]byte, sz),
}
copy(stxo.ticketMinOuts.data, serialized[offset:offset+sz])
offset += sz
}
return offset, nil
}
// deserializeSpendJournalEntry decodes the passed serialized byte slice into a
// slice of spent txouts according to the format described in detail above.
//
// Since the serialization format is not self describing, as noted in the
// format comments, this function also requires the transactions that spend the
// txouts and a utxo view that contains any remaining existing utxos in the
// transactions referenced by the inputs to the passed transactions.
func deserializeSpendJournalEntry(serialized []byte, txns []*wire.MsgTx) ([]spentTxOut, error) {
// Calculate the total number of stxos.
var numStxos int
for _, tx := range txns {
if stake.IsSSGen(tx) {
numStxos++
continue
}
numStxos += len(tx.TxIn)
}
// When a block has no spent txouts there is nothing to serialize.
if len(serialized) == 0 {
// Ensure the block actually has no stxos. This should never
// happen unless there is database corruption or an empty entry
// erroneously made its way into the database.
if numStxos != 0 {
return nil, AssertError(fmt.Sprintf("mismatched spend "+
"journal serialization - no serialization for "+
"expected %d stxos", numStxos))
}
return nil, nil
}
// Loop backwards through all transactions so everything is read in
// reverse order to match the serialization order.
stxoIdx := numStxos - 1
offset := 0
stxos := make([]spentTxOut, numStxos)
for txIdx := len(txns) - 1; txIdx > -1; txIdx-- {
tx := txns[txIdx]
isVote := stake.IsSSGen(tx)
// Loop backwards through all of the transaction inputs and read
// the associated stxo.
for txInIdx := len(tx.TxIn) - 1; txInIdx > -1; txInIdx-- {
// Skip stakebase since it has no input.
if txInIdx == 0 && isVote {
continue
}
txIn := tx.TxIn[txInIdx]
stxo := &stxos[stxoIdx]
stxoIdx--
n, err := decodeSpentTxOut(serialized[offset:], stxo, txIn.ValueIn,
txIn.BlockHeight, txIn.BlockIndex, txIn.PreviousOutPoint.Index)
offset += n
if err != nil {
return nil, errDeserialize(fmt.Sprintf("unable "+
"to decode stxo for %v: %v",
txIn.PreviousOutPoint, err))
}
}
}
return stxos, nil
}
// serializeSpendJournalEntry serializes all of the passed spent txouts into a
// single byte slice according to the format described in detail above.
func serializeSpendJournalEntry(stxos []spentTxOut) ([]byte, error) {
if len(stxos) == 0 {
return nil, nil
}
// Calculate the size needed to serialize the entire journal entry.
var size int
sizes := make([]int, 0, len(stxos))
for i := range stxos {
sz := spentTxOutSerializeSize(&stxos[i])
sizes = append(sizes, sz)
size += sz
}
serialized := make([]byte, size)
// Serialize each individual stxo directly into the slice in reverse
// order one after the other.
var offset int
for i := len(stxos) - 1; i > -1; i-- {
oldOffset := offset
offset += putSpentTxOut(serialized[offset:], &stxos[i])
if offset-oldOffset != sizes[i] {
return nil, AssertError(fmt.Sprintf("bad write; expect sz %v, "+
"got sz %v (wrote %x)", sizes[i], offset-oldOffset,
serialized[oldOffset:offset]))
}
}
return serialized, nil
}
// dbFetchSpendJournalEntry fetches the spend journal entry for the passed
// block and deserializes it into a slice of spent txout entries. The provided
// view MUST have the utxos referenced by all of the transactions available for
// the passed block since that information is required to reconstruct the spent
// txouts.
func dbFetchSpendJournalEntry(dbTx database.Tx, block *dcrutil.Block, isTreasuryEnabled bool) ([]spentTxOut, error) {
// Exclude the coinbase transaction since it can't spend anything.
spendBucket := dbTx.Metadata().Bucket(spendJournalBucketName)
serialized := spendBucket.Get(block.Hash()[:])
msgBlock := block.MsgBlock()
blockTxns := make([]*wire.MsgTx, 0, len(msgBlock.STransactions)+
len(msgBlock.Transactions[1:]))
if len(msgBlock.STransactions) > 0 && isTreasuryEnabled {
// Skip treasury base and remove tspends.
for _, v := range msgBlock.STransactions[1:] {
if stake.IsTSpend(v) {
continue
}
blockTxns = append(blockTxns, v)
}
} else {
blockTxns = append(blockTxns, msgBlock.STransactions...)
}
blockTxns = append(blockTxns, msgBlock.Transactions[1:]...)
if len(blockTxns) > 0 && len(serialized) == 0 {
panicf("missing spend journal data for %s", block.Hash())
}
stxos, err := deserializeSpendJournalEntry(serialized, blockTxns)
if err != nil {
// Ensure any deserialization errors are returned as database
// corruption errors.
if isDeserializeErr(err) {
str := fmt.Sprintf("corrupt spend information for %v: %v",
block.Hash(), err)
return nil, makeDbErr(database.ErrCorruption, str)
}
return nil, err
}
return stxos, nil
}
// dbPutSpendJournalEntry uses an existing database transaction to update the
// spend journal entry for the given block hash using the provided slice of
// spent txouts. The spent txouts slice must contain an entry for every txout
// the transactions in the block spend in the order they are spent.
func dbPutSpendJournalEntry(dbTx database.Tx, blockHash *chainhash.Hash, stxos []spentTxOut) error {
spendBucket := dbTx.Metadata().Bucket(spendJournalBucketName)
serialized, err := serializeSpendJournalEntry(stxos)
if err != nil {
return err
}
return spendBucket.Put(blockHash[:], serialized)
}
// dbRemoveSpendJournalEntry uses an existing database transaction to remove the
// spend journal entry for the passed block hash.
func dbRemoveSpendJournalEntry(dbTx database.Tx, blockHash *chainhash.Hash) error {
spendBucket := dbTx.Metadata().Bucket(spendJournalBucketName)
return spendBucket.Delete(blockHash[:])
}
// -----------------------------------------------------------------------------
// The GCS filter journal consists of an entry for each block connected to the
// main chain (or has ever been connected to it) which consists of a serialized
// GCS filter.
//
// The serialized key format is:
//
// <block hash>
//
// Field Type Size
// block hash chainhash.Hash chainhash.HashSize
//
// The serialized value format is:
//
// <serialized filter>
//
// Field Type Size
// filter []byte (gcs.FilterV2) variable
//
// -----------------------------------------------------------------------------
// dbFetchGCSFilter fetches the version 2 GCS filter for the passed block.
//
// When there is no entry for the provided hash, nil will be returned for both
// the filter and the error.
func dbFetchGCSFilter(dbTx database.Tx, blockHash *chainhash.Hash) (*gcs.FilterV2, error) {
filterBucket := dbTx.Metadata().Bucket(gcsFilterBucketName)
serialized := filterBucket.Get(blockHash[:])
if serialized == nil {
return nil, nil
}
filter, err := gcs.FromBytesV2(blockcf2.B, blockcf2.M, serialized)
if err != nil {
str := fmt.Sprintf("corrupt filter for %v: %v", blockHash, err)
return nil, makeDbErr(database.ErrCorruption, str)
}
return filter, nil
}
// dbPutGCSFilter uses an existing database transaction to update the version 2
// GCS filter for the given block hash using the provided filter.
func dbPutGCSFilter(dbTx database.Tx, blockHash *chainhash.Hash, filter *gcs.FilterV2) error {
filterBucket := dbTx.Metadata().Bucket(gcsFilterBucketName)
serialized := filter.Bytes()
return filterBucket.Put(blockHash[:], serialized)
}
// -----------------------------------------------------------------------------
// The header commitments journal consists of an entry for each block connected
// to the main chain (or has ever been connected to it) that contains each of
// the individual commitments covered by the commitment root field of the header
// of that block.
//
// Note that there will also not be an entry for blocks that do not commit to
// anything such as those prior to the activation of the header commitments
// agenda on networks where it is not always active.
//
// The serialized key format is:
//
// <block hash>
//
// Field Type Size
// block hash chainhash.Hash chainhash.HashSize
//
// The serialized value format is:
//
// <num commitment hashes><commitment hashes>
//
// Field Type Size
// num commitment hashes VLQ variable
// commitment hashes
// commitment hash chainhash.Hash chainhash.HashSize
//
// -----------------------------------------------------------------------------
// serializeHeaderCommitments serializes the passed commitment hashes into a
// single byte slice according to the format described in detail above.
func serializeHeaderCommitments(commitments []chainhash.Hash) []byte {
// Nothing to serialize when there are no commitments.
if len(commitments) == 0 {
return nil
}
// Calculate the full size needed to serialize the commitments.
numCommitments := len(commitments)
serializedLen := serializeSizeVLQ(uint64(numCommitments)) +
numCommitments*chainhash.HashSize
// Serialize the commitments.
serialized := make([]byte, serializedLen)
offset := putVLQ(serialized, uint64(numCommitments))
for i := range commitments {
copy(serialized[offset:], commitments[i][:])
offset += chainhash.HashSize
}
return serialized
}
// deserializeHeaderCommitments decodes the passed serialized byte slice into a
// slice of commitment hashes according to the format described in detail above.
func deserializeHeaderCommitments(serialized []byte) ([]chainhash.Hash, error) {
// Nothing is serialized when there are no commitments.
if len(serialized) == 0 {
return nil, nil
}
// Deserialize the number of commitments.
numCommitments, offset := deserializeVLQ(serialized)
if offset >= len(serialized) {
str := "unexpected end of data after num commitments"
return nil, makeDbErr(database.ErrCorruption, str)
}
// Ensure there are enough bytes remaining to read for the expected number
// of commitments.
totalCommitmentsSize := int(numCommitments) * chainhash.HashSize
if len(serialized[offset:]) < totalCommitmentsSize {
str := fmt.Sprintf("unexpected end of data after number of commitments "+
"(got %v, need %v)", len(serialized[offset:]), totalCommitmentsSize)
return nil, makeDbErr(database.ErrCorruption, str)
}
// Deserialize the commitments.
commitments := make([]chainhash.Hash, numCommitments)
for i := 0; i < int(numCommitments); i++ {
copy(commitments[i][:], serialized[offset:offset+chainhash.HashSize])
offset += chainhash.HashSize
}
return commitments, nil
}
// dbFetchHeaderCommitments fetches the hashes that the commitment root field of
// the header commits to for the passed block.
//
// When there is no entry for the provided block hash, nil will be returned for
// both the commitment hashes and the error.
func dbFetchHeaderCommitments(dbTx database.Tx, blockHash *chainhash.Hash) ([]chainhash.Hash, error) {
commitmentsBucket := dbTx.Metadata().Bucket(headerCmtsBucketName)
serialized := commitmentsBucket.Get(blockHash[:])
return deserializeHeaderCommitments(serialized)
}
// dbPutHeaderCommitments uses an existing database transaction to update the
// hashes that the commitment root field of the header commits to for the passed
// block.
//
// No database entry will be created when the provided commitments slice is nil
// or empty (aka zero length).
func dbPutHeaderCommitments(dbTx database.Tx, blockHash *chainhash.Hash, commitments []chainhash.Hash) error {
serialized := serializeHeaderCommitments(commitments)
if len(serialized) == 0 {
return nil
}
commitmentsBucket := dbTx.Metadata().Bucket(headerCmtsBucketName)
return commitmentsBucket.Put(blockHash[:], serialized)
}
// -----------------------------------------------------------------------------
// The database information contains information about the version and date
// of the blockchain database.
//
// It consists of a separate key for each individual piece of information:
//
// Key Value Size Description
// version uint32 4 bytes The version of the database
// compver uint32 4 bytes The script compression version of the database
// bidxver uint32 4 bytes The block index version of the database
// created uint64 8 bytes The date of the creation of the database
// stxover uint32 4 bytes The spend journal version of the database
// -----------------------------------------------------------------------------
// databaseInfo is the structure for a database.
type databaseInfo struct {
version uint32
compVer uint32
bidxVer uint32
created time.Time
stxoVer uint32
}
// dbPutDatabaseInfo uses an existing database transaction to store the database
// information.
func dbPutDatabaseInfo(dbTx database.Tx, dbi *databaseInfo) error {
// uint32Bytes is a helper function to convert a uint32 to a byte slice