github.com/lbryio/lbcd@v0.22.119/blockchain/validate.go (about)

     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.
     4  
     5  package blockchain
     6  
     7  import (
     8  	"encoding/binary"
     9  	"fmt"
    10  	"math"
    11  	"math/big"
    12  	"time"
    13  
    14  	"github.com/lbryio/lbcd/chaincfg"
    15  	"github.com/lbryio/lbcd/chaincfg/chainhash"
    16  	"github.com/lbryio/lbcd/txscript"
    17  	"github.com/lbryio/lbcd/wire"
    18  	btcutil "github.com/lbryio/lbcutil"
    19  )
    20  
    21  const (
    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
    24  	// hours.
    25  	MaxTimeOffsetSeconds = 2 * 60 * 60
    26  
    27  	// MinCoinbaseScriptLen is the minimum length a coinbase script can be.
    28  	MinCoinbaseScriptLen = 2
    29  
    30  	// MaxCoinbaseScriptLen is the maximum length a coinbase script can be.
    31  	MaxCoinbaseScriptLen = 100
    32  
    33  	// medianTimeBlocks is the number of previous blocks which should be
    34  	// used to calculate the median time used to validate block timestamps.
    35  	medianTimeBlocks = 11
    36  
    37  	// serializedHeightVersion is the block version which changed block
    38  	// coinbases to start with the serialized block height.
    39  	serializedHeightVersion = 2
    40  
    41  	// baseSubsidy is the starting subsidy amount for mined blocks.  This
    42  	// value is halved every SubsidyHalvingInterval blocks.
    43  	baseSubsidy = 500 * btcutil.SatoshiPerBitcoin
    44  )
    45  
    46  var (
    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
    51  
    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")
    56  
    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")
    61  )
    62  
    63  // isNullOutpoint determines whether or not a previous transaction output point
    64  // is set.
    65  func isNullOutpoint(outpoint *wire.OutPoint) bool {
    66  	if outpoint.Index == math.MaxUint32 && outpoint.Hash == zeroHash {
    67  		return true
    68  	}
    69  	return false
    70  }
    71  
    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
    79  }
    80  
    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
    85  // zero hash.
    86  //
    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 {
    92  		return false
    93  	}
    94  
    95  	// The previous output of a coin base must have a max value index and
    96  	// a zero hash.
    97  	prevOut := &msgTx.TxIn[0].PreviousOutPoint
    98  	if prevOut.Index != math.MaxUint32 || prevOut.Hash != zeroHash {
    99  		return false
   100  	}
   101  
   102  	return true
   103  }
   104  
   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
   109  // zero hash.
   110  //
   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())
   115  }
   116  
   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 {
   122  
   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
   125  	// sequence locks.
   126  	if sequenceLock.Seconds >= medianTimePast.Unix() ||
   127  		sequenceLock.BlockHeight >= blockHeight {
   128  		return false
   129  	}
   130  
   131  	return true
   132  }
   133  
   134  // IsFinalizedTransaction determines whether or not a transaction is finalized.
   135  func IsFinalizedTransaction(tx *btcutil.Tx, blockHeight int32, blockTime time.Time) bool {
   136  	msgTx := tx.MsgTx()
   137  
   138  	// Lock time of zero means the transaction is finalized.
   139  	lockTime := msgTx.LockTime
   140  	if lockTime == 0 {
   141  		return true
   142  	}
   143  
   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)
   151  	} else {
   152  		blockTimeOrHeight = blockTime.Unix()
   153  	}
   154  	if int64(lockTime) < blockTimeOrHeight {
   155  		return true
   156  	}
   157  
   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 {
   163  			return false
   164  		}
   165  	}
   166  	return true
   167  }
   168  
   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) {
   174  		return true
   175  	}
   176  
   177  	if node.height == 91880 && node.hash.IsEqual(block91880Hash) {
   178  		return true
   179  	}
   180  
   181  	return false
   182  }
   183  
   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.
   188  //
   189  // The subsidy is halved every SubsidyReductionInterval blocks.  Mathematically
   190  // this is: baseSubsidy / 2^(height/SubsidyReductionInterval)
   191  //
   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  	h := int64(height)
   196  	if h == 0 {
   197  		return btcutil.SatoshiPerBitcoin * 4e8
   198  	}
   199  	if h <= 5100 {
   200  		return btcutil.SatoshiPerBitcoin
   201  	}
   202  	if h <= 55000 {
   203  		return btcutil.SatoshiPerBitcoin * (1 + (h-5001)/100)
   204  	}
   205  
   206  	lv := (h - 55001) / int64(chainParams.SubsidyReductionInterval)
   207  	reduction := (int64(math.Sqrt((float64(8*lv))+1)) - 1) / 2
   208  	for !withinLevelBounds(reduction, lv) {
   209  		if ((reduction*reduction + reduction) >> 1) > lv {
   210  			reduction--
   211  		} else {
   212  			reduction++
   213  		}
   214  	}
   215  	subsidyReduction := btcutil.SatoshiPerBitcoin * reduction
   216  	if subsidyReduction >= baseSubsidy {
   217  		return 0
   218  	}
   219  	return baseSubsidy - subsidyReduction
   220  }
   221  
   222  func withinLevelBounds(reduction int64, lv int64) bool {
   223  	if ((reduction*reduction + reduction) >> 1) > lv {
   224  		return false
   225  	}
   226  	reduction++
   227  	return ((reduction*reduction + reduction) >> 1) > lv
   228  }
   229  
   230  // CheckTransactionSanity performs some preliminary checks on a transaction to
   231  // ensure it is sane.
   232  func CheckTransactionSanity(tx *btcutil.Tx, enforceSoftFork bool) error {
   233  	// A transaction must have at least one input.
   234  	msgTx := tx.MsgTx()
   235  	if len(msgTx.TxIn) == 0 {
   236  		return ruleError(ErrNoTxInputs, "transaction has no inputs")
   237  	}
   238  
   239  	// A transaction must have at least one output.
   240  	if len(msgTx.TxOut) == 0 {
   241  		return ruleError(ErrNoTxOutputs, "transaction has no outputs")
   242  	}
   243  
   244  	// A transaction must not exceed the maximum allowed block payload when
   245  	// serialized.
   246  	serializedTxSize := tx.MsgTx().SerializeSizeStripped()
   247  	if serializedTxSize > MaxBlockBaseSize {
   248  		str := fmt.Sprintf("serialized transaction is too big - got "+
   249  			"%d, max %d", serializedTxSize, MaxBlockBaseSize)
   250  		return ruleError(ErrTxTooBig, str)
   251  	}
   252  
   253  	// Ensure the transaction amounts are in range.  Each transaction
   254  	// output must not be negative or more than the max allowed per
   255  	// transaction.  Also, the total of all outputs must abide by the same
   256  	// restrictions.  All amounts in a transaction are in a unit value known
   257  	// as a satoshi.  One bitcoin is a quantity of satoshi as defined by the
   258  	// SatoshiPerBitcoin constant.
   259  	var totalSatoshi int64
   260  	for _, txOut := range msgTx.TxOut {
   261  		satoshi := txOut.Value
   262  		if satoshi < 0 {
   263  			str := fmt.Sprintf("transaction output has negative "+
   264  				"value of %v", satoshi)
   265  			return ruleError(ErrBadTxOutValue, str)
   266  		}
   267  		if satoshi > btcutil.MaxSatoshi {
   268  			str := fmt.Sprintf("transaction output value of %v is "+
   269  				"higher than max allowed value of %v", satoshi,
   270  				btcutil.MaxSatoshi)
   271  			return ruleError(ErrBadTxOutValue, str)
   272  		}
   273  
   274  		// Two's complement int64 overflow guarantees that any overflow
   275  		// is detected and reported.  This is impossible for Bitcoin, but
   276  		// perhaps possible if an alt increases the total money supply.
   277  		totalSatoshi += satoshi
   278  		if totalSatoshi < 0 {
   279  			str := fmt.Sprintf("total value of all transaction "+
   280  				"outputs exceeds max allowed value of %v",
   281  				btcutil.MaxSatoshi)
   282  			return ruleError(ErrBadTxOutValue, str)
   283  		}
   284  		if totalSatoshi > btcutil.MaxSatoshi {
   285  			str := fmt.Sprintf("total value of all transaction "+
   286  				"outputs is %v which is higher than max "+
   287  				"allowed value of %v", totalSatoshi,
   288  				btcutil.MaxSatoshi)
   289  			return ruleError(ErrBadTxOutValue, str)
   290  		}
   291  
   292  		err := txscript.AllClaimsAreSane(txOut.PkScript, enforceSoftFork)
   293  		if err != nil {
   294  			return ruleError(ErrBadTxOutValue, err.Error())
   295  		}
   296  	}
   297  
   298  	// Check for duplicate transaction inputs.
   299  	existingTxOut := make(map[wire.OutPoint]struct{})
   300  	for _, txIn := range msgTx.TxIn {
   301  		if _, exists := existingTxOut[txIn.PreviousOutPoint]; exists {
   302  			return ruleError(ErrDuplicateTxInputs, "transaction "+
   303  				"contains duplicate inputs")
   304  		}
   305  		existingTxOut[txIn.PreviousOutPoint] = struct{}{}
   306  	}
   307  
   308  	// Coinbase script length must be between min and max length.
   309  	if IsCoinBase(tx) {
   310  		slen := len(msgTx.TxIn[0].SignatureScript)
   311  		if slen < MinCoinbaseScriptLen || slen > MaxCoinbaseScriptLen {
   312  			str := fmt.Sprintf("coinbase transaction script length "+
   313  				"of %d is out of range (min: %d, max: %d)",
   314  				slen, MinCoinbaseScriptLen, MaxCoinbaseScriptLen)
   315  			return ruleError(ErrBadCoinbaseScriptLen, str)
   316  		}
   317  	} else {
   318  		// Previous transaction outputs referenced by the inputs to this
   319  		// transaction must not be null.
   320  		for _, txIn := range msgTx.TxIn {
   321  			if isNullOutpoint(&txIn.PreviousOutPoint) {
   322  				return ruleError(ErrBadTxInput, "transaction "+
   323  					"input refers to previous output that "+
   324  					"is null")
   325  			}
   326  		}
   327  	}
   328  
   329  	return nil
   330  }
   331  
   332  // checkProofOfWork ensures the block header bits which indicate the target
   333  // difficulty is in min/max range and that the block hash is less than the
   334  // target difficulty as claimed.
   335  //
   336  // The flags modify the behavior of this function as follows:
   337  //   - BFNoPoWCheck: The check to ensure the block hash is less than the target
   338  //     difficulty is not performed.
   339  func checkProofOfWork(header *wire.BlockHeader, powLimit *big.Int, flags BehaviorFlags) error {
   340  	// The target difficulty must be larger than zero.
   341  	target := CompactToBig(header.Bits)
   342  	if target.Sign() <= 0 {
   343  		str := fmt.Sprintf("block target difficulty of %064x is too low",
   344  			target)
   345  		return ruleError(ErrUnexpectedDifficulty, str)
   346  	}
   347  
   348  	// The target difficulty must be less than the maximum allowed.
   349  	if target.Cmp(powLimit) > 0 {
   350  		str := fmt.Sprintf("block target difficulty of %064x is "+
   351  			"higher than max of %064x", target, powLimit)
   352  		return ruleError(ErrUnexpectedDifficulty, str)
   353  	}
   354  
   355  	// The block hash must be less than the claimed target unless the flag
   356  	// to avoid proof of work checks is set.
   357  	if flags&BFNoPoWCheck != BFNoPoWCheck {
   358  		// The block hash must be less than the claimed target.
   359  		hash := header.BlockPoWHash()
   360  		hashNum := HashToBig(&hash)
   361  		if hashNum.Cmp(target) > 0 {
   362  			str := fmt.Sprintf("block hash of %064x is higher than "+
   363  				"expected max of %064x", hashNum, target)
   364  			return ruleError(ErrHighHash, str)
   365  		}
   366  	}
   367  
   368  	return nil
   369  }
   370  
   371  // CheckProofOfWork ensures the block header bits which indicate the target
   372  // difficulty is in min/max range and that the block hash is less than the
   373  // target difficulty as claimed.
   374  func CheckProofOfWork(block *btcutil.Block, powLimit *big.Int) error {
   375  	return checkProofOfWork(&block.MsgBlock().Header, powLimit, BFNone)
   376  }
   377  
   378  // CountSigOps returns the number of signature operations for all transaction
   379  // input and output scripts in the provided transaction.  This uses the
   380  // quicker, but imprecise, signature operation counting mechanism from
   381  // txscript.
   382  func CountSigOps(tx *btcutil.Tx) int {
   383  	msgTx := tx.MsgTx()
   384  
   385  	// Accumulate the number of signature operations in all transaction
   386  	// inputs.
   387  	totalSigOps := 0
   388  	for _, txIn := range msgTx.TxIn {
   389  		numSigOps := txscript.GetSigOpCount(txIn.SignatureScript)
   390  		totalSigOps += numSigOps
   391  	}
   392  
   393  	// Accumulate the number of signature operations in all transaction
   394  	// outputs.
   395  	for _, txOut := range msgTx.TxOut {
   396  		numSigOps := txscript.GetSigOpCount(txOut.PkScript)
   397  		totalSigOps += numSigOps
   398  	}
   399  
   400  	return totalSigOps
   401  }
   402  
   403  // CountP2SHSigOps returns the number of signature operations for all input
   404  // transactions which are of the pay-to-script-hash type.  This uses the
   405  // precise, signature operation counting mechanism from the script engine which
   406  // requires access to the input transaction scripts.
   407  func CountP2SHSigOps(tx *btcutil.Tx, isCoinBaseTx bool, utxoView *UtxoViewpoint) (int, error) {
   408  	// Coinbase transactions have no interesting inputs.
   409  	if isCoinBaseTx {
   410  		return 0, nil
   411  	}
   412  
   413  	// Accumulate the number of signature operations in all transaction
   414  	// inputs.
   415  	msgTx := tx.MsgTx()
   416  	totalSigOps := 0
   417  	for txInIndex, txIn := range msgTx.TxIn {
   418  		// Ensure the referenced input transaction is available.
   419  		utxo := utxoView.LookupEntry(txIn.PreviousOutPoint)
   420  		if utxo == nil || utxo.IsSpent() {
   421  			str := fmt.Sprintf("output %v referenced from "+
   422  				"transaction %s:%d either does not exist or "+
   423  				"has already been spent", txIn.PreviousOutPoint,
   424  				tx.Hash(), txInIndex)
   425  			return 0, ruleError(ErrMissingTxOut, str)
   426  		}
   427  
   428  		// We're only interested in pay-to-script-hash types, so skip
   429  		// this input if it's not one.
   430  		pkScript := utxo.PkScript()
   431  		if !txscript.IsPayToScriptHash(pkScript) {
   432  			continue
   433  		}
   434  
   435  		// Count the precise number of signature operations in the
   436  		// referenced public key script.
   437  		sigScript := txIn.SignatureScript
   438  		numSigOps := txscript.GetPreciseSigOpCount(sigScript, pkScript,
   439  			true)
   440  
   441  		// We could potentially overflow the accumulator so check for
   442  		// overflow.
   443  		lastSigOps := totalSigOps
   444  		totalSigOps += numSigOps
   445  		if totalSigOps < lastSigOps {
   446  			str := fmt.Sprintf("the public key script from output "+
   447  				"%v contains too many signature operations - "+
   448  				"overflow", txIn.PreviousOutPoint)
   449  			return 0, ruleError(ErrTooManySigOps, str)
   450  		}
   451  	}
   452  
   453  	return totalSigOps, nil
   454  }
   455  
   456  // checkBlockHeaderSanity performs some preliminary checks on a block header to
   457  // ensure it is sane before continuing with processing.  These checks are
   458  // context free.
   459  //
   460  // The flags do not modify the behavior of this function directly, however they
   461  // are needed to pass along to checkProofOfWork.
   462  func checkBlockHeaderSanity(header *wire.BlockHeader, powLimit *big.Int, timeSource MedianTimeSource, flags BehaviorFlags) error {
   463  	// Ensure the proof of work bits in the block header is in min/max range
   464  	// and the block hash is less than the target value described by the
   465  	// bits.
   466  	err := checkProofOfWork(header, powLimit, flags)
   467  	if err != nil {
   468  		return err
   469  	}
   470  
   471  	// A block timestamp must not have a greater precision than one second.
   472  	// This check is necessary because Go time.Time values support
   473  	// nanosecond precision whereas the consensus rules only apply to
   474  	// seconds and it's much nicer to deal with standard Go time values
   475  	// instead of converting to seconds everywhere.
   476  	if !header.Timestamp.Equal(time.Unix(header.Timestamp.Unix(), 0)) {
   477  		str := fmt.Sprintf("block timestamp of %v has a higher "+
   478  			"precision than one second", header.Timestamp)
   479  		return ruleError(ErrInvalidTime, str)
   480  	}
   481  
   482  	// Ensure the block time is not too far in the future.
   483  	maxTimestamp := timeSource.AdjustedTime().Add(time.Second *
   484  		MaxTimeOffsetSeconds)
   485  	if header.Timestamp.After(maxTimestamp) {
   486  		str := fmt.Sprintf("block timestamp of %v is too far in the "+
   487  			"future", header.Timestamp)
   488  		return ruleError(ErrTimeTooNew, str)
   489  	}
   490  
   491  	return nil
   492  }
   493  
   494  // checkBlockSanity performs some preliminary checks on a block to ensure it is
   495  // sane before continuing with block processing.  These checks are context free.
   496  //
   497  // The flags do not modify the behavior of this function directly, however they
   498  // are needed to pass along to checkBlockHeaderSanity.
   499  func checkBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource, flags BehaviorFlags) error {
   500  	msgBlock := block.MsgBlock()
   501  	header := &msgBlock.Header
   502  	err := checkBlockHeaderSanity(header, powLimit, timeSource, flags)
   503  	if err != nil {
   504  		return err
   505  	}
   506  
   507  	// A block must have at least one transaction.
   508  	numTx := len(msgBlock.Transactions)
   509  	if numTx == 0 {
   510  		return ruleError(ErrNoTransactions, "block does not contain "+
   511  			"any transactions")
   512  	}
   513  
   514  	// A block must not have more transactions than the max block payload or
   515  	// else it is certainly over the weight limit.
   516  	if numTx > MaxBlockBaseSize {
   517  		str := fmt.Sprintf("block contains too many transactions - "+
   518  			"got %d, max %d", numTx, MaxBlockBaseSize)
   519  		return ruleError(ErrBlockTooBig, str)
   520  	}
   521  
   522  	// A block must not exceed the maximum allowed block payload when
   523  	// serialized.
   524  	serializedSize := msgBlock.SerializeSizeStripped()
   525  	if serializedSize > MaxBlockBaseSize {
   526  		str := fmt.Sprintf("serialized block is too big - got %d, "+
   527  			"max %d", serializedSize, MaxBlockBaseSize)
   528  		return ruleError(ErrBlockTooBig, str)
   529  	}
   530  
   531  	// The first transaction in a block must be a coinbase.
   532  	transactions := block.Transactions()
   533  	if !IsCoinBase(transactions[0]) {
   534  		return ruleError(ErrFirstTxNotCoinbase, "first transaction in "+
   535  			"block is not a coinbase")
   536  	}
   537  
   538  	// A block must not have more than one coinbase.
   539  	for i, tx := range transactions[1:] {
   540  		if IsCoinBase(tx) {
   541  			str := fmt.Sprintf("block contains second coinbase at "+
   542  				"index %d", i+1)
   543  			return ruleError(ErrMultipleCoinbases, str)
   544  		}
   545  	}
   546  
   547  	// Do some preliminary checks on each transaction to ensure they are
   548  	// sane before continuing.
   549  	for _, tx := range transactions {
   550  		err := CheckTransactionSanity(tx, false)
   551  		if err != nil {
   552  			return err
   553  		}
   554  	}
   555  
   556  	// Build merkle tree and ensure the calculated merkle root matches the
   557  	// entry in the block header.  This also has the effect of caching all
   558  	// of the transaction hashes in the block to speed up future hash
   559  	// checks.  Bitcoind builds the tree here and checks the merkle root
   560  	// after the following checks, but there is no reason not to check the
   561  	// merkle root matches here.
   562  	merkles := BuildMerkleTreeStore(block.Transactions(), false)
   563  	calculatedMerkleRoot := merkles[len(merkles)-1]
   564  	if !header.MerkleRoot.IsEqual(calculatedMerkleRoot) {
   565  		str := fmt.Sprintf("block merkle root is invalid - block "+
   566  			"header indicates %v, but calculated value is %v",
   567  			header.MerkleRoot, calculatedMerkleRoot)
   568  		return ruleError(ErrBadMerkleRoot, str)
   569  	}
   570  
   571  	// Check for duplicate transactions.  This check will be fairly quick
   572  	// since the transaction hashes are already cached due to building the
   573  	// merkle tree above.
   574  	existingTxHashes := make(map[chainhash.Hash]struct{})
   575  	for _, tx := range transactions {
   576  		hash := tx.Hash()
   577  		if _, exists := existingTxHashes[*hash]; exists {
   578  			str := fmt.Sprintf("block contains duplicate "+
   579  				"transaction %v", hash)
   580  			return ruleError(ErrDuplicateTx, str)
   581  		}
   582  		existingTxHashes[*hash] = struct{}{}
   583  	}
   584  
   585  	// The number of signature operations must be less than the maximum
   586  	// allowed per block.
   587  	totalSigOps := 0
   588  	for _, tx := range transactions {
   589  		// We could potentially overflow the accumulator so check for
   590  		// overflow.
   591  		lastSigOps := totalSigOps
   592  		totalSigOps += (CountSigOps(tx) * WitnessScaleFactor)
   593  		if totalSigOps < lastSigOps || totalSigOps > MaxBlockSigOpsCost {
   594  			str := fmt.Sprintf("block contains too many signature "+
   595  				"operations - got %v, max %v", totalSigOps,
   596  				MaxBlockSigOpsCost)
   597  			return ruleError(ErrTooManySigOps, str)
   598  		}
   599  	}
   600  
   601  	return nil
   602  }
   603  
   604  // CheckBlockSanity performs some preliminary checks on a block to ensure it is
   605  // sane before continuing with block processing.  These checks are context free.
   606  func CheckBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource) error {
   607  	return checkBlockSanity(block, powLimit, timeSource, BFNone)
   608  }
   609  
   610  // ExtractCoinbaseHeight attempts to extract the height of the block from the
   611  // scriptSig of a coinbase transaction.  Coinbase heights are only present in
   612  // blocks of version 2 or later.  This was added as part of BIP0034.
   613  func ExtractCoinbaseHeight(coinbaseTx *btcutil.Tx) (int32, error) {
   614  	sigScript := coinbaseTx.MsgTx().TxIn[0].SignatureScript
   615  	if len(sigScript) < 1 {
   616  		str := "the coinbase signature script for blocks of " +
   617  			"version %d or greater must start with the " +
   618  			"length of the serialized block height"
   619  		str = fmt.Sprintf(str, serializedHeightVersion)
   620  		return 0, ruleError(ErrMissingCoinbaseHeight, str)
   621  	}
   622  
   623  	// Detect the case when the block height is a small integer encoded with
   624  	// as single byte.
   625  	opcode := int(sigScript[0])
   626  	if opcode == txscript.OP_0 {
   627  		return 0, nil
   628  	}
   629  	if opcode >= txscript.OP_1 && opcode <= txscript.OP_16 {
   630  		return int32(opcode - (txscript.OP_1 - 1)), nil
   631  	}
   632  
   633  	// Otherwise, the opcode is the length of the following bytes which
   634  	// encode in the block height.
   635  	serializedLen := int(sigScript[0])
   636  	if len(sigScript[1:]) < serializedLen {
   637  		str := "the coinbase signature script for blocks of " +
   638  			"version %d or greater must start with the " +
   639  			"serialized block height"
   640  		str = fmt.Sprintf(str, serializedLen)
   641  		return 0, ruleError(ErrMissingCoinbaseHeight, str)
   642  	}
   643  
   644  	serializedHeightBytes := make([]byte, 8)
   645  	copy(serializedHeightBytes, sigScript[1:serializedLen+1])
   646  	serializedHeight := binary.LittleEndian.Uint64(serializedHeightBytes)
   647  
   648  	return int32(serializedHeight), nil
   649  }
   650  
   651  // checkSerializedHeight checks if the signature script in the passed
   652  // transaction starts with the serialized block height of wantHeight.
   653  func checkSerializedHeight(coinbaseTx *btcutil.Tx, wantHeight int32) error {
   654  	serializedHeight, err := ExtractCoinbaseHeight(coinbaseTx)
   655  	if err != nil {
   656  		return err
   657  	}
   658  
   659  	if serializedHeight != wantHeight {
   660  		str := fmt.Sprintf("the coinbase signature script serialized "+
   661  			"block height is %d when %d was expected",
   662  			serializedHeight, wantHeight)
   663  		return ruleError(ErrBadCoinbaseHeight, str)
   664  	}
   665  	return nil
   666  }
   667  
   668  // checkBlockHeaderContext performs several validation checks on the block header
   669  // which depend on its position within the block chain.
   670  //
   671  // The flags modify the behavior of this function as follows:
   672  //   - BFFastAdd: All checks except those involving comparing the header against
   673  //     the checkpoints are not performed.
   674  //
   675  // This function MUST be called with the chain state lock held (for writes).
   676  func (b *BlockChain) checkBlockHeaderContext(header *wire.BlockHeader, prevNode *blockNode, flags BehaviorFlags) error {
   677  	fastAdd := flags&BFFastAdd == BFFastAdd
   678  	if !fastAdd {
   679  		// Ensure the difficulty specified in the block header matches
   680  		// the calculated difficulty based on the previous block and
   681  		// difficulty retarget rules.
   682  		expectedDifficulty, err := b.calcNextRequiredDifficulty(prevNode,
   683  			header.Timestamp)
   684  		if err != nil {
   685  			return err
   686  		}
   687  		blockDifficulty := header.Bits
   688  		if blockDifficulty != expectedDifficulty {
   689  			str := "block difficulty of %d is not the expected value of %d"
   690  			str = fmt.Sprintf(str, blockDifficulty, expectedDifficulty)
   691  			return ruleError(ErrUnexpectedDifficulty, str)
   692  		}
   693  
   694  		// Ensure the timestamp for the block header is after the
   695  		// median time of the last several blocks (medianTimeBlocks).
   696  		medianTime := prevNode.CalcPastMedianTime()
   697  		if !header.Timestamp.After(medianTime) {
   698  			str := "block timestamp of %v is not after expected %v"
   699  			str = fmt.Sprintf(str, header.Timestamp, medianTime)
   700  			return ruleError(ErrTimeTooOld, str)
   701  		}
   702  	}
   703  
   704  	// The height of this block is one more than the referenced previous
   705  	// block.
   706  	blockHeight := prevNode.height + 1
   707  
   708  	// Ensure chain matches up to predetermined checkpoints.
   709  	blockHash := header.BlockHash()
   710  	if !b.verifyCheckpoint(blockHeight, &blockHash) {
   711  		str := fmt.Sprintf("block at height %d does not match "+
   712  			"checkpoint hash", blockHeight)
   713  		return ruleError(ErrBadCheckpoint, str)
   714  	}
   715  
   716  	// Find the previous checkpoint and prevent blocks which fork the main
   717  	// chain before it.  This prevents storage of new, otherwise valid,
   718  	// blocks which build off of old blocks that are likely at a much easier
   719  	// difficulty and therefore could be used to waste cache and disk space.
   720  	checkpointNode, err := b.findPreviousCheckpoint()
   721  	if err != nil {
   722  		return err
   723  	}
   724  	if checkpointNode != nil && blockHeight < checkpointNode.height {
   725  		str := fmt.Sprintf("block at height %d forks the main chain "+
   726  			"before the previous checkpoint at height %d",
   727  			blockHeight, checkpointNode.height)
   728  		return ruleError(ErrForkTooOld, str)
   729  	}
   730  
   731  	// Reject outdated block versions once a majority of the network
   732  	// has upgraded.  These were originally voted on by BIP0034,
   733  	// BIP0065, and BIP0066.
   734  	params := b.chainParams
   735  	if header.Version < 2 && blockHeight >= params.BIP0034Height ||
   736  		header.Version < 3 && blockHeight >= params.BIP0066Height ||
   737  		header.Version < 4 && blockHeight >= params.BIP0065Height {
   738  
   739  		str := "new blocks with version %d are no longer valid"
   740  		str = fmt.Sprintf(str, header.Version)
   741  		return ruleError(ErrBlockVersionTooOld, str)
   742  	}
   743  
   744  	return nil
   745  }
   746  
   747  // checkBlockContext peforms several validation checks on the block which depend
   748  // on its position within the block chain.
   749  //
   750  // The flags modify the behavior of this function as follows:
   751  //   - BFFastAdd: The transaction are not checked to see if they are finalized
   752  //     and the somewhat expensive BIP0034 validation is not performed.
   753  //
   754  // The flags are also passed to checkBlockHeaderContext.  See its documentation
   755  // for how the flags modify its behavior.
   756  //
   757  // This function MUST be called with the chain state lock held (for writes).
   758  func (b *BlockChain) checkBlockContext(block *btcutil.Block, prevNode *blockNode, flags BehaviorFlags) error {
   759  	// Perform all block header related validation checks.
   760  	header := &block.MsgBlock().Header
   761  	err := b.checkBlockHeaderContext(header, prevNode, flags)
   762  	if err != nil {
   763  		return err
   764  	}
   765  
   766  	fastAdd := flags&BFFastAdd == BFFastAdd
   767  	if !fastAdd {
   768  		// Obtain the latest state of the deployed CSV soft-fork in
   769  		// order to properly guard the new validation behavior based on
   770  		// the current BIP 9 version bits state.
   771  		csvState, err := b.deploymentState(prevNode, chaincfg.DeploymentCSV)
   772  		if err != nil {
   773  			return err
   774  		}
   775  
   776  		// Once the CSV soft-fork is fully active, we'll switch to
   777  		// using the current median time past of the past block's
   778  		// timestamps for all lock-time based checks.
   779  		blockTime := header.Timestamp
   780  		if csvState == ThresholdActive {
   781  			blockTime = prevNode.CalcPastMedianTime()
   782  		}
   783  
   784  		// The height of this block is one more than the referenced
   785  		// previous block.
   786  		blockHeight := prevNode.height + 1
   787  
   788  		// Ensure all transactions in the block are finalized.
   789  		for _, tx := range block.Transactions() {
   790  			if !IsFinalizedTransaction(tx, blockHeight,
   791  				blockTime) {
   792  
   793  				str := fmt.Sprintf("block contains unfinalized "+
   794  					"transaction %v", tx.Hash())
   795  				return ruleError(ErrUnfinalizedTx, str)
   796  			}
   797  		}
   798  
   799  		// Ensure coinbase starts with serialized block heights for
   800  		// blocks whose version is the serializedHeightVersion or newer
   801  		// once a majority of the network has upgraded.  This is part of
   802  		// BIP0034.
   803  		if ShouldHaveSerializedBlockHeight(header) &&
   804  			blockHeight >= b.chainParams.BIP0034Height {
   805  
   806  			coinbaseTx := block.Transactions()[0]
   807  			err := checkSerializedHeight(coinbaseTx, blockHeight)
   808  			if err != nil {
   809  				return err
   810  			}
   811  		}
   812  
   813  		// Query for the Version Bits state for the segwit soft-fork
   814  		// deployment. If segwit is active, we'll switch over to
   815  		// enforcing all the new rules.
   816  		segwitState, err := b.deploymentState(prevNode,
   817  			chaincfg.DeploymentSegwit)
   818  		if err != nil {
   819  			return err
   820  		}
   821  
   822  		// If segwit is active, then we'll need to fully validate the
   823  		// new witness commitment for adherence to the rules.
   824  		if segwitState == ThresholdActive {
   825  			// Validate the witness commitment (if any) within the
   826  			// block.  This involves asserting that if the coinbase
   827  			// contains the special commitment output, then this
   828  			// merkle root matches a computed merkle root of all
   829  			// the wtxid's of the transactions within the block. In
   830  			// addition, various other checks against the
   831  			// coinbase's witness stack.
   832  			if err := ValidateWitnessCommitment(block); err != nil {
   833  				return err
   834  			}
   835  
   836  			// Once the witness commitment, witness nonce, and sig
   837  			// op cost have been validated, we can finally assert
   838  			// that the block's weight doesn't exceed the current
   839  			// consensus parameter.
   840  			blockWeight := GetBlockWeight(block)
   841  			if blockWeight > MaxBlockWeight {
   842  				str := fmt.Sprintf("block's weight metric is "+
   843  					"too high - got %v, max %v",
   844  					blockWeight, MaxBlockWeight)
   845  				return ruleError(ErrBlockWeightTooHigh, str)
   846  			}
   847  		}
   848  	}
   849  
   850  	return nil
   851  }
   852  
   853  // checkBIP0030 ensures blocks do not contain duplicate transactions which
   854  // 'overwrite' older transactions that are not fully spent.  This prevents an
   855  // attack where a coinbase and all of its dependent transactions could be
   856  // duplicated to effectively revert the overwritten transactions to a single
   857  // confirmation thereby making them vulnerable to a double spend.
   858  //
   859  // For more details, see
   860  // https://github.com/bitcoin/bips/blob/master/bip-0030.mediawiki and
   861  // http://r6.ca/blog/20120206T005236Z.html.
   862  //
   863  // This function MUST be called with the chain state lock held (for reads).
   864  func (b *BlockChain) checkBIP0030(node *blockNode, block *btcutil.Block, view *UtxoViewpoint) error {
   865  	// Fetch utxos for all of the transaction ouputs in this block.
   866  	// Typically, there will not be any utxos for any of the outputs.
   867  	fetchSet := make(map[wire.OutPoint]struct{})
   868  	for _, tx := range block.Transactions() {
   869  		prevOut := wire.OutPoint{Hash: *tx.Hash()}
   870  		for txOutIdx := range tx.MsgTx().TxOut {
   871  			prevOut.Index = uint32(txOutIdx)
   872  			fetchSet[prevOut] = struct{}{}
   873  		}
   874  	}
   875  	err := view.fetchUtxos(b.db, fetchSet)
   876  	if err != nil {
   877  		return err
   878  	}
   879  
   880  	// Duplicate transactions are only allowed if the previous transaction
   881  	// is fully spent.
   882  	for outpoint := range fetchSet {
   883  		utxo := view.LookupEntry(outpoint)
   884  		if utxo != nil && !utxo.IsSpent() {
   885  			str := fmt.Sprintf("tried to overwrite transaction %v "+
   886  				"at block height %d that is not fully spent",
   887  				outpoint.Hash, utxo.BlockHeight())
   888  			return ruleError(ErrOverwriteTx, str)
   889  		}
   890  	}
   891  
   892  	return nil
   893  }
   894  
   895  // CheckTransactionInputs performs a series of checks on the inputs to a
   896  // transaction to ensure they are valid.  An example of some of the checks
   897  // include verifying all inputs exist, ensuring the coinbase seasoning
   898  // requirements are met, detecting double spends, validating all values and fees
   899  // are in the legal range and the total output amount doesn't exceed the input
   900  // amount, and verifying the signatures to prove the spender was the owner of
   901  // the bitcoins and therefore allowed to spend them.  As it checks the inputs,
   902  // it also calculates the total fees for the transaction and returns that value.
   903  //
   904  // NOTE: The transaction MUST have already been sanity checked with the
   905  // CheckTransactionSanity function prior to calling this function.
   906  func CheckTransactionInputs(tx *btcutil.Tx, txHeight int32, utxoView *UtxoViewpoint, chainParams *chaincfg.Params) (int64, error) {
   907  	// Coinbase transactions have no inputs.
   908  	if IsCoinBase(tx) {
   909  		return 0, nil
   910  	}
   911  
   912  	var totalSatoshiIn int64
   913  	for txInIndex, txIn := range tx.MsgTx().TxIn {
   914  		// Ensure the referenced input transaction is available.
   915  		utxo := utxoView.LookupEntry(txIn.PreviousOutPoint)
   916  		if utxo == nil || utxo.IsSpent() {
   917  			str := fmt.Sprintf("output %v referenced from "+
   918  				"transaction %s:%d either does not exist or "+
   919  				"has already been spent", txIn.PreviousOutPoint,
   920  				tx.Hash(), txInIndex)
   921  			return 0, ruleError(ErrMissingTxOut, str)
   922  		}
   923  
   924  		// Ensure the transaction is not spending coins which have not
   925  		// yet reached the required coinbase maturity.
   926  		if utxo.IsCoinBase() {
   927  			originHeight := utxo.BlockHeight()
   928  			blocksSincePrev := txHeight - originHeight
   929  			coinbaseMaturity := int32(chainParams.CoinbaseMaturity)
   930  			if blocksSincePrev < coinbaseMaturity {
   931  				str := fmt.Sprintf("tried to spend coinbase "+
   932  					"transaction output %v from height %v "+
   933  					"at height %v before required maturity "+
   934  					"of %v blocks", txIn.PreviousOutPoint,
   935  					originHeight, txHeight,
   936  					coinbaseMaturity)
   937  				return 0, ruleError(ErrImmatureSpend, str)
   938  			}
   939  		}
   940  
   941  		// Ensure the transaction amounts are in range.  Each of the
   942  		// output values of the input transactions must not be negative
   943  		// or more than the max allowed per transaction.  All amounts in
   944  		// a transaction are in a unit value known as a satoshi.  One
   945  		// bitcoin is a quantity of satoshi as defined by the
   946  		// SatoshiPerBitcoin constant.
   947  		originTxSatoshi := utxo.Amount()
   948  		if originTxSatoshi < 0 {
   949  			str := fmt.Sprintf("transaction output has negative "+
   950  				"value of %v", btcutil.Amount(originTxSatoshi))
   951  			return 0, ruleError(ErrBadTxOutValue, str)
   952  		}
   953  		if originTxSatoshi > btcutil.MaxSatoshi {
   954  			str := fmt.Sprintf("transaction output value of %v is "+
   955  				"higher than max allowed value of %v",
   956  				btcutil.Amount(originTxSatoshi),
   957  				btcutil.MaxSatoshi)
   958  			return 0, ruleError(ErrBadTxOutValue, str)
   959  		}
   960  
   961  		// The total of all outputs must not be more than the max
   962  		// allowed per transaction.  Also, we could potentially overflow
   963  		// the accumulator so check for overflow.
   964  		lastSatoshiIn := totalSatoshiIn
   965  		totalSatoshiIn += originTxSatoshi
   966  		if totalSatoshiIn < lastSatoshiIn ||
   967  			totalSatoshiIn > btcutil.MaxSatoshi {
   968  			str := fmt.Sprintf("total value of all transaction "+
   969  				"inputs is %v which is higher than max "+
   970  				"allowed value of %v", totalSatoshiIn,
   971  				btcutil.MaxSatoshi)
   972  			return 0, ruleError(ErrBadTxOutValue, str)
   973  		}
   974  	}
   975  
   976  	// Calculate the total output amount for this transaction.  It is safe
   977  	// to ignore overflow and out of range errors here because those error
   978  	// conditions would have already been caught by checkTransactionSanity.
   979  	var totalSatoshiOut int64
   980  	for _, txOut := range tx.MsgTx().TxOut {
   981  		totalSatoshiOut += txOut.Value
   982  	}
   983  
   984  	// Ensure the transaction does not spend more than its inputs.
   985  	if totalSatoshiIn < totalSatoshiOut {
   986  		str := fmt.Sprintf("total value of all transaction inputs for "+
   987  			"transaction %v is %v which is less than the amount "+
   988  			"spent of %v", tx.Hash(), totalSatoshiIn, totalSatoshiOut)
   989  		return 0, ruleError(ErrSpendTooHigh, str)
   990  	}
   991  
   992  	// NOTE: bitcoind checks if the transaction fees are < 0 here, but that
   993  	// is an impossible condition because of the check above that ensures
   994  	// the inputs are >= the outputs.
   995  	txFeeInSatoshi := totalSatoshiIn - totalSatoshiOut
   996  	return txFeeInSatoshi, nil
   997  }
   998  
   999  // checkConnectBlock performs several checks to confirm connecting the passed
  1000  // block to the chain represented by the passed view does not violate any rules.
  1001  // In addition, the passed view is updated to spend all of the referenced
  1002  // outputs and add all of the new utxos created by block.  Thus, the view will
  1003  // represent the state of the chain as if the block were actually connected and
  1004  // consequently the best hash for the view is also updated to passed block.
  1005  //
  1006  // An example of some of the checks performed are ensuring connecting the block
  1007  // would not cause any duplicate transaction hashes for old transactions that
  1008  // aren't already fully spent, double spends, exceeding the maximum allowed
  1009  // signature operations per block, invalid values in relation to the expected
  1010  // block subsidy, or fail transaction script validation.
  1011  //
  1012  // The CheckConnectBlockTemplate function makes use of this function to perform
  1013  // the bulk of its work.  The only difference is this function accepts a node
  1014  // which may or may not require reorganization to connect it to the main chain
  1015  // whereas CheckConnectBlockTemplate creates a new node which specifically
  1016  // connects to the end of the current main chain and then calls this function
  1017  // with that node.
  1018  //
  1019  // This function MUST be called with the chain state lock held (for writes).
  1020  func (b *BlockChain) checkConnectBlock(node *blockNode, block *btcutil.Block, view *UtxoViewpoint, stxos *[]SpentTxOut) error {
  1021  	// If the side chain blocks end up in the database, a call to
  1022  	// CheckBlockSanity should be done here in case a previous version
  1023  	// allowed a block that is no longer valid.  However, since the
  1024  	// implementation only currently uses memory for the side chain blocks,
  1025  	// it isn't currently necessary.
  1026  
  1027  	// The coinbase for the Genesis block is not spendable, so just return
  1028  	// an error now.
  1029  	if node.hash.IsEqual(b.chainParams.GenesisHash) {
  1030  		str := "the coinbase for the genesis block is not spendable"
  1031  		return ruleError(ErrMissingTxOut, str)
  1032  	}
  1033  
  1034  	// Ensure the view is for the node being checked.
  1035  	parentHash := &block.MsgBlock().Header.PrevBlock
  1036  	if !view.BestHash().IsEqual(parentHash) {
  1037  		return AssertError(fmt.Sprintf("inconsistent view when "+
  1038  			"checking block connection: best hash is %v instead "+
  1039  			"of expected %v", view.BestHash(), parentHash))
  1040  	}
  1041  
  1042  	// BIP0030 added a rule to prevent blocks which contain duplicate
  1043  	// transactions that 'overwrite' older transactions which are not fully
  1044  	// spent.  See the documentation for checkBIP0030 for more details.
  1045  	//
  1046  	// There are two blocks in the chain which violate this rule, so the
  1047  	// check must be skipped for those blocks.  The isBIP0030Node function
  1048  	// is used to determine if this block is one of the two blocks that must
  1049  	// be skipped.
  1050  	//
  1051  	// In addition, as of BIP0034, duplicate coinbases are no longer
  1052  	// possible due to its requirement for including the block height in the
  1053  	// coinbase and thus it is no longer possible to create transactions
  1054  	// that 'overwrite' older ones.  Therefore, only enforce the rule if
  1055  	// BIP0034 is not yet active.  This is a useful optimization because the
  1056  	// BIP0030 check is expensive since it involves a ton of cache misses in
  1057  	// the utxoset.
  1058  	if !isBIP0030Node(node) && (node.height < b.chainParams.BIP0034Height) {
  1059  		err := b.checkBIP0030(node, block, view)
  1060  		if err != nil {
  1061  			return err
  1062  		}
  1063  	}
  1064  
  1065  	// Load all of the utxos referenced by the inputs for all transactions
  1066  	// in the block don't already exist in the utxo view from the database.
  1067  	//
  1068  	// These utxo entries are needed for verification of things such as
  1069  	// transaction inputs, counting pay-to-script-hashes, and scripts.
  1070  	err := view.fetchInputUtxos(b.db, block)
  1071  	if err != nil {
  1072  		return err
  1073  	}
  1074  
  1075  	// BIP0016 describes a pay-to-script-hash type that is considered a
  1076  	// "standard" type.  The rules for this BIP only apply to transactions
  1077  	// after the timestamp defined by txscript.Bip16Activation.  See
  1078  	// https://en.bitcoin.it/wiki/BIP_0016 for more details.
  1079  	enforceBIP0016 := node.timestamp >= txscript.Bip16Activation.Unix()
  1080  
  1081  	// Query for the Version Bits state for the segwit soft-fork
  1082  	// deployment. If segwit is active, we'll switch over to enforcing all
  1083  	// the new rules.
  1084  	segwitState, err := b.deploymentState(node.parent, chaincfg.DeploymentSegwit)
  1085  	if err != nil {
  1086  		return err
  1087  	}
  1088  	enforceSegWit := segwitState == ThresholdActive
  1089  
  1090  	// The number of signature operations must be less than the maximum
  1091  	// allowed per block.  Note that the preliminary sanity checks on a
  1092  	// block also include a check similar to this one, but this check
  1093  	// expands the count to include a precise count of pay-to-script-hash
  1094  	// signature operations in each of the input transaction public key
  1095  	// scripts.
  1096  	transactions := block.Transactions()
  1097  	totalSigOpCost := 0
  1098  	for i, tx := range transactions {
  1099  		// Since the first (and only the first) transaction has
  1100  		// already been verified to be a coinbase transaction,
  1101  		// use i == 0 as an optimization for the flag to
  1102  		// countP2SHSigOps for whether or not the transaction is
  1103  		// a coinbase transaction rather than having to do a
  1104  		// full coinbase check again.
  1105  		sigOpCost, err := GetSigOpCost(tx, i == 0, view, enforceBIP0016,
  1106  			enforceSegWit)
  1107  		if err != nil {
  1108  			return err
  1109  		}
  1110  
  1111  		// Check for overflow or going over the limits.  We have to do
  1112  		// this on every loop iteration to avoid overflow.
  1113  		lastSigOpCost := totalSigOpCost
  1114  		totalSigOpCost += sigOpCost
  1115  		if totalSigOpCost < lastSigOpCost || totalSigOpCost > MaxBlockSigOpsCost {
  1116  			str := fmt.Sprintf("block contains too many "+
  1117  				"signature operations - got %v, max %v",
  1118  				totalSigOpCost, MaxBlockSigOpsCost)
  1119  			return ruleError(ErrTooManySigOps, str)
  1120  		}
  1121  	}
  1122  
  1123  	// Perform several checks on the inputs for each transaction.  Also
  1124  	// accumulate the total fees.  This could technically be combined with
  1125  	// the loop above instead of running another loop over the transactions,
  1126  	// but by separating it we can avoid running the more expensive (though
  1127  	// still relatively cheap as compared to running the scripts) checks
  1128  	// against all the inputs when the signature operations are out of
  1129  	// bounds.
  1130  	var totalFees int64
  1131  	for _, tx := range transactions {
  1132  		txFee, err := CheckTransactionInputs(tx, node.height, view,
  1133  			b.chainParams)
  1134  		if err != nil {
  1135  			return err
  1136  		}
  1137  
  1138  		// Sum the total fees and ensure we don't overflow the
  1139  		// accumulator.
  1140  		lastTotalFees := totalFees
  1141  		totalFees += txFee
  1142  		if totalFees < lastTotalFees {
  1143  			return ruleError(ErrBadFees, "total fees for block "+
  1144  				"overflows accumulator")
  1145  		}
  1146  
  1147  		// Add all of the outputs for this transaction which are not
  1148  		// provably unspendable as available utxos.  Also, the passed
  1149  		// spent txos slice is updated to contain an entry for each
  1150  		// spent txout in the order each transaction spends them.
  1151  		err = view.connectTransaction(tx, node.height, stxos)
  1152  		if err != nil {
  1153  			return err
  1154  		}
  1155  	}
  1156  
  1157  	// The total output values of the coinbase transaction must not exceed
  1158  	// the expected subsidy value plus total transaction fees gained from
  1159  	// mining the block.  It is safe to ignore overflow and out of range
  1160  	// errors here because those error conditions would have already been
  1161  	// caught by checkTransactionSanity.
  1162  	var totalSatoshiOut int64
  1163  	for _, txOut := range transactions[0].MsgTx().TxOut {
  1164  		totalSatoshiOut += txOut.Value
  1165  	}
  1166  	expectedSatoshiOut := CalcBlockSubsidy(node.height, b.chainParams) +
  1167  		totalFees
  1168  	if totalSatoshiOut > expectedSatoshiOut {
  1169  		str := fmt.Sprintf("coinbase transaction for block pays %v "+
  1170  			"which is more than expected value of %v",
  1171  			totalSatoshiOut, expectedSatoshiOut)
  1172  		return ruleError(ErrBadCoinbaseValue, str)
  1173  	}
  1174  
  1175  	// Don't run scripts if this node is before the latest known good
  1176  	// checkpoint since the validity is verified via the checkpoints (all
  1177  	// transactions are included in the merkle root hash and any changes
  1178  	// will therefore be detected by the next checkpoint).  This is a huge
  1179  	// optimization because running the scripts is the most time consuming
  1180  	// portion of block handling.
  1181  	checkpoint := b.LatestCheckpoint()
  1182  	runScripts := true
  1183  	if checkpoint != nil && node.height <= checkpoint.Height {
  1184  		runScripts = false
  1185  	}
  1186  
  1187  	// Blocks created after the BIP0016 activation time need to have the
  1188  	// pay-to-script-hash checks enabled.
  1189  	var scriptFlags txscript.ScriptFlags
  1190  	if enforceBIP0016 {
  1191  		scriptFlags |= txscript.ScriptBip16
  1192  	}
  1193  
  1194  	// Enforce DER signatures for block versions 3+ once the historical
  1195  	// activation threshold has been reached.  This is part of BIP0066.
  1196  	blockHeader := &block.MsgBlock().Header
  1197  	if blockHeader.Version >= 3 && node.height >= b.chainParams.BIP0066Height {
  1198  		scriptFlags |= txscript.ScriptVerifyDERSignatures
  1199  	}
  1200  
  1201  	// Enforce CHECKLOCKTIMEVERIFY for block versions 4+ once the historical
  1202  	// activation threshold has been reached.  This is part of BIP0065.
  1203  	if blockHeader.Version >= 4 && node.height >= b.chainParams.BIP0065Height {
  1204  		scriptFlags |= txscript.ScriptVerifyCheckLockTimeVerify
  1205  	}
  1206  
  1207  	// Enforce CHECKSEQUENCEVERIFY during all block validation checks once
  1208  	// the soft-fork deployment is fully active.
  1209  	csvState, err := b.deploymentState(node.parent, chaincfg.DeploymentCSV)
  1210  	if err != nil {
  1211  		return err
  1212  	}
  1213  	if csvState == ThresholdActive {
  1214  		// If the CSV soft-fork is now active, then modify the
  1215  		// scriptFlags to ensure that the CSV op code is properly
  1216  		// validated during the script checks bleow.
  1217  		scriptFlags |= txscript.ScriptVerifyCheckSequenceVerify
  1218  
  1219  		// We obtain the MTP of the *previous* block in order to
  1220  		// determine if transactions in the current block are final.
  1221  		medianTime := node.parent.CalcPastMedianTime()
  1222  
  1223  		// Additionally, if the CSV soft-fork package is now active,
  1224  		// then we also enforce the relative sequence number based
  1225  		// lock-times within the inputs of all transactions in this
  1226  		// candidate block.
  1227  		for _, tx := range block.Transactions() {
  1228  			// A transaction can only be included within a block
  1229  			// once the sequence locks of *all* its inputs are
  1230  			// active.
  1231  			sequenceLock, err := b.calcSequenceLock(node, tx, view,
  1232  				false)
  1233  			if err != nil {
  1234  				return err
  1235  			}
  1236  			if !SequenceLockActive(sequenceLock, node.height,
  1237  				medianTime) {
  1238  				str := fmt.Sprintf("block contains " +
  1239  					"transaction whose input sequence " +
  1240  					"locks are not met")
  1241  				return ruleError(ErrUnfinalizedTx, str)
  1242  			}
  1243  		}
  1244  	}
  1245  
  1246  	// Enforce the segwit soft-fork package once the soft-fork has shifted
  1247  	// into the "active" version bits state.
  1248  	if enforceSegWit {
  1249  		scriptFlags |= txscript.ScriptVerifyWitness
  1250  		scriptFlags |= txscript.ScriptStrictMultiSig
  1251  	}
  1252  
  1253  	// Now that the inexpensive checks are done and have passed, verify the
  1254  	// transactions are actually allowed to spend the coins by running the
  1255  	// expensive ECDSA signature check scripts.  Doing this last helps
  1256  	// prevent CPU exhaustion attacks.
  1257  	if runScripts {
  1258  		err := checkBlockScripts(block, view, scriptFlags, b.sigCache,
  1259  			b.hashCache)
  1260  		if err != nil {
  1261  			return err
  1262  		}
  1263  	}
  1264  
  1265  	// Update the best hash for view to include this block since all of its
  1266  	// transactions have been connected.
  1267  	view.SetBestHash(&node.hash)
  1268  
  1269  	return nil
  1270  }
  1271  
  1272  // CheckConnectBlockTemplate fully validates that connecting the passed block to
  1273  // the main chain does not violate any consensus rules, aside from the proof of
  1274  // work requirement. The block must connect to the current tip of the main chain.
  1275  //
  1276  // This function is safe for concurrent access.
  1277  func (b *BlockChain) CheckConnectBlockTemplate(block *btcutil.Block) error {
  1278  	b.chainLock.Lock()
  1279  	defer b.chainLock.Unlock()
  1280  
  1281  	// Skip the proof of work check as this is just a block template.
  1282  	flags := BFNoPoWCheck
  1283  
  1284  	// This only checks whether the block can be connected to the tip of the
  1285  	// current chain.
  1286  	tip := b.bestChain.Tip()
  1287  	header := block.MsgBlock().Header
  1288  	if tip.hash != header.PrevBlock {
  1289  		str := fmt.Sprintf("previous block must be the current chain tip %v, "+
  1290  			"instead got %v", tip.hash, header.PrevBlock)
  1291  		return ruleError(ErrPrevBlockNotBest, str)
  1292  	}
  1293  
  1294  	err := checkBlockSanity(block, b.chainParams.PowLimit, b.timeSource, flags)
  1295  	if err != nil {
  1296  		return err
  1297  	}
  1298  
  1299  	err = b.checkBlockContext(block, tip, flags)
  1300  	if err != nil {
  1301  		return err
  1302  	}
  1303  
  1304  	// Leave the spent txouts entry nil in the state since the information
  1305  	// is not needed and thus extra work can be avoided.
  1306  	view := NewUtxoViewpoint()
  1307  	view.SetBestHash(&tip.hash)
  1308  	newNode := newBlockNode(&header, tip)
  1309  	return b.checkConnectBlock(newNode, block, view, nil)
  1310  }