forked from decred/dcrd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
2719 lines (2402 loc) · 94.2 KB
/
validate.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-2016 The btcsuite developers
// Copyright (c) 2015-2017 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"
"fmt"
"math"
"math/big"
"time"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/database"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
)
const (
// MaxSigOpsPerBlock is the maximum number of signature operations
// allowed for a block. This really should be based upon the max
// allowed block size for a network and any votes that might change it,
// however, since it was not updated to be based upon it before
// release, it will require a hard fork and associated vote agenda to
// change it. The original max block size for the protocol was 1MiB,
// so that is what this is based on.
MaxSigOpsPerBlock = 1000000 / 200
// MaxTimeOffsetSeconds is the maximum number of seconds a block time
// is allowed to be ahead of the current time. This is currently 2
// hours.
MaxTimeOffsetSeconds = 2 * 60 * 60
// MinCoinbaseScriptLen is the minimum length a coinbase script can be.
MinCoinbaseScriptLen = 2
// MaxCoinbaseScriptLen is the maximum length a coinbase script can be.
MaxCoinbaseScriptLen = 100
// medianTimeBlocks is the number of previous blocks which should be
// used to calculate the median time used to validate block timestamps.
medianTimeBlocks = 11
// earlyVoteBitsValue is the only value of VoteBits allowed in a block
// header before stake validation height.
earlyVoteBitsValue = 0x0001
)
var (
// zeroHash is the zero value for a chainhash.Hash and is defined as a
// package level variable to avoid the need to create a new instance
// every time a check is needed.
zeroHash = &chainhash.Hash{}
)
// isNullOutpoint determines whether or not a previous transaction output point
// is set.
func isNullOutpoint(outpoint *wire.OutPoint) bool {
if outpoint.Index == math.MaxUint32 &&
outpoint.Hash.IsEqual(zeroHash) &&
outpoint.Tree == wire.TxTreeRegular {
return true
}
return false
}
// isNullFraudProof determines whether or not a previous transaction fraud
// proof is set.
func isNullFraudProof(txIn *wire.TxIn) bool {
switch {
case txIn.BlockHeight != wire.NullBlockHeight:
return false
case txIn.BlockIndex != wire.NullBlockIndex:
return false
}
return true
}
// IsCoinBaseTx determines whether or not a transaction is a coinbase. A
// coinbase is a special transaction created by miners that has no inputs.
// This is represented in the block chain by a transaction with a single input
// that has a previous output transaction index set to the maximum value along
// with a zero hash.
//
// This function only differs from IsCoinBase in that it works with a raw wire
// transaction as opposed to a higher level util transaction.
func IsCoinBaseTx(msgTx *wire.MsgTx) bool {
// A coin base must only have one transaction input.
if len(msgTx.TxIn) != 1 {
return false
}
// The previous output of a coin base must have a max value index and a
// zero hash.
prevOut := &msgTx.TxIn[0].PreviousOutPoint
if prevOut.Index != math.MaxUint32 || !prevOut.Hash.IsEqual(zeroHash) {
return false
}
return true
}
// IsCoinBase determines whether or not a transaction is a coinbase. A
// coinbase is a special transaction created by miners that has no inputs.
// This is represented in the block chain by a transaction with a single input
// that has a previous output transaction index set to the maximum value along
// with a zero hash.
//
// This function only differs from IsCoinBaseTx in that it works with a higher
// level util transaction as opposed to a raw wire transaction.
func IsCoinBase(tx *dcrutil.Tx) bool {
return IsCoinBaseTx(tx.MsgTx())
}
// SequenceLockActive determines if all of the inputs to a given transaction
// have achieved a relative age that surpasses the requirements specified by
// their respective sequence locks as calculated by CalcSequenceLock. A single
// sequence lock is sufficient because the calculated lock selects the minimum
// required time and block height from all of the non-disabled inputs after
// which the transaction can be included.
func SequenceLockActive(lock *SequenceLock, blockHeight int64, medianTime time.Time) bool {
// The transaction is not yet mature if it has not yet reached the
// required minimum time and block height according to its sequence
// locks.
if blockHeight <= lock.MinHeight || medianTime.Unix() <= lock.MinTime {
return false
}
return true
}
// CheckTransactionSanity performs some preliminary checks on a transaction to
// ensure it is sane. These checks are context free.
func CheckTransactionSanity(tx *wire.MsgTx, params *chaincfg.Params) error {
// A transaction must have at least one input.
if len(tx.TxIn) == 0 {
return ruleError(ErrNoTxInputs, "transaction has no inputs")
}
// A transaction must have at least one output.
if len(tx.TxOut) == 0 {
return ruleError(ErrNoTxOutputs, "transaction has no outputs")
}
// A transaction must not exceed the maximum allowed size when
// serialized.
serializedTxSize := tx.SerializeSize()
if serializedTxSize > params.MaxTxSize {
str := fmt.Sprintf("serialized transaction is too big - got "+
"%d, max %d", serializedTxSize, params.MaxTxSize)
return ruleError(ErrTxTooBig, str)
}
// Ensure the transaction amounts are in range. Each transaction
// output must not be negative or more than the max allowed per
// transaction. Also, the total of all outputs must abide by the same
// restrictions. All amounts in a transaction are in a unit value
// known as an atom. One decred is a quantity of atoms as defined by
// the AtomsPerCoin constant.
var totalAtom int64
for _, txOut := range tx.TxOut {
atom := txOut.Value
if atom < 0 {
str := fmt.Sprintf("transaction output has negative "+
"value of %v", atom)
return ruleError(ErrBadTxOutValue, str)
}
if atom > dcrutil.MaxAmount {
str := fmt.Sprintf("transaction output value of %v is "+
"higher than max allowed value of %v", atom,
dcrutil.MaxAmount)
return ruleError(ErrBadTxOutValue, str)
}
// Two's complement int64 overflow guarantees that any overflow
// is detected and reported. This is impossible for Decred,
// but perhaps possible if an alt increases the total money
// supply.
totalAtom += atom
if totalAtom < 0 {
str := fmt.Sprintf("total value of all transaction "+
"outputs exceeds max allowed value of %v",
dcrutil.MaxAmount)
return ruleError(ErrBadTxOutValue, str)
}
if totalAtom > dcrutil.MaxAmount {
str := fmt.Sprintf("total value of all transaction "+
"outputs is %v which is higher than max "+
"allowed value of %v", totalAtom,
dcrutil.MaxAmount)
return ruleError(ErrBadTxOutValue, str)
}
}
isSSGen, _ := stake.IsSSGen(tx)
// Coinbase script length must be between min and max length.
if IsCoinBaseTx(tx) {
// The referenced outpoint should be null.
if !isNullOutpoint(&tx.TxIn[0].PreviousOutPoint) {
str := fmt.Sprintf("coinbase transaction did not use " +
"a null outpoint")
return ruleError(ErrBadCoinbaseOutpoint, str)
}
// The fraud proof should also be null.
if !isNullFraudProof(tx.TxIn[0]) {
str := fmt.Sprintf("coinbase transaction fraud proof " +
"was non-null")
return ruleError(ErrBadCoinbaseFraudProof, str)
}
slen := len(tx.TxIn[0].SignatureScript)
if slen < MinCoinbaseScriptLen || slen > MaxCoinbaseScriptLen {
str := fmt.Sprintf("coinbase transaction script "+
"length of %d is out of range (min: %d, max: "+
"%d)", slen, MinCoinbaseScriptLen,
MaxCoinbaseScriptLen)
return ruleError(ErrBadCoinbaseScriptLen, str)
}
} else if isSSGen {
// Check script length of stake base signature.
slen := len(tx.TxIn[0].SignatureScript)
if slen < MinCoinbaseScriptLen || slen > MaxCoinbaseScriptLen {
str := fmt.Sprintf("stakebase transaction script "+
"length of %d is out of range (min: %d, max: "+
"%d)", slen, MinCoinbaseScriptLen,
MaxCoinbaseScriptLen)
return ruleError(ErrBadStakebaseScriptLen, str)
}
// The script must be set to the one specified by the network.
// Check script length of stake base signature.
if !bytes.Equal(tx.TxIn[0].SignatureScript,
params.StakeBaseSigScript) {
str := fmt.Sprintf("stakebase transaction signature "+
"script was set to disallowed value (got %x, "+
"want %x)", tx.TxIn[0].SignatureScript,
params.StakeBaseSigScript)
return ruleError(ErrBadStakebaseScrVal, str)
}
// The ticket reference hash in an SSGen tx must not be null.
ticketHash := &tx.TxIn[1].PreviousOutPoint
if isNullOutpoint(ticketHash) {
return ruleError(ErrBadTxInput, "ssgen tx ticket input"+
" refers to previous output that is null")
}
} else {
// Previous transaction outputs referenced by the inputs to
// this transaction must not be null except in the case of
// stake bases for SSGen tx.
for _, txIn := range tx.TxIn {
prevOut := &txIn.PreviousOutPoint
if isNullOutpoint(prevOut) {
return ruleError(ErrBadTxInput, "transaction "+
"input refers to previous output that "+
"is null")
}
}
}
// Check for duplicate transaction inputs.
existingTxOut := make(map[wire.OutPoint]struct{})
for _, txIn := range tx.TxIn {
if _, exists := existingTxOut[txIn.PreviousOutPoint]; exists {
return ruleError(ErrDuplicateTxInputs, "transaction "+
"contains duplicate inputs")
}
existingTxOut[txIn.PreviousOutPoint] = struct{}{}
}
return nil
}
// checkProofOfStake checks to see that all new SStx tx in a block are actually
// at the network stake target.
func checkProofOfStake(block *dcrutil.Block, posLimit int64) error {
msgBlock := block.MsgBlock()
for _, staketx := range block.STransactions() {
msgTx := staketx.MsgTx()
if is, _ := stake.IsSStx(msgTx); is {
commitValue := msgTx.TxOut[0].Value
// Check for underflow block sbits.
if commitValue < msgBlock.Header.SBits {
errStr := fmt.Sprintf("Stake tx %v has a "+
"commitment value less than the "+
"minimum stake difficulty specified in"+
" the block (%v)", staketx.Hash(),
msgBlock.Header.SBits)
return ruleError(ErrNotEnoughStake, errStr)
}
// Check if it's above the PoS limit.
if commitValue < posLimit {
errStr := fmt.Sprintf("Stake tx %v has a "+
"commitment value less than the "+
"minimum stake difficulty for the "+
"network (%v)", staketx.Hash(),
posLimit)
return ruleError(ErrStakeBelowMinimum, errStr)
}
}
}
return nil
}
// CheckProofOfStake exports the above func.
func CheckProofOfStake(block *dcrutil.Block, posLimit int64) error {
return checkProofOfStake(block, posLimit)
}
// checkProofOfWork ensures the block header bits which indicate the target
// difficulty is in min/max range and that the block hash is less than the
// target difficulty as claimed.
//
// The flags modify the behavior of this function as follows:
// - BFNoPoWCheck: The check to ensure the block hash is less than the target
// difficulty is not performed.
func checkProofOfWork(header *wire.BlockHeader, powLimit *big.Int, flags BehaviorFlags) error {
// The target difficulty must be larger than zero.
target := CompactToBig(header.Bits)
if target.Sign() <= 0 {
str := fmt.Sprintf("block target difficulty of %064x is too "+
"low", target)
return ruleError(ErrUnexpectedDifficulty, str)
}
// The target difficulty must be less than the maximum allowed.
if target.Cmp(powLimit) > 0 {
str := fmt.Sprintf("block target difficulty of %064x is "+
"higher than max of %064x", target, powLimit)
return ruleError(ErrUnexpectedDifficulty, str)
}
// The block hash must be less than the claimed target unless the flag
// to avoid proof of work checks is set.
if flags&BFNoPoWCheck != BFNoPoWCheck {
// The block hash must be less than the claimed target.
hash := header.BlockHash()
hashNum := HashToBig(&hash)
if hashNum.Cmp(target) > 0 {
str := fmt.Sprintf("block hash of %064x is higher than"+
" expected max of %064x", hashNum, target)
return ruleError(ErrHighHash, str)
}
}
return nil
}
// CheckProofOfWork ensures the block header bits which indicate the target
// difficulty is in min/max range and that the block hash is less than the
// target difficulty as claimed.
func CheckProofOfWork(block *dcrutil.Block, powLimit *big.Int) error {
return checkProofOfWork(&block.MsgBlock().Header, powLimit, BFNone)
}
// checkBlockHeaderSanity performs some preliminary checks on a block header to
// ensure it is sane before continuing with processing. These checks are
// context free.
//
// The flags do not modify the behavior of this function directly, however they
// are needed to pass along to checkProofOfWork.
func checkBlockHeaderSanity(block *dcrutil.Block, timeSource MedianTimeSource, flags BehaviorFlags, chainParams *chaincfg.Params) error {
powLimit := chainParams.PowLimit
posLimit := chainParams.MinimumStakeDiff
header := &block.MsgBlock().Header
// Ensure the proof of work bits in the block header is in min/max
// range and the block hash is less than the target value described by
// the bits.
err := checkProofOfWork(header, powLimit, flags)
if err != nil {
return err
}
// Check to make sure that all newly purchased tickets meet the
// difficulty specified in the block.
err = checkProofOfStake(block, posLimit)
if err != nil {
return err
}
// A block timestamp must not have a greater precision than one second.
// This check is necessary because Go time.Time values support
// nanosecond precision whereas the consensus rules only apply to
// seconds and it's much nicer to deal with standard Go time values
// instead of converting to seconds everywhere.
if !header.Timestamp.Equal(time.Unix(header.Timestamp.Unix(), 0)) {
str := fmt.Sprintf("block timestamp of %v has a higher "+
"precision than one second", header.Timestamp)
return ruleError(ErrInvalidTime, str)
}
// Ensure the block time is not too far in the future.
maxTimestamp := timeSource.AdjustedTime().Add(time.Second *
MaxTimeOffsetSeconds)
if header.Timestamp.After(maxTimestamp) {
str := fmt.Sprintf("block timestamp of %v is too far in the "+
"future", header.Timestamp)
return ruleError(ErrTimeTooNew, str)
}
return nil
}
// checkBlockSanity performs some preliminary checks on a block to ensure it is
// sane before continuing with block processing. These checks are context
// free.
//
// The flags do not modify the behavior of this function directly, however they
// are needed to pass along to checkBlockHeaderSanity.
func checkBlockSanity(block *dcrutil.Block, timeSource MedianTimeSource, flags BehaviorFlags, chainParams *chaincfg.Params) error {
msgBlock := block.MsgBlock()
header := &msgBlock.Header
err := checkBlockHeaderSanity(block, timeSource, flags, chainParams)
if err != nil {
return err
}
// A block must have at least one regular transaction.
numTx := len(msgBlock.Transactions)
if numTx == 0 {
return ruleError(ErrNoTransactions, "block does not contain "+
"any transactions")
}
// A block must not exceed the maximum allowed block payload when
// serialized.
//
// This is a quick and context-free sanity check of the maximum block
// size according to the wire protocol. Even though the wire protocol
// already prevents blocks bigger than this limit, there are other
// methods of receiving a block that might not have been checked
// already. A separate block size is enforced later that takes into
// account the network-specific block size and the results of block
// size votes. Typically that block size is more restrictive than this
// one.
serializedSize := msgBlock.SerializeSize()
if serializedSize > wire.MaxBlockPayload {
str := fmt.Sprintf("serialized block is too big - got %d, "+
"max %d", serializedSize, wire.MaxBlockPayload)
return ruleError(ErrBlockTooBig, str)
}
if msgBlock.Header.Size != uint32(serializedSize) {
str := fmt.Sprintf("serialized block is not size indicated in "+
"header - got %d, expected %d", msgBlock.Header.Size,
serializedSize)
return ruleError(ErrWrongBlockSize, str)
}
// The first transaction in a block's txtreeregular must be a coinbase.
transactions := block.Transactions()
if !IsCoinBaseTx(transactions[0].MsgTx()) {
return ruleError(ErrFirstTxNotCoinbase, "first transaction in "+
"block is not a coinbase")
}
// A block must not have more than one coinbase.
for i, tx := range transactions[1:] {
if IsCoinBaseTx(tx.MsgTx()) {
str := fmt.Sprintf("block contains second coinbase at "+
"index %d", i+1)
return ruleError(ErrMultipleCoinbases, str)
}
}
// Do some preliminary checks on each transaction to ensure they are
// sane before continuing.
for _, tx := range transactions {
msgTx := tx.MsgTx()
txType := stake.DetermineTxType(msgTx)
if txType != stake.TxTypeRegular {
errStr := fmt.Sprintf("found stake tx in regular tx " +
"tree")
return ruleError(ErrStakeTxInRegularTree, errStr)
}
err := CheckTransactionSanity(msgTx, chainParams)
if err != nil {
return err
}
}
totalTickets := 0
totalVotes := 0
totalRevocations := 0
for _, stx := range block.MsgBlock().STransactions {
err := CheckTransactionSanity(stx, chainParams)
if err != nil {
return err
}
txType := stake.DetermineTxType(stx)
if txType == stake.TxTypeRegular {
errStr := fmt.Sprintf("found regular tx in stake tx " +
"tree")
return ruleError(ErrRegTxInStakeTree, errStr)
}
switch txType {
case stake.TxTypeSStx:
totalTickets++
case stake.TxTypeSSGen:
totalVotes++
case stake.TxTypeSSRtx:
totalRevocations++
}
}
if totalTickets != int(block.MsgBlock().Header.FreshStake) {
errStr := fmt.Sprintf("%v tickets found in block, while "+
"header reports %v", totalTickets,
block.MsgBlock().Header.FreshStake)
return ruleError(ErrFreshStakeMismatch, errStr)
}
// Not enough voters on this block.
if block.Height() >= chainParams.StakeValidationHeight &&
totalVotes <= int(chainParams.TicketsPerBlock)/2 {
errStr := fmt.Sprintf("block contained too few votes! %v "+
"votes but %v or more required", totalVotes,
(int(chainParams.TicketsPerBlock)/2)+1)
return ruleError(ErrNotEnoughVotes, errStr)
}
if totalVotes > int(chainParams.TicketsPerBlock) {
errStr := fmt.Sprintf("the number of SSGen tx in block %v "+
"was %v, overflowing the maximum allowed (%v)",
block.Hash(), totalVotes,
int(chainParams.TicketsPerBlock))
return ruleError(ErrTooManyVotes, errStr)
}
if totalVotes != int(block.MsgBlock().Header.Voters) {
errStr := fmt.Sprintf("%v votes found in block, while header "+
"reports %v", totalVotes,
block.MsgBlock().Header.Voters)
return ruleError(ErrVotesMismatch, errStr)
}
if totalRevocations != int(block.MsgBlock().Header.Revocations) {
errStr := fmt.Sprintf("%v revocations found in block, while "+
"header reports %v", totalRevocations,
block.MsgBlock().Header.Revocations)
return ruleError(ErrRevocationsMismatch, errStr)
}
// The number of votes must be the same as the number declared in the
// header. The same is true for tickets and revocations.
// Build merkle tree and ensure the calculated merkle root matches the
// entry in the block header. This also has the effect of caching all
// of the transaction hashes in the block to speed up future hash
// checks. Bitcoind builds the tree here and checks the merkle root
// after the following checks, but there is no reason not to check the
// merkle root matches here.
merkles := BuildMerkleTreeStore(block.Transactions())
calculatedMerkleRoot := merkles[len(merkles)-1]
if !header.MerkleRoot.IsEqual(calculatedMerkleRoot) {
str := fmt.Sprintf("block merkle root is invalid - block "+
"header indicates %v, but calculated value is %v",
header.MerkleRoot, calculatedMerkleRoot)
return ruleError(ErrBadMerkleRoot, str)
}
// Build the stake tx tree merkle root too and check it.
merkleStake := BuildMerkleTreeStore(block.STransactions())
calculatedStakeMerkleRoot := merkleStake[len(merkleStake)-1]
if !header.StakeRoot.IsEqual(calculatedStakeMerkleRoot) {
str := fmt.Sprintf("block stake merkle root is invalid - block"+
" header indicates %v, but calculated value is %v",
header.StakeRoot, calculatedStakeMerkleRoot)
return ruleError(ErrBadMerkleRoot, str)
}
// Check for duplicate transactions. This check will be fairly quick
// since the transaction hashes are already cached due to building the
// merkle tree above.
existingTxHashes := make(map[chainhash.Hash]struct{})
stakeTransactions := block.STransactions()
allTransactions := append(transactions, stakeTransactions...)
for _, tx := range allTransactions {
hash := tx.Hash()
if _, exists := existingTxHashes[*hash]; exists {
str := fmt.Sprintf("block contains duplicate "+
"transaction %v", hash)
return ruleError(ErrDuplicateTx, str)
}
existingTxHashes[*hash] = struct{}{}
}
// The number of signature operations must be less than the maximum
// allowed per block.
totalSigOps := 0
for _, tx := range allTransactions {
msgTx := tx.MsgTx()
// We could potentially overflow the accumulator so check for
// overflow.
lastSigOps := totalSigOps
isSSGen, _ := stake.IsSSGen(msgTx)
isCoinBase := IsCoinBaseTx(msgTx)
totalSigOps += CountSigOps(tx, isCoinBase, isSSGen)
if totalSigOps < lastSigOps || totalSigOps > MaxSigOpsPerBlock {
str := fmt.Sprintf("block contains too many signature "+
"operations - got %v, max %v", totalSigOps,
MaxSigOpsPerBlock)
return ruleError(ErrTooManySigOps, str)
}
}
// Blocks before stake validation height may only have 0x0001 as their
// VoteBits in the header.
if int64(header.Height) < chainParams.StakeValidationHeight {
if header.VoteBits != earlyVoteBitsValue {
str := fmt.Sprintf("pre stake validation height "+
"block %v contained an invalid votebits value"+
" (expected %v, got %v)", block.Hash(),
earlyVoteBitsValue, header.VoteBits)
return ruleError(ErrInvalidEarlyVoteBits, str)
}
}
return nil
}
// CheckBlockSanity performs some preliminary checks on a block to ensure it is
// sane before continuing with block processing. These checks are context
// free.
func CheckBlockSanity(block *dcrutil.Block, timeSource MedianTimeSource, chainParams *chaincfg.Params) error {
return checkBlockSanity(block, timeSource, BFNone, chainParams)
}
// CheckWorklessBlockSanity performs some preliminary checks on a block to
// ensure it is sane before continuing with block processing. These checks are
// context free.
func CheckWorklessBlockSanity(block *dcrutil.Block, timeSource MedianTimeSource, chainParams *chaincfg.Params) error {
return checkBlockSanity(block, timeSource, BFNoPoWCheck, chainParams)
}
// checkBlockHeaderContext peforms several validation checks on the block
// header which depend on its position within the block chain.
//
// The flags modify the behavior of this function as follows:
// - BFFastAdd: All checks except those involving comparing the header against
// the checkpoints are not performed.
//
// This function MUST be called with the chain state lock held (for writes).
func (b *BlockChain) checkBlockHeaderContext(header *wire.BlockHeader, prevNode *blockNode, flags BehaviorFlags) error {
// The genesis block is valid by definition.
if prevNode == nil {
return nil
}
fastAdd := flags&BFFastAdd == BFFastAdd
if !fastAdd {
// Ensure the difficulty specified in the block header matches
// the calculated difficulty based on the previous block and
// difficulty retarget rules.
expDiff, err := b.calcNextRequiredDifficulty(prevNode,
header.Timestamp)
if err != nil {
return err
}
blockDifficulty := header.Bits
if blockDifficulty != expDiff {
str := fmt.Sprintf("block difficulty of %d is not the"+
" expected "+"value of %d", blockDifficulty,
expDiff)
return ruleError(ErrUnexpectedDifficulty, str)
}
// Ensure the timestamp for the block header is after the
// median time of the last several blocks (medianTimeBlocks).
medianTime, err := b.calcPastMedianTime(prevNode)
if err != nil {
log.Errorf("calcPastMedianTime: %v", err)
return err
}
if !header.Timestamp.After(medianTime) {
str := "block timestamp of %v is not after expected %v"
str = fmt.Sprintf(str, header.Timestamp, medianTime)
return ruleError(ErrTimeTooOld, str)
}
}
// The height of this block is one more than the referenced previous
// block.
blockHeight := prevNode.height + 1
// Ensure chain matches up to predetermined checkpoints.
blockHash := header.BlockHash()
if !b.verifyCheckpoint(blockHeight, &blockHash) {
str := fmt.Sprintf("block at height %d does not match "+
"checkpoint hash", blockHeight)
return ruleError(ErrBadCheckpoint, str)
}
// Find the previous checkpoint and prevent blocks which fork the main
// chain before it. This prevents storage of new, otherwise valid,
// blocks which build off of old blocks that are likely at a much
// easier difficulty and therefore could be used to waste cache and
// disk space.
checkpointBlock, err := b.findPreviousCheckpoint()
if err != nil {
return err
}
if checkpointBlock != nil && blockHeight < checkpointBlock.Height() {
str := fmt.Sprintf("block at height %d forks the main chain "+
"before the previous checkpoint at height %d",
blockHeight, checkpointBlock.Height())
return ruleError(ErrForkTooOld, str)
}
if !fastAdd {
// Reject version 5 blocks for networks other than the main
// network once a majority of the network has upgraded.
if b.chainParams.Net != wire.MainNet && header.Version < 6 &&
b.isMajorityVersion(6, prevNode,
b.chainParams.BlockRejectNumRequired) {
str := "new blocks with version %d are no longer valid"
str = fmt.Sprintf(str, header.Version)
return ruleError(ErrBlockVersionTooOld, str)
}
// Reject version 4 blocks once a majority of the network has
// upgraded.
if header.Version < 5 && b.isMajorityVersion(5, prevNode,
b.chainParams.BlockRejectNumRequired) {
str := "new blocks with version %d are no longer valid"
str = fmt.Sprintf(str, header.Version)
return ruleError(ErrBlockVersionTooOld, str)
}
// Reject version 3 blocks once a majority of the network has
// upgraded.
if header.Version < 4 && b.isMajorityVersion(4, prevNode,
b.chainParams.BlockRejectNumRequired) {
str := "new blocks with version %d are no longer valid"
str = fmt.Sprintf(str, header.Version)
return ruleError(ErrBlockVersionTooOld, str)
}
// Reject version 2 blocks once a majority of the network has
// upgraded.
if header.Version < 3 && b.isMajorityVersion(3, prevNode,
b.chainParams.BlockRejectNumRequired) {
str := "new blocks with version %d are no longer valid"
str = fmt.Sprintf(str, header.Version)
return ruleError(ErrBlockVersionTooOld, str)
}
// Reject version 1 blocks once a majority of the network has
// upgraded.
if header.Version < 2 && b.isMajorityVersion(2, prevNode,
b.chainParams.BlockRejectNumRequired) {
str := "new blocks with version %d are no longer valid"
str = fmt.Sprintf(str, header.Version)
return ruleError(ErrBlockVersionTooOld, str)
}
// Enforce the stake version in the header once a majority of
// the network has upgraded to version 3 blocks.
if header.Version >= 3 && b.isMajorityVersion(3, prevNode,
b.chainParams.BlockEnforceNumRequired) {
expectedStakeVer := b.calcStakeVersion(prevNode)
if header.StakeVersion != expectedStakeVer {
str := fmt.Sprintf("block stake version of %d "+
"is not the expected version of %d",
header.StakeVersion, expectedStakeVer)
return ruleError(ErrBadStakeVersion, str)
}
}
}
return nil
}
// checkDupTxs ensures blocks do not contain duplicate transactions which
// 'overwrite' older transactions that are not fully spent. This prevents an
// attack where a coinbase and all of its dependent transactions could be
// duplicated to effectively revert the overwritten transactions to a single
// confirmation thereby making them vulnerable to a double spend.
//
// For more details, see https://en.bitcoin.it/wiki/BIP_0030 and
// http://r6.ca/blog/20120206T005236Z.html.
//
// Decred: Check the stake transactions to make sure they don't have this txid
// too.
func (b *BlockChain) checkDupTxs(txSet []*dcrutil.Tx, view *UtxoViewpoint) error {
if !chaincfg.CheckForDuplicateHashes {
return nil
}
// Fetch utxo details for all of the transactions in this block.
// Typically, there will not be any utxos for any of the transactions.
fetchSet := make(map[chainhash.Hash]struct{})
for _, tx := range txSet {
fetchSet[*tx.Hash()] = struct{}{}
}
err := view.fetchUtxos(b.db, fetchSet)
if err != nil {
return err
}
// Duplicate transactions are only allowed if the previous transaction
// is fully spent.
for _, tx := range txSet {
txEntry := view.LookupEntry(tx.Hash())
if txEntry != nil && !txEntry.IsFullySpent() {
str := fmt.Sprintf("tried to overwrite transaction %v "+
"at block height %d that is not fully spent",
tx.Hash(), txEntry.BlockHeight())
return ruleError(ErrOverwriteTx, str)
}
}
return nil
}
// CheckBlockStakeSanity performs a series of checks on a block to ensure that
// the information from the block's header about stake is sane. For instance,
// the number of SSGen tx must be equal to voters.
// TODO: We can consider breaking this into two functions and making some of
// these checks go through in processBlock, however if a block has demonstrable
// PoW it seems unlikely that it will have stake errors (because the miner is
// then just wasting hash power).
func (b *BlockChain) CheckBlockStakeSanity(stakeValidationHeight int64, node *blockNode, block *dcrutil.Block, parent *dcrutil.Block, chainParams *chaincfg.Params) error {
// Setup variables.
stakeTransactions := block.STransactions()
msgBlock := block.MsgBlock()
sbits := msgBlock.Header.SBits
blockHash := block.Hash()
prevBlockHash := &msgBlock.Header.PrevBlock
poolSize := int(msgBlock.Header.PoolSize)
finalState := node.header.FinalState
ticketsPerBlock := int(b.chainParams.TicketsPerBlock)
txTreeRegularValid := dcrutil.IsFlagSet16(msgBlock.Header.VoteBits,
dcrutil.BlockValid)
stakeEnabledHeight := chainParams.StakeEnabledHeight
parentStakeNode, err := b.fetchStakeNode(node.parent)
if err != nil {
return err
}
// Do some preliminary checks on each stake transaction to ensure they
// are sane before continuing.
ssGens := 0 // Votes
ssRtxs := 0 // Revocations
for i, tx := range stakeTransactions {
msgTx := tx.MsgTx()
isSSGen, _ := stake.IsSSGen(msgTx)
isSSRtx, _ := stake.IsSSRtx(msgTx)
if isSSGen {
ssGens++
}
if isSSRtx {
ssRtxs++
}
// If we haven't reached the point in which staking is enabled,
// there should be absolutely no SSGen or SSRtx transactions.
if (isSSGen && (block.Height() < stakeEnabledHeight)) ||
(isSSRtx && (block.Height() < stakeEnabledHeight)) {
errStr := fmt.Sprintf("block contained SSGen or SSRtx "+
"transaction at idx %v, which was before stake"+
" voting was enabled; block height %v, stake "+
"enabled height %v", i, block.Height(),
stakeEnabledHeight)
return ruleError(ErrInvalidEarlyStakeTx, errStr)
}
}
// Make sure we have no votes or revocations if stake validation is not
// enabled.
containsVotes := ssGens > 0
containsRevocations := ssRtxs > 0
if node.height < chainParams.StakeValidationHeight &&
(containsVotes || containsRevocations) {
errStr := fmt.Sprintf("block contained votes or revocations " +
"before the stake validation height")
return ruleError(ErrInvalidEarlyStakeTx, errStr)
}
// Check the stake difficulty.
calcSBits, err := b.calcNextRequiredStakeDifficulty(node.parent)
if err != nil {
errStr := fmt.Sprintf("couldn't calculate stake difficulty "+
"for block node %v: %v", node.hash, err)
return ruleError(ErrUnexpectedDifficulty, errStr)
}
if block.MsgBlock().Header.SBits != calcSBits {
errStr := fmt.Sprintf("block had unexpected stake difficulty "+
"(%v given, %v expected)",
block.MsgBlock().Header.SBits, calcSBits)
return ruleError(ErrUnexpectedDifficulty, errStr)
}
// --------------------------------------------------------------------
// SStx Tx Handling
// --------------------------------------------------------------------
// PER SSTX
// 1. Check to make sure that the amount committed with the SStx is
// equal to the target of the last block (sBits).
// 2. Ensure the the number of SStx tx in the block is the same as
// FreshStake in the header.
// PER BLOCK
// 3. Check to make sure we haven't exceeded max number of new SStx.
numSStxTx := 0
for _, staketx := range stakeTransactions {
msgTx := staketx.MsgTx()
if is, _ := stake.IsSStx(msgTx); is {
numSStxTx++
// 1. Make sure that we're committing enough coins.
// Checked already when we check stake difficulty, so
// may not be needed.
if msgTx.TxOut[0].Value < sbits {
txHash := staketx.Hash()
errStr := fmt.Sprintf("Error in stake "+
"consensus: the amount committed in "+
"SStx %v was less than the sBits "+
"value %v", txHash, sbits)
return ruleError(ErrNotEnoughStake, errStr)
}
}
}
// 2. Ensure the the number of SStx tx in the block is the same as
// FreshStake in the header. This is also tested for in
// checkBlockSanity.
// 3. Check to make sure we haven't exceeded max number of new SStx.
// May not need this check, as the above one should fail if you
// overflow uint8.
if numSStxTx > int(chainParams.MaxFreshStakePerBlock) {
errStr := fmt.Sprintf("Error in stake consensus: the number "+
"of SStx tx "+"in block %v was %v, overflowing the "+
"maximum allowed (255)", blockHash, numSStxTx)
return ruleError(ErrTooManySStxs, errStr)
}
// Break if the stake system is otherwise disabled.
if block.Height() < stakeValidationHeight {
stakeTxSum := numSStxTx
// Check and make sure we're only including SStx in the stake
// tx tree.
if stakeTxSum != len(stakeTransactions) {
errStr := fmt.Sprintf("Error in stake consensus: the "+
"number of stake tx in block %v was %v, "+
"however we expected %v", block.Hash(),
stakeTxSum, len(stakeTransactions))
return ruleError(ErrInvalidEarlyStakeTx, errStr)
}
// Check the ticket pool size.
if parentStakeNode.PoolSize() != poolSize {
errStr := fmt.Sprintf("Error in stake consensus: the "+
"poolsize in block %v was %v, however we "+
"expected %v", node.hash, poolSize,
parentStakeNode.PoolSize())
return ruleError(ErrPoolSize, errStr)
}
return nil
}
// -------------------------------------------------------------------
// General Purpose Checks
// -------------------------------------------------------------------
// 1. Check that we have a majority vote of potential voters.