github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/btcutil/blockchain/validate.go (about)

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