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