1 // Copyright (c) 2013-2017 The btcsuite developers
2 // Use of this source code is governed by an ISC
3 // license that can be found in the LICENSE file.
14 "github.com/btcsuite/btcd/chaincfg"
15 "github.com/btcsuite/btcd/chaincfg/chainhash"
16 "github.com/btcsuite/btcd/txscript"
17 "github.com/btcsuite/btcd/wire"
18 "github.com/btcsuite/btcutil"
22 // MaxTimeOffsetSeconds is the maximum number of seconds a block time
23 // is allowed to be ahead of the current time. This is currently 2
25 MaxTimeOffsetSeconds = 2 * 60 * 60
27 // MinCoinbaseScriptLen is the minimum length a coinbase script can be.
28 MinCoinbaseScriptLen = 2
30 // MaxCoinbaseScriptLen is the maximum length a coinbase script can be.
31 MaxCoinbaseScriptLen = 100
33 // medianTimeBlocks is the number of previous blocks which should be
34 // used to calculate the median time used to validate block timestamps.
37 // serializedHeightVersion is the block version which changed block
38 // coinbases to start with the serialized block height.
39 serializedHeightVersion = 2
41 // baseSubsidy is the starting subsidy amount for mined blocks. This
42 // value is halved every SubsidyHalvingInterval blocks.
43 baseSubsidy = 50 * btcutil.SatoshiPerBitcoin
47 // zeroHash is the zero value for a chainhash.Hash and is defined as
48 // a package level variable to avoid the need to create a new instance
49 // every time a check is needed.
50 zeroHash = &chainhash.Hash{}
52 // block91842Hash is one of the two nodes which violate the rules
53 // set forth in BIP0030. It is defined as a package level variable to
54 // avoid the need to create a new instance every time a check is needed.
55 block91842Hash = newHashFromStr("00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")
57 // block91880Hash is one of the two nodes which violate the rules
58 // set forth in BIP0030. It is defined as a package level variable to
59 // avoid the need to create a new instance every time a check is needed.
60 block91880Hash = newHashFromStr("00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")
63 // isNullOutpoint determines whether or not a previous transaction output point
65 func isNullOutpoint(outpoint *wire.OutPoint) bool {
66 if outpoint.Index == math.MaxUint32 && outpoint.Hash.IsEqual(zeroHash) {
72 // ShouldHaveSerializedBlockHeight determines if a block should have a
73 // serialized block height embedded within the scriptSig of its
74 // coinbase transaction. Judgement is based on the block version in the block
75 // header. Blocks with version 2 and above satisfy this criteria. See BIP0034
76 // for further information.
77 func ShouldHaveSerializedBlockHeight(header *wire.BlockHeader) bool {
78 return header.Version >= serializedHeightVersion
81 // IsCoinBaseTx determines whether or not a transaction is a coinbase. A coinbase
82 // is a special transaction created by miners that has no inputs. This is
83 // represented in the block chain by a transaction with a single input that has
84 // a previous output transaction index set to the maximum value along with a
87 // This function only differs from IsCoinBase in that it works with a raw wire
88 // transaction as opposed to a higher level util transaction.
89 func IsCoinBaseTx(msgTx *wire.MsgTx) bool {
90 // A coin base must only have one transaction input.
91 if len(msgTx.TxIn) != 1 {
95 // The previous output of a coin base must have a max value index and
97 prevOut := &msgTx.TxIn[0].PreviousOutPoint
98 if prevOut.Index != math.MaxUint32 || !prevOut.Hash.IsEqual(zeroHash) {
105 // IsCoinBase determines whether or not a transaction is a coinbase. A coinbase
106 // is a special transaction created by miners that has no inputs. This is
107 // represented in the block chain by a transaction with a single input that has
108 // a previous output transaction index set to the maximum value along with a
111 // This function only differs from IsCoinBaseTx in that it works with a higher
112 // level util transaction as opposed to a raw wire transaction.
113 func IsCoinBase(tx *btcutil.Tx) bool {
114 return IsCoinBaseTx(tx.MsgTx())
117 // SequenceLockActive determines if a transaction's sequence locks have been
118 // met, meaning that all the inputs of a given transaction have reached a
119 // height or time sufficient for their relative lock-time maturity.
120 func SequenceLockActive(sequenceLock *SequenceLock, blockHeight int32,
121 medianTimePast time.Time) bool {
123 // If either the seconds, or height relative-lock time has not yet
124 // reached, then the transaction is not yet mature according to its
126 if sequenceLock.Seconds >= medianTimePast.Unix() ||
127 sequenceLock.BlockHeight >= blockHeight {
134 // IsFinalizedTransaction determines whether or not a transaction is finalized.
135 func IsFinalizedTransaction(tx *btcutil.Tx, blockHeight int32, blockTime time.Time) bool {
138 // Lock time of zero means the transaction is finalized.
139 lockTime := msgTx.LockTime
144 // The lock time field of a transaction is either a block height at
145 // which the transaction is finalized or a timestamp depending on if the
146 // value is before the txscript.LockTimeThreshold. When it is under the
147 // threshold it is a block height.
148 blockTimeOrHeight := int64(0)
149 if lockTime < txscript.LockTimeThreshold {
150 blockTimeOrHeight = int64(blockHeight)
152 blockTimeOrHeight = blockTime.Unix()
154 if int64(lockTime) < blockTimeOrHeight {
158 // At this point, the transaction's lock time hasn't occurred yet, but
159 // the transaction might still be finalized if the sequence number
160 // for all transaction inputs is maxed out.
161 for _, txIn := range msgTx.TxIn {
162 if txIn.Sequence != math.MaxUint32 {
169 // isBIP0030Node returns whether or not the passed node represents one of the
170 // two blocks that violate the BIP0030 rule which prevents transactions from
171 // overwriting old ones.
172 func isBIP0030Node(node *blockNode) bool {
173 if node.height == 91842 && node.hash.IsEqual(block91842Hash) {
177 if node.height == 91880 && node.hash.IsEqual(block91880Hash) {
184 // CalcBlockSubsidy returns the subsidy amount a block at the provided height
185 // should have. This is mainly used for determining how much the coinbase for
186 // newly generated blocks awards as well as validating the coinbase for blocks
187 // has the expected value.
189 // The subsidy is halved every SubsidyReductionInterval blocks. Mathematically
190 // this is: baseSubsidy / 2^(height/SubsidyReductionInterval)
192 // At the target block generation rate for the main network, this is
193 // approximately every 4 years.
194 func CalcBlockSubsidy(height int32, chainParams *chaincfg.Params) int64 {
195 if chainParams.SubsidyReductionInterval == 0 {
199 // Equivalent to: baseSubsidy / 2^(height/subsidyHalvingInterval)
200 return baseSubsidy >> uint(height/chainParams.SubsidyReductionInterval)
203 // CheckTransactionSanity performs some preliminary checks on a transaction to
204 // ensure it is sane. These checks are context free.
205 func CheckTransactionSanity(tx *btcutil.Tx) error {
206 // A transaction must have at least one input.
208 if len(msgTx.TxIn) == 0 {
209 return ruleError(ErrNoTxInputs, "transaction has no inputs")
212 // A transaction must have at least one output.
213 if len(msgTx.TxOut) == 0 {
214 return ruleError(ErrNoTxOutputs, "transaction has no outputs")
217 // A transaction must not exceed the maximum allowed block payload when
219 serializedTxSize := tx.MsgTx().SerializeSizeStripped()
220 if serializedTxSize > MaxBlockBaseSize {
221 str := fmt.Sprintf("serialized transaction is too big - got "+
222 "%d, max %d", serializedTxSize, MaxBlockBaseSize)
223 return ruleError(ErrTxTooBig, str)
226 // Ensure the transaction amounts are in range. Each transaction
227 // output must not be negative or more than the max allowed per
228 // transaction. Also, the total of all outputs must abide by the same
229 // restrictions. All amounts in a transaction are in a unit value known
230 // as a satoshi. One bitcoin is a quantity of satoshi as defined by the
231 // SatoshiPerBitcoin constant.
232 var totalSatoshi int64
233 for _, txOut := range msgTx.TxOut {
234 satoshi := txOut.Value
236 str := fmt.Sprintf("transaction output has negative "+
237 "value of %v", satoshi)
238 return ruleError(ErrBadTxOutValue, str)
240 if satoshi > btcutil.MaxSatoshi {
241 str := fmt.Sprintf("transaction output value of %v is "+
242 "higher than max allowed value of %v", satoshi,
244 return ruleError(ErrBadTxOutValue, str)
247 // Two's complement int64 overflow guarantees that any overflow
248 // is detected and reported. This is impossible for Bitcoin, but
249 // perhaps possible if an alt increases the total money supply.
250 totalSatoshi += satoshi
251 if totalSatoshi < 0 {
252 str := fmt.Sprintf("total value of all transaction "+
253 "outputs exceeds max allowed value of %v",
255 return ruleError(ErrBadTxOutValue, str)
257 if totalSatoshi > btcutil.MaxSatoshi {
258 str := fmt.Sprintf("total value of all transaction "+
259 "outputs is %v which is higher than max "+
260 "allowed value of %v", totalSatoshi,
262 return ruleError(ErrBadTxOutValue, str)
266 // Check for duplicate transaction inputs.
267 existingTxOut := make(map[wire.OutPoint]struct{})
268 for _, txIn := range msgTx.TxIn {
269 if _, exists := existingTxOut[txIn.PreviousOutPoint]; exists {
270 return ruleError(ErrDuplicateTxInputs, "transaction "+
271 "contains duplicate inputs")
273 existingTxOut[txIn.PreviousOutPoint] = struct{}{}
276 // Coinbase script length must be between min and max length.
278 slen := len(msgTx.TxIn[0].SignatureScript)
279 if slen < MinCoinbaseScriptLen || slen > MaxCoinbaseScriptLen {
280 str := fmt.Sprintf("coinbase transaction script length "+
281 "of %d is out of range (min: %d, max: %d)",
282 slen, MinCoinbaseScriptLen, MaxCoinbaseScriptLen)
283 return ruleError(ErrBadCoinbaseScriptLen, str)
286 // Previous transaction outputs referenced by the inputs to this
287 // transaction must not be null.
288 for _, txIn := range msgTx.TxIn {
289 prevOut := &txIn.PreviousOutPoint
290 if isNullOutpoint(prevOut) {
291 return ruleError(ErrBadTxInput, "transaction "+
292 "input refers to previous output that "+
301 // checkProofOfWork ensures the block header bits which indicate the target
302 // difficulty is in min/max range and that the block hash is less than the
303 // target difficulty as claimed.
305 // The flags modify the behavior of this function as follows:
306 // - BFNoPoWCheck: The check to ensure the block hash is less than the target
307 // difficulty is not performed.
308 func checkProofOfWork(header *wire.BlockHeader, powLimit *big.Int, flags BehaviorFlags) error {
309 // The target difficulty must be larger than zero.
310 target := CompactToBig(header.Bits)
311 if target.Sign() <= 0 {
312 str := fmt.Sprintf("block target difficulty of %064x is too low",
314 return ruleError(ErrUnexpectedDifficulty, str)
317 // The target difficulty must be less than the maximum allowed.
318 if target.Cmp(powLimit) > 0 {
319 str := fmt.Sprintf("block target difficulty of %064x is "+
320 "higher than max of %064x", target, powLimit)
321 return ruleError(ErrUnexpectedDifficulty, str)
324 // The block hash must be less than the claimed target unless the flag
325 // to avoid proof of work checks is set.
326 if flags&BFNoPoWCheck != BFNoPoWCheck {
327 // The block hash must be less than the claimed target.
328 hash := header.BlockHash()
329 hashNum := HashToBig(&hash)
330 if hashNum.Cmp(target) > 0 {
331 str := fmt.Sprintf("block hash of %064x is higher than "+
332 "expected max of %064x", hashNum, target)
333 return ruleError(ErrHighHash, str)
340 // CheckProofOfWork ensures the block header bits which indicate the target
341 // difficulty is in min/max range and that the block hash is less than the
342 // target difficulty as claimed.
343 func CheckProofOfWork(block *btcutil.Block, powLimit *big.Int) error {
344 return checkProofOfWork(&block.MsgBlock().Header, powLimit, BFNone)
347 // CountSigOps returns the number of signature operations for all transaction
348 // input and output scripts in the provided transaction. This uses the
349 // quicker, but imprecise, signature operation counting mechanism from
351 func CountSigOps(tx *btcutil.Tx) int {
354 // Accumulate the number of signature operations in all transaction
357 for _, txIn := range msgTx.TxIn {
358 numSigOps := txscript.GetSigOpCount(txIn.SignatureScript)
359 totalSigOps += numSigOps
362 // Accumulate the number of signature operations in all transaction
364 for _, txOut := range msgTx.TxOut {
365 numSigOps := txscript.GetSigOpCount(txOut.PkScript)
366 totalSigOps += numSigOps
372 // CountP2SHSigOps returns the number of signature operations for all input
373 // transactions which are of the pay-to-script-hash type. This uses the
374 // precise, signature operation counting mechanism from the script engine which
375 // requires access to the input transaction scripts.
376 func CountP2SHSigOps(tx *btcutil.Tx, isCoinBaseTx bool, utxoView *UtxoViewpoint) (int, error) {
377 // Coinbase transactions have no interesting inputs.
382 // Accumulate the number of signature operations in all transaction
386 for txInIndex, txIn := range msgTx.TxIn {
387 // Ensure the referenced input transaction is available.
388 originTxHash := &txIn.PreviousOutPoint.Hash
389 originTxIndex := txIn.PreviousOutPoint.Index
390 txEntry := utxoView.LookupEntry(originTxHash)
391 if txEntry == nil || txEntry.IsOutputSpent(originTxIndex) {
392 str := fmt.Sprintf("output %v referenced from "+
393 "transaction %s:%d either does not exist or "+
394 "has already been spent", txIn.PreviousOutPoint,
395 tx.Hash(), txInIndex)
396 return 0, ruleError(ErrMissingTxOut, str)
399 // We're only interested in pay-to-script-hash types, so skip
400 // this input if it's not one.
401 pkScript := txEntry.PkScriptByIndex(originTxIndex)
402 if !txscript.IsPayToScriptHash(pkScript) {
406 // Count the precise number of signature operations in the
407 // referenced public key script.
408 sigScript := txIn.SignatureScript
409 numSigOps := txscript.GetPreciseSigOpCount(sigScript, pkScript,
412 // We could potentially overflow the accumulator so check for
414 lastSigOps := totalSigOps
415 totalSigOps += numSigOps
416 if totalSigOps < lastSigOps {
417 str := fmt.Sprintf("the public key script from output "+
418 "%v contains too many signature operations - "+
419 "overflow", txIn.PreviousOutPoint)
420 return 0, ruleError(ErrTooManySigOps, str)
424 return totalSigOps, nil
427 // checkBlockHeaderSanity performs some preliminary checks on a block header to
428 // ensure it is sane before continuing with processing. These checks are
431 // The flags do not modify the behavior of this function directly, however they
432 // are needed to pass along to checkProofOfWork.
433 func checkBlockHeaderSanity(header *wire.BlockHeader, powLimit *big.Int, timeSource MedianTimeSource, flags BehaviorFlags) error {
434 // Ensure the proof of work bits in the block header is in min/max range
435 // and the block hash is less than the target value described by the
437 err := checkProofOfWork(header, powLimit, flags)
442 // A block timestamp must not have a greater precision than one second.
443 // This check is necessary because Go time.Time values support
444 // nanosecond precision whereas the consensus rules only apply to
445 // seconds and it's much nicer to deal with standard Go time values
446 // instead of converting to seconds everywhere.
447 if !header.Timestamp.Equal(time.Unix(header.Timestamp.Unix(), 0)) {
448 str := fmt.Sprintf("block timestamp of %v has a higher "+
449 "precision than one second", header.Timestamp)
450 return ruleError(ErrInvalidTime, str)
453 // Ensure the block time is not too far in the future.
454 maxTimestamp := timeSource.AdjustedTime().Add(time.Second *
455 MaxTimeOffsetSeconds)
456 if header.Timestamp.After(maxTimestamp) {
457 str := fmt.Sprintf("block timestamp of %v is too far in the "+
458 "future", header.Timestamp)
459 return ruleError(ErrTimeTooNew, str)
465 // checkBlockSanity performs some preliminary checks on a block to ensure it is
466 // sane before continuing with block processing. These checks are context free.
468 // The flags do not modify the behavior of this function directly, however they
469 // are needed to pass along to checkBlockHeaderSanity.
470 func checkBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource, flags BehaviorFlags) error {
471 msgBlock := block.MsgBlock()
472 header := &msgBlock.Header
473 err := checkBlockHeaderSanity(header, powLimit, timeSource, flags)
478 // A block must have at least one transaction.
479 numTx := len(msgBlock.Transactions)
481 return ruleError(ErrNoTransactions, "block does not contain "+
485 // A block must not have more transactions than the max block payload.
486 if numTx > wire.MaxBlockPayload {
487 str := fmt.Sprintf("block contains too many transactions - "+
488 "got %d, max %d", numTx, wire.MaxBlockPayload)
489 return ruleError(ErrTooManyTransactions, str)
492 // A block must not exceed the maximum allowed block payload when
494 serializedSize := msgBlock.SerializeSizeStripped()
495 if serializedSize > MaxBlockBaseSize {
496 str := fmt.Sprintf("serialized block is too big - got %d, "+
497 "max %d", serializedSize, MaxBlockBaseSize)
498 return ruleError(ErrBlockTooBig, str)
501 // The first transaction in a block must be a coinbase.
502 transactions := block.Transactions()
503 if !IsCoinBase(transactions[0]) {
504 return ruleError(ErrFirstTxNotCoinbase, "first transaction in "+
505 "block is not a coinbase")
508 // A block must not have more than one coinbase.
509 for i, tx := range transactions[1:] {
511 str := fmt.Sprintf("block contains second coinbase at "+
513 return ruleError(ErrMultipleCoinbases, str)
517 // Do some preliminary checks on each transaction to ensure they are
518 // sane before continuing.
519 for _, tx := range transactions {
520 err := CheckTransactionSanity(tx)
526 // Build merkle tree and ensure the calculated merkle root matches the
527 // entry in the block header. This also has the effect of caching all
528 // of the transaction hashes in the block to speed up future hash
529 // checks. Bitcoind builds the tree here and checks the merkle root
530 // after the following checks, but there is no reason not to check the
531 // merkle root matches here.
532 merkles := BuildMerkleTreeStore(block.Transactions(), false)
533 calculatedMerkleRoot := merkles[len(merkles)-1]
534 if !header.MerkleRoot.IsEqual(calculatedMerkleRoot) {
535 str := fmt.Sprintf("block merkle root is invalid - block "+
536 "header indicates %v, but calculated value is %v",
537 header.MerkleRoot, calculatedMerkleRoot)
538 return ruleError(ErrBadMerkleRoot, str)
541 // Check for duplicate transactions. This check will be fairly quick
542 // since the transaction hashes are already cached due to building the
543 // merkle tree above.
544 existingTxHashes := make(map[chainhash.Hash]struct{})
545 for _, tx := range transactions {
547 if _, exists := existingTxHashes[*hash]; exists {
548 str := fmt.Sprintf("block contains duplicate "+
549 "transaction %v", hash)
550 return ruleError(ErrDuplicateTx, str)
552 existingTxHashes[*hash] = struct{}{}
555 // The number of signature operations must be less than the maximum
556 // allowed per block.
558 for _, tx := range transactions {
559 // We could potentially overflow the accumulator so check for
561 lastSigOps := totalSigOps
562 totalSigOps += (CountSigOps(tx) * WitnessScaleFactor)
563 if totalSigOps < lastSigOps || totalSigOps > MaxBlockSigOpsCost {
564 str := fmt.Sprintf("block contains too many signature "+
565 "operations - got %v, max %v", totalSigOps,
567 return ruleError(ErrTooManySigOps, str)
574 // CheckBlockSanity performs some preliminary checks on a block to ensure it is
575 // sane before continuing with block processing. These checks are context free.
576 func CheckBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource) error {
577 return checkBlockSanity(block, powLimit, timeSource, BFNone)
580 // ExtractCoinbaseHeight attempts to extract the height of the block from the
581 // scriptSig of a coinbase transaction. Coinbase heights are only present in
582 // blocks of version 2 or later. This was added as part of BIP0034.
583 func ExtractCoinbaseHeight(coinbaseTx *btcutil.Tx) (int32, error) {
584 sigScript := coinbaseTx.MsgTx().TxIn[0].SignatureScript
585 if len(sigScript) < 1 {
586 str := "the coinbase signature script for blocks of " +
587 "version %d or greater must start with the " +
588 "length of the serialized block height"
589 str = fmt.Sprintf(str, serializedHeightVersion)
590 return 0, ruleError(ErrMissingCoinbaseHeight, str)
593 // Detect the case when the block height is a small integer encoded with
595 opcode := int(sigScript[0])
596 if opcode == txscript.OP_0 {
599 if opcode >= txscript.OP_1 && opcode <= txscript.OP_16 {
600 return int32(opcode - (txscript.OP_1 - 1)), nil
603 // Otherwise, the opcode is the length of the following bytes which
604 // encode in the block height.
605 serializedLen := int(sigScript[0])
606 if len(sigScript[1:]) < serializedLen {
607 str := "the coinbase signature script for blocks of " +
608 "version %d or greater must start with the " +
609 "serialized block height"
610 str = fmt.Sprintf(str, serializedLen)
611 return 0, ruleError(ErrMissingCoinbaseHeight, str)
614 serializedHeightBytes := make([]byte, 8)
615 copy(serializedHeightBytes, sigScript[1:serializedLen+1])
616 serializedHeight := binary.LittleEndian.Uint64(serializedHeightBytes)
618 return int32(serializedHeight), nil
621 // checkSerializedHeight checks if the signature script in the passed
622 // transaction starts with the serialized block height of wantHeight.
623 func checkSerializedHeight(coinbaseTx *btcutil.Tx, wantHeight int32) error {
624 serializedHeight, err := ExtractCoinbaseHeight(coinbaseTx)
629 if serializedHeight != wantHeight {
630 str := fmt.Sprintf("the coinbase signature script serialized "+
631 "block height is %d when %d was expected",
632 serializedHeight, wantHeight)
633 return ruleError(ErrBadCoinbaseHeight, str)
638 // checkBlockHeaderContext performs several validation checks on the block header
639 // which depend on its position within the block chain.
641 // The flags modify the behavior of this function as follows:
642 // - BFFastAdd: All checks except those involving comparing the header against
643 // the checkpoints are not performed.
645 // This function MUST be called with the chain state lock held (for writes).
646 func (b *BlockChain) checkBlockHeaderContext(header *wire.BlockHeader, prevNode *blockNode, flags BehaviorFlags) error {
647 // The genesis block is valid by definition.
652 fastAdd := flags&BFFastAdd == BFFastAdd
654 // Ensure the difficulty specified in the block header matches
655 // the calculated difficulty based on the previous block and
656 // difficulty retarget rules.
657 expectedDifficulty, err := b.calcNextRequiredDifficulty(prevNode,
662 blockDifficulty := header.Bits
663 if blockDifficulty != expectedDifficulty {
664 str := "block difficulty of %d is not the expected value of %d"
665 str = fmt.Sprintf(str, blockDifficulty, expectedDifficulty)
666 return ruleError(ErrUnexpectedDifficulty, str)
669 // Ensure the timestamp for the block header is after the
670 // median time of the last several blocks (medianTimeBlocks).
671 medianTime := prevNode.CalcPastMedianTime()
672 if !header.Timestamp.After(medianTime) {
673 str := "block timestamp of %v is not after expected %v"
674 str = fmt.Sprintf(str, header.Timestamp, medianTime)
675 return ruleError(ErrTimeTooOld, str)
679 // The height of this block is one more than the referenced previous
681 blockHeight := prevNode.height + 1
683 // Ensure chain matches up to predetermined checkpoints.
684 blockHash := header.BlockHash()
685 if !b.verifyCheckpoint(blockHeight, &blockHash) {
686 str := fmt.Sprintf("block at height %d does not match "+
687 "checkpoint hash", blockHeight)
688 return ruleError(ErrBadCheckpoint, str)
691 // Find the previous checkpoint and prevent blocks which fork the main
692 // chain before it. This prevents storage of new, otherwise valid,
693 // blocks which build off of old blocks that are likely at a much easier
694 // difficulty and therefore could be used to waste cache and disk space.
695 checkpointNode, err := b.findPreviousCheckpoint()
699 if checkpointNode != nil && blockHeight < checkpointNode.height {
700 str := fmt.Sprintf("block at height %d forks the main chain "+
701 "before the previous checkpoint at height %d",
702 blockHeight, checkpointNode.height)
703 return ruleError(ErrForkTooOld, str)
706 // Reject outdated block versions once a majority of the network
707 // has upgraded. These were originally voted on by BIP0034,
708 // BIP0065, and BIP0066.
709 params := b.chainParams
710 if header.Version < 2 && blockHeight >= params.BIP0034Height ||
711 header.Version < 3 && blockHeight >= params.BIP0066Height ||
712 header.Version < 4 && blockHeight >= params.BIP0065Height {
714 str := "new blocks with version %d are no longer valid"
715 str = fmt.Sprintf(str, header.Version)
716 return ruleError(ErrBlockVersionTooOld, str)
722 // checkBlockContext peforms several validation checks on the block which depend
723 // on its position within the block chain.
725 // The flags modify the behavior of this function as follows:
726 // - BFFastAdd: The transaction are not checked to see if they are finalized
727 // and the somewhat expensive BIP0034 validation is not performed.
729 // The flags are also passed to checkBlockHeaderContext. See its documentation
730 // for how the flags modify its behavior.
732 // This function MUST be called with the chain state lock held (for writes).
733 func (b *BlockChain) checkBlockContext(block *btcutil.Block, prevNode *blockNode, flags BehaviorFlags) error {
734 // The genesis block is valid by definition.
739 // Perform all block header related validation checks.
740 header := &block.MsgBlock().Header
741 err := b.checkBlockHeaderContext(header, prevNode, flags)
746 fastAdd := flags&BFFastAdd == BFFastAdd
748 // Obtain the latest state of the deployed CSV soft-fork in
749 // order to properly guard the new validation behavior based on
750 // the current BIP 9 version bits state.
751 csvState, err := b.deploymentState(prevNode, chaincfg.DeploymentCSV)
756 // Once the CSV soft-fork is fully active, we'll switch to
757 // using the current median time past of the past block's
758 // timestamps for all lock-time based checks.
759 blockTime := header.Timestamp
760 if csvState == ThresholdActive {
761 blockTime = prevNode.CalcPastMedianTime()
764 // The height of this block is one more than the referenced
766 blockHeight := prevNode.height + 1
768 // Ensure all transactions in the block are finalized.
769 for _, tx := range block.Transactions() {
770 if !IsFinalizedTransaction(tx, blockHeight,
773 str := fmt.Sprintf("block contains unfinalized "+
774 "transaction %v", tx.Hash())
775 return ruleError(ErrUnfinalizedTx, str)
779 // Ensure coinbase starts with serialized block heights for
780 // blocks whose version is the serializedHeightVersion or newer
781 // once a majority of the network has upgraded. This is part of
783 if ShouldHaveSerializedBlockHeight(header) &&
784 blockHeight >= b.chainParams.BIP0034Height {
786 coinbaseTx := block.Transactions()[0]
787 err := checkSerializedHeight(coinbaseTx, blockHeight)
793 // Query for the Version Bits state for the segwit soft-fork
794 // deployment. If segwit is active, we'll switch over to
795 // enforcing all the new rules.
796 segwitState, err := b.deploymentState(prevNode,
797 chaincfg.DeploymentSegwit)
802 // If segwit is active, then we'll need to fully validate the
803 // new witness commitment for adherance to the rules.
804 if segwitState == ThresholdActive {
805 // Validate the witness commitment (if any) within the
806 // block. This involves asserting that if the coinbase
807 // contains the special commitment output, then this
808 // merkle root matches a computed merkle root of all
809 // the wtxid's of the transactions within the block. In
810 // addition, various other checks against the
811 // coinbase's witness stack.
812 if err := ValidateWitnessCommitment(block); err != nil {
816 // Once the witness commitment, witness nonce, and sig
817 // op cost have been validated, we can finally assert
818 // that the block's weight doesn't exceed the current
819 // consensus parameter.
820 blockWeight := GetBlockWeight(block)
821 if blockWeight > MaxBlockWeight {
822 str := fmt.Sprintf("block's weight metric is "+
823 "too high - got %v, max %v",
824 blockWeight, MaxBlockWeight)
825 return ruleError(ErrBlockVersionTooOld, str)
833 // checkBIP0030 ensures blocks do not contain duplicate transactions which
834 // 'overwrite' older transactions that are not fully spent. This prevents an
835 // attack where a coinbase and all of its dependent transactions could be
836 // duplicated to effectively revert the overwritten transactions to a single
837 // confirmation thereby making them vulnerable to a double spend.
839 // For more details, see https://en.bitcoin.it/wiki/BIP_0030 and
840 // http://r6.ca/blog/20120206T005236Z.html.
842 // This function MUST be called with the chain state lock held (for reads).
843 func (b *BlockChain) checkBIP0030(node *blockNode, block *btcutil.Block, view *UtxoViewpoint) error {
844 // Fetch utxo details for all of the transactions in this block.
845 // Typically, there will not be any utxos for any of the transactions.
846 fetchSet := make(map[chainhash.Hash]struct{})
847 for _, tx := range block.Transactions() {
848 fetchSet[*tx.Hash()] = struct{}{}
850 err := view.fetchUtxos(b.db, fetchSet)
855 // Duplicate transactions are only allowed if the previous transaction
857 for _, tx := range block.Transactions() {
858 txEntry := view.LookupEntry(tx.Hash())
859 if txEntry != nil && !txEntry.IsFullySpent() {
860 str := fmt.Sprintf("tried to overwrite transaction %v "+
861 "at block height %d that is not fully spent",
862 tx.Hash(), txEntry.blockHeight)
863 return ruleError(ErrOverwriteTx, str)
870 // CheckTransactionInputs performs a series of checks on the inputs to a
871 // transaction to ensure they are valid. An example of some of the checks
872 // include verifying all inputs exist, ensuring the coinbase seasoning
873 // requirements are met, detecting double spends, validating all values and fees
874 // are in the legal range and the total output amount doesn't exceed the input
875 // amount, and verifying the signatures to prove the spender was the owner of
876 // the bitcoins and therefore allowed to spend them. As it checks the inputs,
877 // it also calculates the total fees for the transaction and returns that value.
879 // NOTE: The transaction MUST have already been sanity checked with the
880 // CheckTransactionSanity function prior to calling this function.
881 func CheckTransactionInputs(tx *btcutil.Tx, txHeight int32, utxoView *UtxoViewpoint, chainParams *chaincfg.Params) (int64, error) {
882 // Coinbase transactions have no inputs.
888 var totalSatoshiIn int64
889 for txInIndex, txIn := range tx.MsgTx().TxIn {
890 // Ensure the referenced input transaction is available.
891 originTxHash := &txIn.PreviousOutPoint.Hash
892 originTxIndex := txIn.PreviousOutPoint.Index
893 utxoEntry := utxoView.LookupEntry(originTxHash)
894 if utxoEntry == nil || utxoEntry.IsOutputSpent(originTxIndex) {
895 str := fmt.Sprintf("output %v referenced from "+
896 "transaction %s:%d either does not exist or "+
897 "has already been spent", txIn.PreviousOutPoint,
898 tx.Hash(), txInIndex)
899 return 0, ruleError(ErrMissingTxOut, str)
902 // Ensure the transaction is not spending coins which have not
903 // yet reached the required coinbase maturity.
904 if utxoEntry.IsCoinBase() {
905 originHeight := utxoEntry.BlockHeight()
906 blocksSincePrev := txHeight - originHeight
907 coinbaseMaturity := int32(chainParams.CoinbaseMaturity)
908 if blocksSincePrev < coinbaseMaturity {
909 str := fmt.Sprintf("tried to spend coinbase "+
910 "transaction %v from height %v at "+
911 "height %v before required maturity "+
912 "of %v blocks", originTxHash,
913 originHeight, txHeight,
915 return 0, ruleError(ErrImmatureSpend, str)
919 // Ensure the transaction amounts are in range. Each of the
920 // output values of the input transactions must not be negative
921 // or more than the max allowed per transaction. All amounts in
922 // a transaction are in a unit value known as a satoshi. One
923 // bitcoin is a quantity of satoshi as defined by the
924 // SatoshiPerBitcoin constant.
925 originTxSatoshi := utxoEntry.AmountByIndex(originTxIndex)
926 if originTxSatoshi < 0 {
927 str := fmt.Sprintf("transaction output has negative "+
928 "value of %v", btcutil.Amount(originTxSatoshi))
929 return 0, ruleError(ErrBadTxOutValue, str)
931 if originTxSatoshi > btcutil.MaxSatoshi {
932 str := fmt.Sprintf("transaction output value of %v is "+
933 "higher than max allowed value of %v",
934 btcutil.Amount(originTxSatoshi),
936 return 0, ruleError(ErrBadTxOutValue, str)
939 // The total of all outputs must not be more than the max
940 // allowed per transaction. Also, we could potentially overflow
941 // the accumulator so check for overflow.
942 lastSatoshiIn := totalSatoshiIn
943 totalSatoshiIn += originTxSatoshi
944 if totalSatoshiIn < lastSatoshiIn ||
945 totalSatoshiIn > btcutil.MaxSatoshi {
946 str := fmt.Sprintf("total value of all transaction "+
947 "inputs is %v which is higher than max "+
948 "allowed value of %v", totalSatoshiIn,
950 return 0, ruleError(ErrBadTxOutValue, str)
954 // Calculate the total output amount for this transaction. It is safe
955 // to ignore overflow and out of range errors here because those error
956 // conditions would have already been caught by checkTransactionSanity.
957 var totalSatoshiOut int64
958 for _, txOut := range tx.MsgTx().TxOut {
959 totalSatoshiOut += txOut.Value
962 // Ensure the transaction does not spend more than its inputs.
963 if totalSatoshiIn < totalSatoshiOut {
964 str := fmt.Sprintf("total value of all transaction inputs for "+
965 "transaction %v is %v which is less than the amount "+
966 "spent of %v", txHash, totalSatoshiIn, totalSatoshiOut)
967 return 0, ruleError(ErrSpendTooHigh, str)
970 // NOTE: bitcoind checks if the transaction fees are < 0 here, but that
971 // is an impossible condition because of the check above that ensures
972 // the inputs are >= the outputs.
973 txFeeInSatoshi := totalSatoshiIn - totalSatoshiOut
974 return txFeeInSatoshi, nil
977 // checkConnectBlock performs several checks to confirm connecting the passed
978 // block to the chain represented by the passed view does not violate any rules.
979 // In addition, the passed view is updated to spend all of the referenced
980 // outputs and add all of the new utxos created by block. Thus, the view will
981 // represent the state of the chain as if the block were actually connected and
982 // consequently the best hash for the view is also updated to passed block.
984 // The CheckConnectBlock function makes use of this function to perform the
985 // bulk of its work. The only difference is this function accepts a node which
986 // may or may not require reorganization to connect it to the main chain whereas
987 // CheckConnectBlock creates a new node which specifically connects to the end
988 // of the current main chain and then calls this function with that node.
990 // See the comments for CheckConnectBlock for some examples of the type of
991 // checks performed by this function.
993 // This function MUST be called with the chain state lock held (for writes).
994 func (b *BlockChain) checkConnectBlock(node *blockNode, block *btcutil.Block, view *UtxoViewpoint, stxos *[]spentTxOut) error {
995 // If the side chain blocks end up in the database, a call to
996 // CheckBlockSanity should be done here in case a previous version
997 // allowed a block that is no longer valid. However, since the
998 // implementation only currently uses memory for the side chain blocks,
999 // it isn't currently necessary.
1001 // The coinbase for the Genesis block is not spendable, so just return
1003 if node.hash.IsEqual(b.chainParams.GenesisHash) {
1004 str := "the coinbase for the genesis block is not spendable"
1005 return ruleError(ErrMissingTxOut, str)
1008 // Ensure the view is for the node being checked.
1009 parentHash := &block.MsgBlock().Header.PrevBlock
1010 if !view.BestHash().IsEqual(parentHash) {
1011 return AssertError(fmt.Sprintf("inconsistent view when "+
1012 "checking block connection: best hash is %v instead "+
1013 "of expected %v", view.BestHash(), parentHash))
1016 // BIP0030 added a rule to prevent blocks which contain duplicate
1017 // transactions that 'overwrite' older transactions which are not fully
1018 // spent. See the documentation for checkBIP0030 for more details.
1020 // There are two blocks in the chain which violate this rule, so the
1021 // check must be skipped for those blocks. The isBIP0030Node function
1022 // is used to determine if this block is one of the two blocks that must
1025 // In addition, as of BIP0034, duplicate coinbases are no longer
1026 // possible due to its requirement for including the block height in the
1027 // coinbase and thus it is no longer possible to create transactions
1028 // that 'overwrite' older ones. Therefore, only enforce the rule if
1029 // BIP0034 is not yet active. This is a useful optimization because the
1030 // BIP0030 check is expensive since it involves a ton of cache misses in
1032 if !isBIP0030Node(node) && (node.height < b.chainParams.BIP0034Height) {
1033 err := b.checkBIP0030(node, block, view)
1039 // Load all of the utxos referenced by the inputs for all transactions
1040 // in the block don't already exist in the utxo view from the database.
1042 // These utxo entries are needed for verification of things such as
1043 // transaction inputs, counting pay-to-script-hashes, and scripts.
1044 err := view.fetchInputUtxos(b.db, block)
1049 // BIP0016 describes a pay-to-script-hash type that is considered a
1050 // "standard" type. The rules for this BIP only apply to transactions
1051 // after the timestamp defined by txscript.Bip16Activation. See
1052 // https://en.bitcoin.it/wiki/BIP_0016 for more details.
1053 enforceBIP0016 := node.timestamp >= txscript.Bip16Activation.Unix()
1055 // Query for the Version Bits state for the segwit soft-fork
1056 // deployment. If segwit is active, we'll switch over to enforcing all
1058 segwitState, err := b.deploymentState(node.parent, chaincfg.DeploymentSegwit)
1062 enforceSegWit := segwitState == ThresholdActive
1064 // The number of signature operations must be less than the maximum
1065 // allowed per block. Note that the preliminary sanity checks on a
1066 // block also include a check similar to this one, but this check
1067 // expands the count to include a precise count of pay-to-script-hash
1068 // signature operations in each of the input transaction public key
1070 transactions := block.Transactions()
1072 for i, tx := range transactions {
1073 // Since the first (and only the first) transaction has
1074 // already been verified to be a coinbase transaction,
1075 // use i == 0 as an optimization for the flag to
1076 // countP2SHSigOps for whether or not the transaction is
1077 // a coinbase transaction rather than having to do a
1078 // full coinbase check again.
1079 sigOpCost, err := GetSigOpCost(tx, i == 0, view, enforceBIP0016,
1085 // Check for overflow or going over the limits. We have to do
1086 // this on every loop iteration to avoid overflow.
1087 lastSigOpCost := totalSigOpCost
1088 totalSigOpCost += sigOpCost
1089 if totalSigOpCost < lastSigOpCost || totalSigOpCost > MaxBlockSigOpsCost {
1090 str := fmt.Sprintf("block contains too many "+
1091 "signature operations - got %v, max %v",
1092 totalSigOpCost, MaxBlockSigOpsCost)
1093 return ruleError(ErrTooManySigOps, str)
1097 // Perform several checks on the inputs for each transaction. Also
1098 // accumulate the total fees. This could technically be combined with
1099 // the loop above instead of running another loop over the transactions,
1100 // but by separating it we can avoid running the more expensive (though
1101 // still relatively cheap as compared to running the scripts) checks
1102 // against all the inputs when the signature operations are out of
1105 for _, tx := range transactions {
1106 txFee, err := CheckTransactionInputs(tx, node.height, view,
1112 // Sum the total fees and ensure we don't overflow the
1114 lastTotalFees := totalFees
1116 if totalFees < lastTotalFees {
1117 return ruleError(ErrBadFees, "total fees for block "+
1118 "overflows accumulator")
1121 // Add all of the outputs for this transaction which are not
1122 // provably unspendable as available utxos. Also, the passed
1123 // spent txos slice is updated to contain an entry for each
1124 // spent txout in the order each transaction spends them.
1125 err = view.connectTransaction(tx, node.height, stxos)
1131 // The total output values of the coinbase transaction must not exceed
1132 // the expected subsidy value plus total transaction fees gained from
1133 // mining the block. It is safe to ignore overflow and out of range
1134 // errors here because those error conditions would have already been
1135 // caught by checkTransactionSanity.
1136 var totalSatoshiOut int64
1137 for _, txOut := range transactions[0].MsgTx().TxOut {
1138 totalSatoshiOut += txOut.Value
1140 expectedSatoshiOut := CalcBlockSubsidy(node.height, b.chainParams) +
1142 if totalSatoshiOut > expectedSatoshiOut {
1143 str := fmt.Sprintf("coinbase transaction for block pays %v "+
1144 "which is more than expected value of %v",
1145 totalSatoshiOut, expectedSatoshiOut)
1146 return ruleError(ErrBadCoinbaseValue, str)
1149 // Don't run scripts if this node is before the latest known good
1150 // checkpoint since the validity is verified via the checkpoints (all
1151 // transactions are included in the merkle root hash and any changes
1152 // will therefore be detected by the next checkpoint). This is a huge
1153 // optimization because running the scripts is the most time consuming
1154 // portion of block handling.
1155 checkpoint := b.LatestCheckpoint()
1157 if checkpoint != nil && node.height <= checkpoint.Height {
1161 // Blocks created after the BIP0016 activation time need to have the
1162 // pay-to-script-hash checks enabled.
1163 var scriptFlags txscript.ScriptFlags
1165 scriptFlags |= txscript.ScriptBip16
1168 // Enforce DER signatures for block versions 3+ once the historical
1169 // activation threshold has been reached. This is part of BIP0066.
1170 blockHeader := &block.MsgBlock().Header
1171 if blockHeader.Version >= 3 && node.height >= b.chainParams.BIP0066Height {
1172 scriptFlags |= txscript.ScriptVerifyDERSignatures
1175 // Enforce CHECKLOCKTIMEVERIFY for block versions 4+ once the historical
1176 // activation threshold has been reached. This is part of BIP0065.
1177 if blockHeader.Version >= 4 && node.height >= b.chainParams.BIP0065Height {
1178 scriptFlags |= txscript.ScriptVerifyCheckLockTimeVerify
1181 // Enforce CHECKSEQUENCEVERIFY during all block validation checks once
1182 // the soft-fork deployment is fully active.
1183 csvState, err := b.deploymentState(node.parent, chaincfg.DeploymentCSV)
1187 if csvState == ThresholdActive {
1188 // If the CSV soft-fork is now active, then modify the
1189 // scriptFlags to ensure that the CSV op code is properly
1190 // validated during the script checks bleow.
1191 scriptFlags |= txscript.ScriptVerifyCheckSequenceVerify
1193 // We obtain the MTP of the *previous* block in order to
1194 // determine if transactions in the current block are final.
1195 medianTime := node.parent.CalcPastMedianTime()
1197 // Additionally, if the CSV soft-fork package is now active,
1198 // then we also enforce the relative sequence number based
1199 // lock-times within the inputs of all transactions in this
1201 for _, tx := range block.Transactions() {
1202 // A transaction can only be included within a block
1203 // once the sequence locks of *all* its inputs are
1205 sequenceLock, err := b.calcSequenceLock(node, tx, view,
1210 if !SequenceLockActive(sequenceLock, node.height,
1212 str := fmt.Sprintf("block contains " +
1213 "transaction whose input sequence " +
1214 "locks are not met")
1215 return ruleError(ErrUnfinalizedTx, str)
1220 // Enforce the segwit soft-fork package once the soft-fork has shifted
1221 // into the "active" version bits state.
1223 scriptFlags |= txscript.ScriptVerifyWitness
1224 scriptFlags |= txscript.ScriptStrictMultiSig
1227 // Now that the inexpensive checks are done and have passed, verify the
1228 // transactions are actually allowed to spend the coins by running the
1229 // expensive ECDSA signature check scripts. Doing this last helps
1230 // prevent CPU exhaustion attacks.
1232 err := checkBlockScripts(block, view, scriptFlags, b.sigCache,
1239 // Update the best hash for view to include this block since all of its
1240 // transactions have been connected.
1241 view.SetBestHash(&node.hash)
1246 // CheckConnectBlock performs several checks to confirm connecting the passed
1247 // block to the main chain does not violate any rules. An example of some of
1248 // the checks performed are ensuring connecting the block would not cause any
1249 // duplicate transaction hashes for old transactions that aren't already fully
1250 // spent, double spends, exceeding the maximum allowed signature operations
1251 // per block, invalid values in relation to the expected block subsidy, or fail
1252 // transaction script validation.
1254 // This function is safe for concurrent access.
1255 func (b *BlockChain) CheckConnectBlock(block *btcutil.Block) error {
1257 defer b.chainLock.Unlock()
1259 prevNode := b.bestChain.Tip()
1260 newNode := newBlockNode(&block.MsgBlock().Header, prevNode.height+1)
1261 newNode.parent = prevNode
1262 newNode.workSum.Add(prevNode.workSum, newNode.workSum)
1264 // Leave the spent txouts entry nil in the state since the information
1265 // is not needed and thus extra work can be avoided.
1266 view := NewUtxoViewpoint()
1267 view.SetBestHash(&prevNode.hash)
1268 return b.checkConnectBlock(newNode, block, view, nil)