forked from decred/dcrwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
txmined.go
3787 lines (3311 loc) · 106 KB
/
txmined.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) 2013-2015 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package udb
import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"sort"
"time"
"github.com/decred/dcrd/blockchain"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrutil"
"github.com/decred/dcrwallet/apperrors"
"github.com/decred/dcrwallet/walletdb"
"golang.org/x/crypto/ripemd160"
)
func storeError(code apperrors.Code, str string, err error) error {
return apperrors.E{ErrorCode: code, Description: str, Err: err}
}
// BehaviorFlags is a bitmask defining tweaks to the normal behavior when
// performing chain processing and consensus rules checks.
type BehaviorFlags uint32
const (
OP_NONSTAKE = txscript.OP_NOP10
BFBalanceAll BehaviorFlags = iota
BFBalanceLockedStake
BFBalanceSpendable
BFBalanceFullScan
)
// Block contains the minimum amount of data to uniquely identify any block on
// either the best or side chain.
type Block struct {
Hash chainhash.Hash
Height int32
}
// BlockMeta contains the unique identification for a block and any metadata
// pertaining to the block. At the moment, this additional metadata only
// includes the block time from the block header.
type BlockMeta struct {
Block
Time time.Time
VoteBits uint16
}
// blockRecord is an in-memory representation of the block record saved in the
// database.
type blockRecord struct {
Block
Time time.Time
VoteBits uint16
transactions []chainhash.Hash
}
// incidence records the block hash and blockchain height of a mined transaction.
// Since a transaction hash alone is not enough to uniquely identify a mined
// transaction (duplicate transaction hashes are allowed), the incidence is used
// instead.
type incidence struct {
txHash chainhash.Hash
block Block
}
// indexedIncidence records the transaction incidence and an input or output
// index.
type indexedIncidence struct {
incidence
index uint32
}
// credit describes a transaction output which was or is spendable by wallet.
type credit struct {
outPoint wire.OutPoint
block Block
amount dcrutil.Amount
change bool
spentBy indexedIncidence // Index == ^uint32(0) if unspent
opCode uint8
isCoinbase bool
}
// TxRecord represents a transaction managed by the Store.
type TxRecord struct {
MsgTx wire.MsgTx
Hash chainhash.Hash
Received time.Time
SerializedTx []byte // Optional: may be nil
TxType stake.TxType
}
// NewTxRecord creates a new transaction record that may be inserted into the
// store. It uses memoization to save the transaction hash and the serialized
// transaction.
func NewTxRecord(serializedTx []byte, received time.Time) (*TxRecord, error) {
rec := &TxRecord{
Received: received,
SerializedTx: serializedTx,
}
err := rec.MsgTx.Deserialize(bytes.NewReader(serializedTx))
if err != nil {
str := "failed to deserialize transaction"
return nil, storeError(apperrors.ErrInput, str, err)
}
rec.TxType = stake.DetermineTxType(&rec.MsgTx)
hash := rec.MsgTx.TxHash()
copy(rec.Hash[:], hash[:])
return rec, nil
}
// NewTxRecordFromMsgTx creates a new transaction record that may be inserted
// into the store.
func NewTxRecordFromMsgTx(msgTx *wire.MsgTx, received time.Time) (*TxRecord,
error) {
var buf bytes.Buffer
buf.Grow(msgTx.SerializeSize())
err := msgTx.Serialize(&buf)
if err != nil {
str := "failed to serialize transaction"
return nil, storeError(apperrors.ErrInput, str, err)
}
rec := &TxRecord{
MsgTx: *msgTx,
Received: received,
SerializedTx: buf.Bytes(),
}
rec.TxType = stake.DetermineTxType(&rec.MsgTx)
hash := rec.MsgTx.TxHash()
copy(rec.Hash[:], hash[:])
return rec, nil
}
// MultisigOut represents a spendable multisignature outpoint contain
// a script hash.
type MultisigOut struct {
OutPoint *wire.OutPoint
Tree int8
ScriptHash [ripemd160.Size]byte
M uint8
N uint8
TxHash chainhash.Hash
BlockHash chainhash.Hash
BlockHeight uint32
Amount dcrutil.Amount
Spent bool
SpentBy chainhash.Hash
SpentByIndex uint32
}
// Credit is the type representing a transaction output which was spent or
// is still spendable by wallet. A UTXO is an unspent Credit, but not all
// Credits are UTXOs.
type Credit struct {
wire.OutPoint
BlockMeta
Amount dcrutil.Amount
PkScript []byte
Received time.Time
FromCoinBase bool
}
// SortableTxRecords is a list of transaction records that can be sorted.
type SortableTxRecords []*TxRecord
func (p SortableTxRecords) Len() int { return len(p) }
func (p SortableTxRecords) Less(i, j int) bool {
return p[i].Received.Before(p[j].Received)
}
func (p SortableTxRecords) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// PruneOldTickets prunes old stake tickets from before ticketCutoff from the
// database.
func (s *Store) PruneOldTickets(ns walletdb.ReadWriteBucket) error {
ticketCutoff := s.chainParams.TargetTimePerBlock *
time.Duration(s.chainParams.WorkDiffWindowSize)
current := time.Now()
log.Infof("Pruning old tickets from before from the transaction " +
"database, please do not attempt to close your wallet.")
minedBalance, err := fetchMinedBalance(ns)
if err != nil {
return err
}
// Cache for records, so we can sort them.
var savedSStxs SortableTxRecords
err = ns.NestedReadBucket(bucketUnmined).ForEach(func(k, v []byte) error {
// TODO: Parsing transactions from the db may be a little
// expensive. It's possible the caller only wants the
// serialized transactions.
var txHash chainhash.Hash
err := readRawUnminedHash(k, &txHash)
if err != nil {
return err
}
var rec TxRecord
err = readRawTxRecord(&txHash, v, &rec)
if err != nil {
return err
}
txType := stake.DetermineTxType(&rec.MsgTx)
// Prune all old tickets.
if current.Sub(rec.Received) > ticketCutoff &&
(txType == stake.TxTypeSStx) {
savedSStxs = append(savedSStxs, &rec)
}
return err
})
if err != nil {
return err
}
// The transactions need to be sorted by date inserted in
// case one SStx spends from the change of another, in
// which case ordering matters.
sort.Sort(sort.Reverse(savedSStxs))
for _, rec := range savedSStxs {
// Return all the inputs to their unspent state.
for _, txi := range rec.MsgTx.TxIn {
// Figure out where the used outpoint was
// from, either a credit or an unmined credit.
// Make sure the input exists.
prevOut := &txi.PreviousOutPoint
prevOutKey := canonicalOutPoint(&prevOut.Hash,
prevOut.Index)
valUMInput := existsRawUnminedInput(ns, prevOutKey)
if valUMInput == nil {
return fmt.Errorf("missing unmined input")
}
var keyCredit []byte
var valCredit []byte
// Look up and see if it spends a mined credit.
spendsMinedCredit := true
err := ns.NestedReadBucket(bucketCredits).ForEach(
func(lkc, lvc []byte) error {
lcHash := extractRawCreditTxHash(lkc)
lcIndex := extractRawCreditIndex(lkc)
lcOp := canonicalOutPoint(&lcHash,
lcIndex)
if bytes.Equal(lcOp, prevOutKey) {
keyCredit = lkc
valCredit = lvc
}
return nil
})
if err != nil {
return err
}
// Should spend an unmined output, then.
// Find it.
if valCredit == nil || keyCredit == nil {
valRawUMC := existsRawUnminedCredit(ns, prevOutKey)
if valRawUMC != nil {
spendsMinedCredit = false
keyCredit = prevOutKey
valCredit = valRawUMC
}
}
if valCredit == nil || keyCredit == nil {
return fmt.Errorf("credit missing")
}
// Unspending mined credits increments our balance,
// so there are a lot of extra steps we have to take
// to patch that.
if spendsMinedCredit {
var amt dcrutil.Amount
amt, err = unspendRawCredit(ns, keyCredit)
if err != nil {
return err
}
// If the credit was previously removed by being
// double spent, the credit amount is zero. Only
// mark the previously spent credit as unspent
// if it still exists.
if amt == 0 {
continue
}
unspentVal, err := fetchRawCreditUnspentValue(keyCredit)
if err != nil {
return err
}
minedBalance = minedBalance + amt
err = putRawUnspent(ns, prevOutKey, unspentVal)
if err != nil {
return err
}
} else {
// An unmined output was used as an input, mark it
// unspent. However, tx mananger doesn't currently
// keep spending data for unspent outputs so do
// nothing??? cj
}
// Delete the unmined input.
err = deleteRawUnminedInput(ns, prevOutKey)
if err != nil {
return err
}
}
for idx, txo := range rec.MsgTx.TxOut {
class := txscript.GetScriptClass(txo.Version, txo.PkScript)
// For tickets, the only thing we care about are submission
// and change tagged outputs.
switch {
case class == txscript.StakeSubmissionTy ||
class == txscript.StakeSubChangeTy:
// See if we inserted the unmined credit. If so,
// remove it.
outK := canonicalOutPoint(&rec.Hash, uint32(idx))
val := existsRawUnminedCredit(ns, outK)
if val != nil {
err = deleteRawUnminedCredit(ns, outK)
if err != nil {
return err
}
}
}
}
// Delete the transaction record itself.
err = deleteRawUnmined(ns, rec.Hash[:])
if err != nil {
return err
}
}
// Update our balance.
return putMinedBalance(ns, minedBalance)
}
// Store implements a transaction store for storing and managing wallet
// transactions.
type Store struct {
chainParams *chaincfg.Params
acctLookupFunc func(walletdb.ReadBucket, dcrutil.Address) (uint32, error)
}
// MainChainTip returns the hash and height of the currently marked tip-most
// block of the main chain.
func (s *Store) MainChainTip(ns walletdb.ReadBucket) (chainhash.Hash, int32) {
var hash chainhash.Hash
tipHash := ns.Get(rootTipBlock)
copy(hash[:], tipHash)
header := ns.NestedReadBucket(bucketHeaders).Get(hash[:])
height := extractBlockHeaderHeight(header)
return hash, height
}
// ExtendMainChain inserts a block header into the database. It must connect to
// the existing tip block.
//
// If the block is already inserted and part of the main chain, an error with
// code ErrDuplicate is returned.
func (s *Store) ExtendMainChain(ns walletdb.ReadWriteBucket, header *BlockHeaderData) error {
height := header.SerializedHeader.Height()
if height < 1 {
const str = "can not extend main chain with genesis block 0"
return storeError(apperrors.ErrInput, str, nil)
}
headerBucket := ns.NestedReadWriteBucket(bucketHeaders)
headerParent := extractBlockHeaderParentHash(header.SerializedHeader[:])
currentTipHash := ns.Get(rootTipBlock)
if !bytes.Equal(headerParent, currentTipHash) {
// Return a special error if it is a duplicate of an existing block in
// the main chain (NOT the headers bucket, since headers are never
// pruned).
_, v := existsBlockRecord(ns, height)
if v != nil && bytes.Equal(extractRawBlockRecordHash(v), header.BlockHash[:]) {
const str = "block already recorded in the main chain"
return storeError(apperrors.ErrDuplicate, str, nil)
}
const str = "header is not a direct child of the current tip block"
return storeError(apperrors.ErrInput, str, nil)
}
// Also check that the height is one more than the current height
// recorded by the current tip.
currentTipHeader := headerBucket.Get(currentTipHash)
currentTipHeight := extractBlockHeaderHeight(currentTipHeader)
if currentTipHeight+1 != height {
const str = "header height is not one more than the current tip height"
return storeError(apperrors.ErrInput, str, nil)
}
vb := extractBlockHeaderVoteBits(header.SerializedHeader[:])
var err error
if approvesParent(vb) {
err = stakeValidate(ns, currentTipHeight)
} else {
err = stakeInvalidate(ns, currentTipHeight)
}
if err != nil {
return err
}
// Add the header
err = headerBucket.Put(header.BlockHash[:], header.SerializedHeader[:])
if err != nil {
const str = "failed to write header"
return storeError(apperrors.ErrDatabase, str, err)
}
// Update the tip block
err = ns.Put(rootTipBlock, header.BlockHash[:])
if err != nil {
const str = "failed to write new tip block hash"
return storeError(apperrors.ErrDatabase, str, err)
}
// Add an empty block record
blockKey := keyBlockRecord(height)
blockVal := valueBlockRecordEmptyFromHeader(&header.BlockHash, &header.SerializedHeader)
return putRawBlockRecord(ns, blockKey, blockVal)
}
// GetBlockHash fetches the block hash for the block at the given height,
// and returns an error if it's missing.
func (s *Store) GetBlockHash(ns walletdb.ReadBucket, height int32) (chainhash.Hash, error) {
br, err := fetchBlockRecord(ns, height)
if err != nil {
return chainhash.Hash{}, err
}
return br.Block.Hash, nil
}
// log2 calculates an integer approximation of log2(x). This is used to
// approximate the cap to use when allocating memory for the block locators.
func log2(x int) int {
res := 0
for x != 0 {
x /= 2
res++
}
return res
}
// BlockLocators returns, in reversed order (newest blocks first), hashes of
// blocks believed to be on the main chain. For memory and lookup efficiency,
// many older hashes are skipped, with increasing gaps between included hashes.
// This returns the block locators that should be included in a getheaders wire
// message or RPC request.
func (s *Store) BlockLocators(ns walletdb.ReadBucket) []chainhash.Hash {
headerBucket := ns.NestedReadBucket(bucketHeaders)
hash := ns.Get(rootTipBlock)
height := extractBlockHeaderHeight(headerBucket.Get(hash))
locators := make([]chainhash.Hash, 1, 10+log2(int(height)))
copy(locators[0][:], hash)
var skip, skips int32 = 0, 1
for height >= 0 {
if skip != 0 {
height -= skip
skip = 0
continue
}
_, blockVal := existsBlockRecord(ns, height)
hash = extractRawBlockRecordHash(blockVal)
var locator chainhash.Hash
copy(locator[:], hash)
locators = append(locators, locator)
if len(locators) >= 10 {
skips *= 2
skip = skips
}
}
return locators
}
func extractBlockHeaderParentHash(header []byte) []byte {
const parentOffset = 4
return header[parentOffset : parentOffset+chainhash.HashSize]
}
// ExtractBlockHeaderParentHash subslices the header to return the bytes of the
// parent block's hash. Must only be called on known good input.
//
// TODO: This really should not be exported by this package.
func ExtractBlockHeaderParentHash(header []byte) []byte {
return extractBlockHeaderParentHash(header)
}
func extractBlockHeaderVoteBits(header []byte) uint16 {
const voteBitsOffset = 100
return binary.LittleEndian.Uint16(header[voteBitsOffset:])
}
func extractBlockHeaderHeight(header []byte) int32 {
const heightOffset = 128
return int32(binary.LittleEndian.Uint32(header[heightOffset:]))
}
// ExtractBlockHeaderHeight returns the height field that is encoded in the
// header. Must only be called on known good input.
//
// TODO: This really should not be exported by this package.
func ExtractBlockHeaderHeight(header []byte) int32 {
return extractBlockHeaderHeight(header)
}
func extractBlockHeaderUnixTime(header []byte) uint32 {
const timestampOffset = 136
return binary.LittleEndian.Uint32(header[timestampOffset:])
}
// ExtractBlockHeaderTime returns the unix timestamp that is encoded in the
// header. Must only be called on known good input. Header timestamps are only
// 4 bytes and this value is actually limited to a maximum unix time of 2^32-1.
//
// TODO: This really should not be exported by this package.
func ExtractBlockHeaderTime(header []byte) int64 {
return int64(extractBlockHeaderUnixTime(header))
}
func blockMetaFromHeader(blockHash *chainhash.Hash, header []byte) BlockMeta {
return BlockMeta{
Block: Block{
Hash: *blockHash,
Height: extractBlockHeaderHeight(header),
},
Time: time.Unix(int64(extractBlockHeaderUnixTime(header)), 0),
VoteBits: extractBlockHeaderVoteBits(header),
}
}
// RawBlockHeader is a 180 byte block header (always true for version 0 blocks).
type RawBlockHeader [180]byte
// Height extracts the height encoded in a block header.
func (h *RawBlockHeader) Height() int32 {
return extractBlockHeaderHeight(h[:])
}
// BlockHeaderData contains the block hashes and serialized blocks headers that
// are inserted into the database. At time of writing this only supports wire
// protocol version 0 blocks and changes will need to be made if the block
// header size changes.
type BlockHeaderData struct {
BlockHash chainhash.Hash
SerializedHeader RawBlockHeader
}
// stakeValidate validates regular tree transactions from the main chain block
// at some height. This does not perform any changes when the block is not
// marked invalid. When currently invalidated, the invalidated byte is set to 0
// to mark the block as stake validated and the mined balance is incremented for
// all credits of this block.
//
// Stake validation or invalidation should only occur for the block at height
// tip-1.
func stakeValidate(ns walletdb.ReadWriteBucket, height int32) error {
k, v := existsBlockRecord(ns, height)
if v == nil {
str := fmt.Sprintf("no block record for height %v", height)
return storeError(apperrors.ErrValueNoExists, str, nil)
}
if !extractRawBlockRecordStakeInvalid(v) {
return nil
}
minedBalance, err := fetchMinedBalance(ns)
if err != nil {
return err
}
var blockRec blockRecord
err = readRawBlockRecord(k, v, &blockRec)
if err != nil {
return err
}
// Rewrite the block record, marking the regular tree as stake validated.
err = putRawBlockRecord(ns, k, valueBlockRecordStakeValidated(v))
if err != nil {
return err
}
for i := range blockRec.transactions {
txHash := &blockRec.transactions[i]
_, txv := existsTxRecord(ns, txHash, &blockRec.Block)
if txv == nil {
str := fmt.Sprintf("missing transaction record for tx %v block %v",
txHash, &blockRec.Block.Hash)
return storeError(apperrors.ErrData, str, err)
}
var txRec TxRecord
err = readRawTxRecord(txHash, txv, &txRec)
if err != nil {
return err
}
// Only regular tree transactions must be considered.
if txRec.TxType != stake.TxTypeRegular {
continue
}
// Move all credits from this tx to the non-invalidated credits bucket.
// Add an unspent output for each validated credit.
// The mined balance is incremented for all moved credit outputs.
creditOutPoint := wire.OutPoint{Hash: txRec.Hash} // Index set in loop
for i, output := range txRec.MsgTx.TxOut {
k, v := existsInvalidatedCredit(ns, &txRec.Hash, uint32(i), &blockRec.Block)
if v == nil {
continue
}
err = ns.NestedReadWriteBucket(bucketStakeInvalidatedCredits).
Delete(k)
if err != nil {
const str = "failed to remove stake invalidated credit"
return storeError(apperrors.ErrDatabase, str, err)
}
err = putRawCredit(ns, k, v)
if err != nil {
return err
}
creditOutPoint.Index = uint32(i)
err = putUnspent(ns, &creditOutPoint, &blockRec.Block)
if err != nil {
return err
}
minedBalance += dcrutil.Amount(output.Value)
}
// Move all debits from this tx to the non-invalidated debits bucket,
// and spend any previous credits spent by the stake validated tx.
// Remove utxos for all spent previous credits. The mined balance is
// decremented for all previous credits that are no longer spendable.
debitIncidence := indexedIncidence{
incidence: incidence{txHash: txRec.Hash, block: blockRec.Block},
// index set for each rec input below.
}
for i := range txRec.MsgTx.TxIn {
debKey, credKey, err := existsInvalidatedDebit(ns, &txRec.Hash, uint32(i),
&blockRec.Block)
if err != nil {
return err
}
if debKey == nil {
continue
}
debitIncidence.index = uint32(i)
debVal := ns.NestedReadBucket(bucketStakeInvalidatedDebits).
Get(debKey)
debitAmount := extractRawDebitAmount(debVal)
_, err = spendCredit(ns, credKey, &debitIncidence)
if err != nil {
return err
}
prevOut := &txRec.MsgTx.TxIn[i].PreviousOutPoint
unspentKey := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
err = deleteRawUnspent(ns, unspentKey)
if err != nil {
return err
}
err = ns.NestedReadWriteBucket(bucketStakeInvalidatedDebits).
Delete(debKey)
if err != nil {
const str = "failed to remove stake invalidated debit"
return storeError(apperrors.ErrDatabase, str, err)
}
err = putRawDebit(ns, debKey, debVal)
if err != nil {
return err
}
minedBalance -= debitAmount
}
}
return putMinedBalance(ns, minedBalance)
}
// stakeInvalidate invalidates regular tree transactions from the main chain
// block at some height. This does not perform any changes when the block is
// not marked invalid. When not marked invalid, the invalidated byte is set to
// 1 to mark the block as stake invalidated and the mined balance is decremented
// for all credits.
//
// Stake validation or invalidation should only occur for the block at height
// tip-1.
//
// See stakeValidate (which performs the reverse operation) for more details.
func stakeInvalidate(ns walletdb.ReadWriteBucket, height int32) error {
k, v := existsBlockRecord(ns, height)
if v == nil {
str := fmt.Sprintf("no block record for height %v", height)
return storeError(apperrors.ErrValueNoExists, str, nil)
}
if extractRawBlockRecordStakeInvalid(v) {
return nil
}
minedBalance, err := fetchMinedBalance(ns)
if err != nil {
return err
}
var blockRec blockRecord
err = readRawBlockRecord(k, v, &blockRec)
if err != nil {
return err
}
// Rewrite the block record, marking the regular tree as stake invalidated.
err = putRawBlockRecord(ns, k, valueBlockRecordStakeInvalidated(v))
if err != nil {
return err
}
for i := range blockRec.transactions {
txHash := &blockRec.transactions[i]
_, txv := existsTxRecord(ns, txHash, &blockRec.Block)
if txv == nil {
str := fmt.Sprintf("missing transaction record for tx %v block %v",
txHash, &blockRec.Block.Hash)
return storeError(apperrors.ErrData, str, err)
}
var txRec TxRecord
err = readRawTxRecord(txHash, txv, &txRec)
if err != nil {
return err
}
// Only regular tree transactions must be considered.
if txRec.TxType != stake.TxTypeRegular {
continue
}
// Move all credits from this tx to the invalidated credits bucket.
// Remove the unspent output for each invalidated credit.
// The mined balance is decremented for all moved credit outputs.
for i, output := range txRec.MsgTx.TxOut {
k, v := existsCredit(ns, &txRec.Hash, uint32(i), &blockRec.Block)
if v == nil {
continue
}
err = deleteRawCredit(ns, k)
if err != nil {
return err
}
err = ns.NestedReadWriteBucket(bucketStakeInvalidatedCredits).
Put(k, v)
if err != nil {
const str = "failed to write stake invalidated credit"
return storeError(apperrors.ErrDatabase, str, err)
}
unspentKey := canonicalOutPoint(txHash, uint32(i))
err = deleteRawUnspent(ns, unspentKey)
if err != nil {
return err
}
minedBalance -= dcrutil.Amount(output.Value)
}
// Move all debits from this tx to the invalidated debits bucket, and
// unspend any credit spents by the stake invalidated tx. The mined
// balance is incremented for all previous credits that are spendable
// again.
for i := range txRec.MsgTx.TxIn {
debKey, credKey, err := existsDebit(ns, &txRec.Hash, uint32(i),
&blockRec.Block)
if err != nil {
return err
}
if debKey == nil {
continue
}
debVal := ns.NestedReadBucket(bucketDebits).Get(debKey)
debitAmount := extractRawDebitAmount(debVal)
_, err = unspendRawCredit(ns, credKey)
if err != nil {
return err
}
err = deleteRawDebit(ns, debKey)
if err != nil {
return err
}
err = ns.NestedReadWriteBucket(bucketStakeInvalidatedDebits).
Put(debKey, debVal)
if err != nil {
const str = "failed to write stake invalidated debit"
return storeError(apperrors.ErrDatabase, str, err)
}
prevOut := &txRec.MsgTx.TxIn[i].PreviousOutPoint
unspentKey := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
unspentVal := extractRawDebitUnspentValue(debVal)
err = putRawUnspent(ns, unspentKey, unspentVal)
if err != nil {
return err
}
minedBalance += debitAmount
}
}
return putMinedBalance(ns, minedBalance)
}
// InsertMainChainHeaders permanently saves block headers. Headers should be in
// order of increasing heights and there should not be any gaps between blocks.
// After inserting headers, if the existing recorded tip block is behind the
// last main chain block header that was inserted, a chain switch occurs and the
// new tip block is recorded.
func (s *Store) InsertMainChainHeaders(ns walletdb.ReadWriteBucket, addrmgrNs walletdb.ReadBucket,
headers []BlockHeaderData) error {
if len(headers) == 0 {
return nil
}
// If the first header is not yet saved, make sure the parent is.
if existsBlockHeader(ns, keyBlockHeader(&headers[0].BlockHash)) == nil {
parentHash := extractBlockHeaderParentHash(headers[0].SerializedHeader[:])
if existsBlockHeader(ns, parentHash) == nil {
const str = "missing parent of first header"
return storeError(apperrors.ErrValueNoExists, str, nil)
}
}
candidateTip := &headers[len(headers)-1]
candidateTipHeight := extractBlockHeaderHeight(candidateTip.SerializedHeader[:])
currentTipHash := ns.Get(rootTipBlock)
currentTipHeader := ns.NestedReadBucket(bucketHeaders).Get(currentTipHash)
currentTipHeight := extractBlockHeaderHeight(currentTipHeader)
if candidateTipHeight >= currentTipHeight {
err := ns.Put(rootTipBlock, candidateTip.BlockHash[:])
if err != nil {
const str = "failed to write new tip block"
return storeError(apperrors.ErrDatabase, str, err)
}
}
for i := range headers {
hash := &headers[i].BlockHash
header := &headers[i].SerializedHeader
// Any blocks known to not exist on this main chain are to be removed.
height := extractBlockHeaderHeight(header[:])
rk, rv := existsBlockRecord(ns, height)
if rv != nil {
recHash := extractRawBlockRecordHash(rv)
if !bytes.Equal(hash[:], recHash) {
err := s.rollback(ns, addrmgrNs, height)
if err != nil {
return err
}
blockVal := valueBlockRecordEmptyFromHeader(hash, header)
err = putRawBlockRecord(ns, rk, blockVal)
if err != nil {
return err
}
}
} else {
blockVal := valueBlockRecordEmptyFromHeader(hash, header)
err := putRawBlockRecord(ns, rk, blockVal)
if err != nil {
return err
}
}
// Insert the header.
k := keyBlockHeader(hash)
v := header[:]
err := putRawBlockHeader(ns, k, v)
if err != nil {
return err
}
// Handle stake validation of the parent block.
parentHeight := header.Height() - 1
vb := extractBlockHeaderVoteBits(header[:])
if approvesParent(vb) {
err = stakeValidate(ns, parentHeight)
} else {
err = stakeInvalidate(ns, parentHeight)
}
if err != nil {
return err
}
}
return nil
}
// GetMainChainBlockHashForHeight returns the block hash of the block on the
// main chain at a given height.
func (s *Store) GetMainChainBlockHashForHeight(ns walletdb.ReadBucket, height int32) (chainhash.Hash, error) {
_, v := existsBlockRecord(ns, height)
if v == nil {
const str = "No main chain block for height"
return chainhash.Hash{}, storeError(apperrors.ErrValueNoExists, str, nil)
}
var hash chainhash.Hash
copy(hash[:], extractRawBlockRecordHash(v))
return hash, nil
}
// GetSerializedBlockHeader returns the bytes of the serialized header for the
// block specified by its hash. These bytes are a copy of the value returned
// from the DB and are usable outside of the transaction.
func (s *Store) GetSerializedBlockHeader(ns walletdb.ReadBucket, blockHash *chainhash.Hash) ([]byte, error) {
return fetchRawBlockHeader(ns, keyBlockHeader(blockHash))
}
// BlockInMainChain returns whether a block identified by its hash is in the
// current main chain and if so, whether it has been stake invalidated by the
// next main chain block.
func (s *Store) BlockInMainChain(dbtx walletdb.ReadTx, blockHash *chainhash.Hash) (inMainChain bool, invalidated bool) {
ns := dbtx.ReadBucket(wtxmgrBucketKey)
header := existsBlockHeader(ns, keyBlockHeader(blockHash))
if header == nil {
return false, false
}
_, v := existsBlockRecord(ns, extractBlockHeaderHeight(header))
if v == nil {
return false, false
}
if !bytes.Equal(extractRawBlockRecordHash(v), blockHash[:]) {
return false, false
}
return true, extractRawBlockRecordStakeInvalid(v)
}
// GetBlockMetaForHash returns the BlockMeta for a block specified by its hash.
//
// TODO: This is legacy code now that headers are saved. BlockMeta can be removed.
func (s *Store) GetBlockMetaForHash(ns walletdb.ReadBucket, blockHash *chainhash.Hash) (BlockMeta, error) {
header := ns.NestedReadBucket(bucketHeaders).Get(blockHash[:])
if header == nil {
const str = "block header not found"
return BlockMeta{}, storeError(apperrors.ErrValueNoExists, str, nil)
}
return BlockMeta{
Block: Block{
Hash: *blockHash,
Height: extractBlockHeaderHeight(header),
},
Time: time.Unix(int64(extractBlockHeaderUnixTime(header)), 0),
VoteBits: extractBlockHeaderVoteBits(header),
}, nil
}
// GetMainChainBlockHashes returns block hashes from the main chain, starting at
// startHash, copying as many as possible into the storage slice and returning a
// subslice for the total number of results. If the start hash is not in the