github.com/btcsuite/btcd@v0.24.0/txscript/engine.go (about) 1 // Copyright (c) 2013-2018 The btcsuite developers 2 // Copyright (c) 2015-2018 The Decred developers 3 // Use of this source code is governed by an ISC 4 // license that can be found in the LICENSE file. 5 6 package txscript 7 8 import ( 9 "bytes" 10 "crypto/sha256" 11 "fmt" 12 "math/big" 13 "strings" 14 15 "github.com/btcsuite/btcd/btcec/v2" 16 "github.com/btcsuite/btcd/chaincfg/chainhash" 17 "github.com/btcsuite/btcd/wire" 18 ) 19 20 // ScriptFlags is a bitmask defining additional operations or tests that will be 21 // done when executing a script pair. 22 type ScriptFlags uint32 23 24 const ( 25 // ScriptBip16 defines whether the bip16 threshold has passed and thus 26 // pay-to-script hash transactions will be fully validated. 27 ScriptBip16 ScriptFlags = 1 << iota 28 29 // ScriptStrictMultiSig defines whether to verify the stack item 30 // used by CHECKMULTISIG is zero length. 31 ScriptStrictMultiSig 32 33 // ScriptDiscourageUpgradableNops defines whether to verify that 34 // NOP1 through NOP10 are reserved for future soft-fork upgrades. This 35 // flag must not be used for consensus critical code nor applied to 36 // blocks as this flag is only for stricter standard transaction 37 // checks. This flag is only applied when the above opcodes are 38 // executed. 39 ScriptDiscourageUpgradableNops 40 41 // ScriptVerifyCheckLockTimeVerify defines whether to verify that 42 // a transaction output is spendable based on the locktime. 43 // This is BIP0065. 44 ScriptVerifyCheckLockTimeVerify 45 46 // ScriptVerifyCheckSequenceVerify defines whether to allow execution 47 // pathways of a script to be restricted based on the age of the output 48 // being spent. This is BIP0112. 49 ScriptVerifyCheckSequenceVerify 50 51 // ScriptVerifyCleanStack defines that the stack must contain only 52 // one stack element after evaluation and that the element must be 53 // true if interpreted as a boolean. This is rule 6 of BIP0062. 54 // This flag should never be used without the ScriptBip16 flag nor the 55 // ScriptVerifyWitness flag. 56 ScriptVerifyCleanStack 57 58 // ScriptVerifyDERSignatures defines that signatures are required 59 // to compily with the DER format. 60 ScriptVerifyDERSignatures 61 62 // ScriptVerifyLowS defines that signtures are required to comply with 63 // the DER format and whose S value is <= order / 2. This is rule 5 64 // of BIP0062. 65 ScriptVerifyLowS 66 67 // ScriptVerifyMinimalData defines that signatures must use the smallest 68 // push operator. This is both rules 3 and 4 of BIP0062. 69 ScriptVerifyMinimalData 70 71 // ScriptVerifyNullFail defines that signatures must be empty if 72 // a CHECKSIG or CHECKMULTISIG operation fails. 73 ScriptVerifyNullFail 74 75 // ScriptVerifySigPushOnly defines that signature scripts must contain 76 // only pushed data. This is rule 2 of BIP0062. 77 ScriptVerifySigPushOnly 78 79 // ScriptVerifyStrictEncoding defines that signature scripts and 80 // public keys must follow the strict encoding requirements. 81 ScriptVerifyStrictEncoding 82 83 // ScriptVerifyWitness defines whether or not to verify a transaction 84 // output using a witness program template. 85 ScriptVerifyWitness 86 87 // ScriptVerifyDiscourageUpgradeableWitnessProgram makes witness 88 // program with versions 2-16 non-standard. 89 ScriptVerifyDiscourageUpgradeableWitnessProgram 90 91 // ScriptVerifyMinimalIf makes a script with an OP_IF/OP_NOTIF whose 92 // operand is anything other than empty vector or [0x01] non-standard. 93 ScriptVerifyMinimalIf 94 95 // ScriptVerifyWitnessPubKeyType makes a script within a check-sig 96 // operation whose public key isn't serialized in a compressed format 97 // non-standard. 98 ScriptVerifyWitnessPubKeyType 99 100 // ScriptVerifyTaproot defines whether or not to verify a transaction 101 // output using the new taproot validation rules. 102 ScriptVerifyTaproot 103 104 // ScriptVerifyDiscourageUpgradeableWitnessProgram defines whether or 105 // not to consider any new/unknown taproot leaf versions as 106 // non-standard. 107 ScriptVerifyDiscourageUpgradeableTaprootVersion 108 109 // ScriptVerifyDiscourageOpSuccess defines whether or not to consider 110 // usage of OP_SUCCESS op codes during tapscript execution as 111 // non-standard. 112 ScriptVerifyDiscourageOpSuccess 113 114 // ScriptVerifyDiscourageUpgradeablePubkeyType defines if unknown 115 // public key versions (during tapscript execution) is non-standard. 116 ScriptVerifyDiscourageUpgradeablePubkeyType 117 ) 118 119 const ( 120 // MaxStackSize is the maximum combined height of stack and alt stack 121 // during execution. 122 MaxStackSize = 1000 123 124 // MaxScriptSize is the maximum allowed length of a raw script. 125 MaxScriptSize = 10000 126 127 // payToWitnessPubKeyHashDataSize is the size of the witness program's 128 // data push for a pay-to-witness-pub-key-hash output. 129 payToWitnessPubKeyHashDataSize = 20 130 131 // payToWitnessScriptHashDataSize is the size of the witness program's 132 // data push for a pay-to-witness-script-hash output. 133 payToWitnessScriptHashDataSize = 32 134 135 // payToTaprootDataSize is the size of the witness program push for 136 // taproot spends. This will be the serialized x-coordinate of the 137 // top-level taproot output public key. 138 payToTaprootDataSize = 32 139 ) 140 141 const ( 142 // BaseSegwitWitnessVersion is the original witness version that defines 143 // the initial set of segwit validation logic. 144 BaseSegwitWitnessVersion = 0 145 146 // TaprootWitnessVersion is the witness version that defines the new 147 // taproot verification logic. 148 TaprootWitnessVersion = 1 149 ) 150 151 // halforder is used to tame ECDSA malleability (see BIP0062). 152 var halfOrder = new(big.Int).Rsh(btcec.S256().N, 1) 153 154 // taprootExecutionCtx houses the special context-specific information we need 155 // to validate a taproot script spend. This includes the annex, the running sig 156 // op count tally, and other relevant information. 157 type taprootExecutionCtx struct { 158 annex []byte 159 160 codeSepPos uint32 161 162 tapLeafHash chainhash.Hash 163 164 sigOpsBudget int32 165 166 mustSucceed bool 167 } 168 169 // sigOpsDelta is both the starting budget for sig ops for tapscript 170 // verification, as well as the decrease in the total budget when we encounter 171 // a signature. 172 const sigOpsDelta = 50 173 174 // tallysigOp attempts to decrease the current sig ops budget by sigOpsDelta. 175 // An error is returned if after subtracting the delta, the budget is below 176 // zero. 177 func (t *taprootExecutionCtx) tallysigOp() error { 178 t.sigOpsBudget -= sigOpsDelta 179 180 if t.sigOpsBudget < 0 { 181 return scriptError(ErrTaprootMaxSigOps, "") 182 } 183 184 return nil 185 } 186 187 // newTaprootExecutionCtx returns a fresh instance of the taproot execution 188 // context. 189 func newTaprootExecutionCtx(inputWitnessSize int32) *taprootExecutionCtx { 190 return &taprootExecutionCtx{ 191 codeSepPos: blankCodeSepValue, 192 sigOpsBudget: sigOpsDelta + inputWitnessSize, 193 } 194 } 195 196 // Engine is the virtual machine that executes scripts. 197 type Engine struct { 198 // The following fields are set when the engine is created and must not be 199 // changed afterwards. The entries of the signature cache are mutated 200 // during execution, however, the cache pointer itself is not changed. 201 // 202 // flags specifies the additional flags which modify the execution behavior 203 // of the engine. 204 // 205 // tx identifies the transaction that contains the input which in turn 206 // contains the signature script being executed. 207 // 208 // txIdx identifies the input index within the transaction that contains 209 // the signature script being executed. 210 // 211 // version specifies the version of the public key script to execute. Since 212 // signature scripts redeem public keys scripts, this means the same version 213 // also extends to signature scripts and redeem scripts in the case of 214 // pay-to-script-hash. 215 // 216 // bip16 specifies that the public key script is of a special form that 217 // indicates it is a BIP16 pay-to-script-hash and therefore the 218 // execution must be treated as such. 219 // 220 // sigCache caches the results of signature verifications. This is useful 221 // since transaction scripts are often executed more than once from various 222 // contexts (e.g. new block templates, when transactions are first seen 223 // prior to being mined, part of full block verification, etc). 224 // 225 // hashCache caches the midstate of segwit v0 and v1 sighashes to 226 // optimize worst-case hashing complexity. 227 // 228 // prevOutFetcher is used to look up all the previous output of 229 // taproot transactions, as that information is hashed into the 230 // sighash digest for such inputs. 231 flags ScriptFlags 232 tx wire.MsgTx 233 txIdx int 234 version uint16 235 bip16 bool 236 sigCache *SigCache 237 hashCache *TxSigHashes 238 prevOutFetcher PrevOutputFetcher 239 240 // The following fields handle keeping track of the current execution state 241 // of the engine. 242 // 243 // scripts houses the raw scripts that are executed by the engine. This 244 // includes the signature script as well as the public key script. It also 245 // includes the redeem script in the case of pay-to-script-hash. 246 // 247 // scriptIdx tracks the index into the scripts array for the current program 248 // counter. 249 // 250 // opcodeIdx tracks the number of the opcode within the current script for 251 // the current program counter. Note that it differs from the actual byte 252 // index into the script and is really only used for disassembly purposes. 253 // 254 // lastCodeSep specifies the position within the current script of the last 255 // OP_CODESEPARATOR. 256 // 257 // tokenizer provides the token stream of the current script being executed 258 // and doubles as state tracking for the program counter within the script. 259 // 260 // savedFirstStack keeps a copy of the stack from the first script when 261 // performing pay-to-script-hash execution. 262 // 263 // dstack is the primary data stack the various opcodes push and pop data 264 // to and from during execution. 265 // 266 // astack is the alternate data stack the various opcodes push and pop data 267 // to and from during execution. 268 // 269 // condStack tracks the conditional execution state with support for 270 // multiple nested conditional execution opcodes. 271 // 272 // numOps tracks the total number of non-push operations in a script and is 273 // primarily used to enforce maximum limits. 274 scripts [][]byte 275 scriptIdx int 276 opcodeIdx int 277 lastCodeSep int 278 tokenizer ScriptTokenizer 279 savedFirstStack [][]byte 280 dstack stack 281 astack stack 282 condStack []int 283 numOps int 284 witnessVersion int 285 witnessProgram []byte 286 inputAmount int64 287 taprootCtx *taprootExecutionCtx 288 289 // stepCallback is an optional function that will be called every time 290 // a step has been performed during script execution. 291 // 292 // NOTE: This is only meant to be used in debugging, and SHOULD NOT BE 293 // USED during regular operation. 294 stepCallback func(*StepInfo) error 295 } 296 297 // StepInfo houses the current VM state information that is passed back to the 298 // stepCallback during script execution. 299 type StepInfo struct { 300 // ScriptIndex is the index of the script currently being executed by 301 // the Engine. 302 ScriptIndex int 303 304 // OpcodeIndex is the index of the next opcode that will be executed. 305 // In case the execution has completed, the opcode index will be 306 // incrementet beyond the number of the current script's opcodes. This 307 // indicates no new script is being executed, and execution is done. 308 OpcodeIndex int 309 310 // Stack is the Engine's current content on the stack: 311 Stack [][]byte 312 313 // AltStack is the Engine's current content on the alt stack. 314 AltStack [][]byte 315 } 316 317 // hasFlag returns whether the script engine instance has the passed flag set. 318 func (vm *Engine) hasFlag(flag ScriptFlags) bool { 319 return vm.flags&flag == flag 320 } 321 322 // isBranchExecuting returns whether or not the current conditional branch is 323 // actively executing. For example, when the data stack has an OP_FALSE on it 324 // and an OP_IF is encountered, the branch is inactive until an OP_ELSE or 325 // OP_ENDIF is encountered. It properly handles nested conditionals. 326 func (vm *Engine) isBranchExecuting() bool { 327 if len(vm.condStack) == 0 { 328 return true 329 } 330 return vm.condStack[len(vm.condStack)-1] == OpCondTrue 331 } 332 333 // isOpcodeDisabled returns whether or not the opcode is disabled and thus is 334 // always bad to see in the instruction stream (even if turned off by a 335 // conditional). 336 func isOpcodeDisabled(opcode byte) bool { 337 switch opcode { 338 case OP_CAT: 339 return true 340 case OP_SUBSTR: 341 return true 342 case OP_LEFT: 343 return true 344 case OP_RIGHT: 345 return true 346 case OP_INVERT: 347 return true 348 case OP_AND: 349 return true 350 case OP_OR: 351 return true 352 case OP_XOR: 353 return true 354 case OP_2MUL: 355 return true 356 case OP_2DIV: 357 return true 358 case OP_MUL: 359 return true 360 case OP_DIV: 361 return true 362 case OP_MOD: 363 return true 364 case OP_LSHIFT: 365 return true 366 case OP_RSHIFT: 367 return true 368 default: 369 return false 370 } 371 } 372 373 // isOpcodeAlwaysIllegal returns whether or not the opcode is always illegal 374 // when passed over by the program counter even if in a non-executed branch (it 375 // isn't a coincidence that they are conditionals). 376 func isOpcodeAlwaysIllegal(opcode byte) bool { 377 switch opcode { 378 case OP_VERIF: 379 return true 380 case OP_VERNOTIF: 381 return true 382 default: 383 return false 384 } 385 } 386 387 // isOpcodeConditional returns whether or not the opcode is a conditional opcode 388 // which changes the conditional execution stack when executed. 389 func isOpcodeConditional(opcode byte) bool { 390 switch opcode { 391 case OP_IF: 392 return true 393 case OP_NOTIF: 394 return true 395 case OP_ELSE: 396 return true 397 case OP_ENDIF: 398 return true 399 default: 400 return false 401 } 402 } 403 404 // checkMinimalDataPush returns whether or not the provided opcode is the 405 // smallest possible way to represent the given data. For example, the value 15 406 // could be pushed with OP_DATA_1 15 (among other variations); however, OP_15 is 407 // a single opcode that represents the same value and is only a single byte 408 // versus two bytes. 409 func checkMinimalDataPush(op *opcode, data []byte) error { 410 opcodeVal := op.value 411 dataLen := len(data) 412 switch { 413 case dataLen == 0 && opcodeVal != OP_0: 414 str := fmt.Sprintf("zero length data push is encoded with opcode %s "+ 415 "instead of OP_0", op.name) 416 return scriptError(ErrMinimalData, str) 417 case dataLen == 1 && data[0] >= 1 && data[0] <= 16: 418 if opcodeVal != OP_1+data[0]-1 { 419 // Should have used OP_1 .. OP_16 420 str := fmt.Sprintf("data push of the value %d encoded with opcode "+ 421 "%s instead of OP_%d", data[0], op.name, data[0]) 422 return scriptError(ErrMinimalData, str) 423 } 424 case dataLen == 1 && data[0] == 0x81: 425 if opcodeVal != OP_1NEGATE { 426 str := fmt.Sprintf("data push of the value -1 encoded with opcode "+ 427 "%s instead of OP_1NEGATE", op.name) 428 return scriptError(ErrMinimalData, str) 429 } 430 case dataLen <= 75: 431 if int(opcodeVal) != dataLen { 432 // Should have used a direct push 433 str := fmt.Sprintf("data push of %d bytes encoded with opcode %s "+ 434 "instead of OP_DATA_%d", dataLen, op.name, dataLen) 435 return scriptError(ErrMinimalData, str) 436 } 437 case dataLen <= 255: 438 if opcodeVal != OP_PUSHDATA1 { 439 str := fmt.Sprintf("data push of %d bytes encoded with opcode %s "+ 440 "instead of OP_PUSHDATA1", dataLen, op.name) 441 return scriptError(ErrMinimalData, str) 442 } 443 case dataLen <= 65535: 444 if opcodeVal != OP_PUSHDATA2 { 445 str := fmt.Sprintf("data push of %d bytes encoded with opcode %s "+ 446 "instead of OP_PUSHDATA2", dataLen, op.name) 447 return scriptError(ErrMinimalData, str) 448 } 449 } 450 return nil 451 } 452 453 // executeOpcode peforms execution on the passed opcode. It takes into account 454 // whether or not it is hidden by conditionals, but some rules still must be 455 // tested in this case. 456 func (vm *Engine) executeOpcode(op *opcode, data []byte) error { 457 // Disabled opcodes are fail on program counter. 458 if isOpcodeDisabled(op.value) { 459 str := fmt.Sprintf("attempt to execute disabled opcode %s", op.name) 460 return scriptError(ErrDisabledOpcode, str) 461 } 462 463 // Always-illegal opcodes are fail on program counter. 464 if isOpcodeAlwaysIllegal(op.value) { 465 str := fmt.Sprintf("attempt to execute reserved opcode %s", op.name) 466 return scriptError(ErrReservedOpcode, str) 467 } 468 469 // Note that this includes OP_RESERVED which counts as a push operation. 470 if vm.taprootCtx == nil && op.value > OP_16 { 471 vm.numOps++ 472 if vm.numOps > MaxOpsPerScript { 473 str := fmt.Sprintf("exceeded max operation limit of %d", 474 MaxOpsPerScript) 475 return scriptError(ErrTooManyOperations, str) 476 } 477 478 } else if len(data) > MaxScriptElementSize { 479 str := fmt.Sprintf("element size %d exceeds max allowed size %d", 480 len(data), MaxScriptElementSize) 481 return scriptError(ErrElementTooBig, str) 482 } 483 484 // Nothing left to do when this is not a conditional opcode and it is 485 // not in an executing branch. 486 if !vm.isBranchExecuting() && !isOpcodeConditional(op.value) { 487 return nil 488 } 489 490 // Ensure all executed data push opcodes use the minimal encoding when 491 // the minimal data verification flag is set. 492 if vm.dstack.verifyMinimalData && vm.isBranchExecuting() && 493 op.value >= 0 && op.value <= OP_PUSHDATA4 { 494 495 if err := checkMinimalDataPush(op, data); err != nil { 496 return err 497 } 498 } 499 500 return op.opfunc(op, data, vm) 501 } 502 503 // checkValidPC returns an error if the current script position is not valid for 504 // execution. 505 func (vm *Engine) checkValidPC() error { 506 if vm.scriptIdx >= len(vm.scripts) { 507 str := fmt.Sprintf("script index %d beyond total scripts %d", 508 vm.scriptIdx, len(vm.scripts)) 509 return scriptError(ErrInvalidProgramCounter, str) 510 } 511 return nil 512 } 513 514 // isWitnessVersionActive returns true if a witness program was extracted 515 // during the initialization of the Engine, and the program's version matches 516 // the specified version. 517 func (vm *Engine) isWitnessVersionActive(version uint) bool { 518 return vm.witnessProgram != nil && uint(vm.witnessVersion) == version 519 } 520 521 // verifyWitnessProgram validates the stored witness program using the passed 522 // witness as input. 523 func (vm *Engine) verifyWitnessProgram(witness wire.TxWitness) error { 524 switch { 525 526 // We're attempting to verify a base (witness version 0) segwit output, 527 // so we'll be looking for either a p2wsh or a p2wkh spend. 528 case vm.isWitnessVersionActive(BaseSegwitWitnessVersion): 529 switch len(vm.witnessProgram) { 530 case payToWitnessPubKeyHashDataSize: // P2WKH 531 // The witness stack should consist of exactly two 532 // items: the signature, and the pubkey. 533 if len(witness) != 2 { 534 err := fmt.Sprintf("should have exactly two "+ 535 "items in witness, instead have %v", len(witness)) 536 return scriptError(ErrWitnessProgramMismatch, err) 537 } 538 539 // Now we'll resume execution as if it were a regular 540 // p2pkh transaction. 541 pkScript, err := payToPubKeyHashScript(vm.witnessProgram) 542 if err != nil { 543 return err 544 } 545 546 const scriptVersion = 0 547 err = checkScriptParses(vm.version, pkScript) 548 if err != nil { 549 return err 550 } 551 552 // Set the stack to the provided witness stack, then 553 // append the pkScript generated above as the next 554 // script to execute. 555 vm.scripts = append(vm.scripts, pkScript) 556 vm.SetStack(witness) 557 558 case payToWitnessScriptHashDataSize: // P2WSH 559 // Additionally, The witness stack MUST NOT be empty at 560 // this point. 561 if len(witness) == 0 { 562 return scriptError(ErrWitnessProgramEmpty, "witness "+ 563 "program empty passed empty witness") 564 } 565 566 // Obtain the witness script which should be the last 567 // element in the passed stack. The size of the script 568 // MUST NOT exceed the max script size. 569 witnessScript := witness[len(witness)-1] 570 if len(witnessScript) > MaxScriptSize { 571 str := fmt.Sprintf("witnessScript size %d "+ 572 "is larger than max allowed size %d", 573 len(witnessScript), MaxScriptSize) 574 return scriptError(ErrScriptTooBig, str) 575 } 576 577 // Ensure that the serialized pkScript at the end of 578 // the witness stack matches the witness program. 579 witnessHash := sha256.Sum256(witnessScript) 580 if !bytes.Equal(witnessHash[:], vm.witnessProgram) { 581 return scriptError(ErrWitnessProgramMismatch, 582 "witness program hash mismatch") 583 } 584 585 // With all the validity checks passed, assert that the 586 // script parses without failure. 587 const scriptVersion = 0 588 err := checkScriptParses(vm.version, witnessScript) 589 if err != nil { 590 return err 591 } 592 593 // The hash matched successfully, so use the witness as 594 // the stack, and set the witnessScript to be the next 595 // script executed. 596 vm.scripts = append(vm.scripts, witnessScript) 597 vm.SetStack(witness[:len(witness)-1]) 598 599 default: 600 errStr := fmt.Sprintf("length of witness program "+ 601 "must either be %v or %v bytes, instead is %v bytes", 602 payToWitnessPubKeyHashDataSize, 603 payToWitnessScriptHashDataSize, 604 len(vm.witnessProgram)) 605 return scriptError(ErrWitnessProgramWrongLength, errStr) 606 } 607 608 // We're attempting to to verify a taproot input, and the witness 609 // program data push is of the expected size, so we'll be looking for a 610 // normal key-path spend, or a merkle proof for a tapscript with 611 // execution afterwards. 612 case vm.isWitnessVersionActive(TaprootWitnessVersion) && 613 len(vm.witnessProgram) == payToTaprootDataSize && !vm.bip16: 614 615 // If taproot isn't currently active, then we'll return a 616 // success here in place as we don't apply the new rules unless 617 // the flag flips, as governed by the version bits deployment. 618 if !vm.hasFlag(ScriptVerifyTaproot) { 619 return nil 620 } 621 622 // If there're no stack elements at all, then this is an 623 // invalid spend. 624 if len(witness) == 0 { 625 return scriptError(ErrWitnessProgramEmpty, "witness "+ 626 "program empty passed empty witness") 627 } 628 629 // At this point, we know taproot is active, so we'll populate 630 // the taproot execution context. 631 vm.taprootCtx = newTaprootExecutionCtx( 632 int32(witness.SerializeSize()), 633 ) 634 635 // If we can detect the annex, then drop that off the stack, 636 // we'll only need it to compute the sighash later. 637 if isAnnexedWitness(witness) { 638 vm.taprootCtx.annex, _ = extractAnnex(witness) 639 640 // Snip the annex off the end of the witness stack. 641 witness = witness[:len(witness)-1] 642 } 643 644 // From here, we'll either be validating a normal key spend, or 645 // a spend from the tap script leaf using a committed leaf. 646 switch { 647 // If there's only a single element left on the stack (the 648 // signature), then we'll apply the normal top-level schnorr 649 // signature verification. 650 case len(witness) == 1: 651 // As we only have a single element left (after maybe 652 // removing the annex), we'll do normal taproot 653 // keyspend validation. 654 rawSig := witness[0] 655 err := VerifyTaprootKeySpend( 656 vm.witnessProgram, rawSig, &vm.tx, vm.txIdx, 657 vm.prevOutFetcher, vm.hashCache, vm.sigCache, 658 ) 659 if err != nil { 660 // TODO(roasbeef): proper error 661 return err 662 } 663 664 // TODO(roasbeef): or remove the other items from the stack? 665 vm.taprootCtx.mustSucceed = true 666 return nil 667 668 // Otherwise, we need to attempt full tapscript leaf 669 // verification in place. 670 default: 671 // First, attempt to parse the control block, if this 672 // isn't formatted properly, then we'll end execution 673 // right here. 674 controlBlock, err := ParseControlBlock( 675 witness[len(witness)-1], 676 ) 677 if err != nil { 678 return err 679 } 680 681 // Now that we know the control block is valid, we'll 682 // verify the top-level taproot commitment, which 683 // proves that the specified script was committed to in 684 // the merkle tree. 685 witnessScript := witness[len(witness)-2] 686 err = VerifyTaprootLeafCommitment( 687 controlBlock, vm.witnessProgram, witnessScript, 688 ) 689 if err != nil { 690 return err 691 } 692 693 // Now that we know the commitment is valid, we'll 694 // check to see if OP_SUCCESS op codes are found in the 695 // script. If so, then we'll return here early as we 696 // skip proper validation. 697 if ScriptHasOpSuccess(witnessScript) { 698 // An op success op code has been found, however if 699 // the policy flag forbidding them is active, then 700 // we'll return an error. 701 if vm.hasFlag(ScriptVerifyDiscourageOpSuccess) { 702 errStr := fmt.Sprintf("script contains " + 703 "OP_SUCCESS op code") 704 return scriptError(ErrDiscourageOpSuccess, errStr) 705 } 706 707 // Otherwise, the script passes scott free. 708 vm.taprootCtx.mustSucceed = true 709 return nil 710 } 711 712 // Before we proceed with normal execution, check the 713 // leaf version of the script, as if the policy flag is 714 // active, then we should only allow the base leaf 715 // version. 716 if controlBlock.LeafVersion != BaseLeafVersion { 717 switch { 718 case vm.hasFlag(ScriptVerifyDiscourageUpgradeableTaprootVersion): 719 errStr := fmt.Sprintf("tapscript is attempting "+ 720 "to use version: %v", controlBlock.LeafVersion) 721 return scriptError( 722 ErrDiscourageUpgradeableTaprootVersion, errStr, 723 ) 724 default: 725 // If the policy flag isn't active, 726 // then execution succeeds here as we 727 // don't know the rules of the future 728 // leaf versions. 729 vm.taprootCtx.mustSucceed = true 730 return nil 731 } 732 } 733 734 // Now that we know we don't have any op success 735 // fields, ensure that the script parses properly. 736 // 737 // TODO(roasbeef): combine w/ the above? 738 err = checkScriptParses(vm.version, witnessScript) 739 if err != nil { 740 return err 741 } 742 743 // Now that we know the script parses, and we have a 744 // valid leaf version, we'll save the tapscript hash of 745 // the leaf, as we need that for signature validation 746 // later. 747 vm.taprootCtx.tapLeafHash = NewBaseTapLeaf( 748 witnessScript, 749 ).TapHash() 750 751 // Otherwise, we'll now "recurse" one level deeper, and 752 // set the remaining witness (leaving off the annex and 753 // the witness script) as the execution stack, and 754 // enter further execution. 755 vm.scripts = append(vm.scripts, witnessScript) 756 vm.SetStack(witness[:len(witness)-2]) 757 } 758 759 case vm.hasFlag(ScriptVerifyDiscourageUpgradeableWitnessProgram): 760 errStr := fmt.Sprintf("new witness program versions "+ 761 "invalid: %v", vm.witnessProgram) 762 763 return scriptError(ErrDiscourageUpgradableWitnessProgram, errStr) 764 default: 765 // If we encounter an unknown witness program version and we 766 // aren't discouraging future unknown witness based soft-forks, 767 // then we de-activate the segwit behavior within the VM for 768 // the remainder of execution. 769 vm.witnessProgram = nil 770 } 771 772 // TODO(roasbeef): other sanity checks here 773 switch { 774 775 // In addition to the normal script element size limits, taproot also 776 // enforces a limit on the max _starting_ stack size. 777 case vm.isWitnessVersionActive(TaprootWitnessVersion): 778 if vm.dstack.Depth() > MaxStackSize { 779 str := fmt.Sprintf("tapscript stack size %d > max allowed %d", 780 vm.dstack.Depth(), MaxStackSize) 781 return scriptError(ErrStackOverflow, str) 782 } 783 784 fallthrough 785 case vm.isWitnessVersionActive(BaseSegwitWitnessVersion): 786 // All elements within the witness stack must not be greater 787 // than the maximum bytes which are allowed to be pushed onto 788 // the stack. 789 for _, witElement := range vm.GetStack() { 790 if len(witElement) > MaxScriptElementSize { 791 str := fmt.Sprintf("element size %d exceeds "+ 792 "max allowed size %d", len(witElement), 793 MaxScriptElementSize) 794 return scriptError(ErrElementTooBig, str) 795 } 796 } 797 798 return nil 799 } 800 801 return nil 802 } 803 804 // DisasmPC returns the string for the disassembly of the opcode that will be 805 // next to execute when Step is called. 806 func (vm *Engine) DisasmPC() (string, error) { 807 if err := vm.checkValidPC(); err != nil { 808 return "", err 809 } 810 811 // Create a copy of the current tokenizer and parse the next opcode in the 812 // copy to avoid mutating the current one. 813 peekTokenizer := vm.tokenizer 814 if !peekTokenizer.Next() { 815 // Note that due to the fact that all scripts are checked for parse 816 // failures before this code ever runs, there should never be an error 817 // here, but check again to be safe in case a refactor breaks that 818 // assumption or new script versions are introduced with different 819 // semantics. 820 if err := peekTokenizer.Err(); err != nil { 821 return "", err 822 } 823 824 // Note that this should be impossible to hit in practice because the 825 // only way it could happen would be for the final opcode of a script to 826 // already be parsed without the script index having been updated, which 827 // is not the case since stepping the script always increments the 828 // script index when parsing and executing the final opcode of a script. 829 // 830 // However, check again to be safe in case a refactor breaks that 831 // assumption or new script versions are introduced with different 832 // semantics. 833 str := fmt.Sprintf("program counter beyond script index %d (bytes %x)", 834 vm.scriptIdx, vm.scripts[vm.scriptIdx]) 835 return "", scriptError(ErrInvalidProgramCounter, str) 836 } 837 838 var buf strings.Builder 839 disasmOpcode(&buf, peekTokenizer.op, peekTokenizer.Data(), false) 840 return fmt.Sprintf("%02x:%04x: %s", vm.scriptIdx, vm.opcodeIdx, 841 buf.String()), nil 842 } 843 844 // DisasmScript returns the disassembly string for the script at the requested 845 // offset index. Index 0 is the signature script and 1 is the public key 846 // script. In the case of pay-to-script-hash, index 2 is the redeem script once 847 // the execution has progressed far enough to have successfully verified script 848 // hash and thus add the script to the scripts to execute. 849 func (vm *Engine) DisasmScript(idx int) (string, error) { 850 if idx >= len(vm.scripts) { 851 str := fmt.Sprintf("script index %d >= total scripts %d", idx, 852 len(vm.scripts)) 853 return "", scriptError(ErrInvalidIndex, str) 854 } 855 856 var disbuf strings.Builder 857 script := vm.scripts[idx] 858 tokenizer := MakeScriptTokenizer(vm.version, script) 859 var opcodeIdx int 860 for tokenizer.Next() { 861 disbuf.WriteString(fmt.Sprintf("%02x:%04x: ", idx, opcodeIdx)) 862 disasmOpcode(&disbuf, tokenizer.op, tokenizer.Data(), false) 863 disbuf.WriteByte('\n') 864 opcodeIdx++ 865 } 866 return disbuf.String(), tokenizer.Err() 867 } 868 869 // CheckErrorCondition returns nil if the running script has ended and was 870 // successful, leaving a a true boolean on the stack. An error otherwise, 871 // including if the script has not finished. 872 func (vm *Engine) CheckErrorCondition(finalScript bool) error { 873 if vm.taprootCtx != nil && vm.taprootCtx.mustSucceed { 874 return nil 875 } 876 877 // Check execution is actually done by ensuring the script index is after 878 // the final script in the array script. 879 if vm.scriptIdx < len(vm.scripts) { 880 return scriptError(ErrScriptUnfinished, 881 "error check when script unfinished") 882 } 883 884 // If we're in version zero witness execution mode, and this was the 885 // final script, then the stack MUST be clean in order to maintain 886 // compatibility with BIP16. 887 if finalScript && vm.isWitnessVersionActive(BaseSegwitWitnessVersion) && 888 vm.dstack.Depth() != 1 { 889 return scriptError(ErrEvalFalse, "witness program must "+ 890 "have clean stack") 891 } 892 893 // The final script must end with exactly one data stack item when the 894 // verify clean stack flag is set. Otherwise, there must be at least one 895 // data stack item in order to interpret it as a boolean. 896 cleanStackActive := vm.hasFlag(ScriptVerifyCleanStack) || vm.taprootCtx != nil 897 if finalScript && cleanStackActive && vm.dstack.Depth() != 1 { 898 899 str := fmt.Sprintf("stack must contain exactly one item (contains %d)", 900 vm.dstack.Depth()) 901 return scriptError(ErrCleanStack, str) 902 } else if vm.dstack.Depth() < 1 { 903 return scriptError(ErrEmptyStack, 904 "stack empty at end of script execution") 905 } 906 907 v, err := vm.dstack.PopBool() 908 if err != nil { 909 return err 910 } 911 if !v { 912 // Log interesting data. 913 log.Tracef("%v", newLogClosure(func() string { 914 var buf strings.Builder 915 buf.WriteString("scripts failed:\n") 916 for i := range vm.scripts { 917 dis, _ := vm.DisasmScript(i) 918 buf.WriteString(fmt.Sprintf("script%d:\n", i)) 919 buf.WriteString(dis) 920 } 921 return buf.String() 922 })) 923 return scriptError(ErrEvalFalse, 924 "false stack entry at end of script execution") 925 } 926 return nil 927 } 928 929 // Step executes the next instruction and moves the program counter to the next 930 // opcode in the script, or the next script if the current has ended. Step will 931 // return true in the case that the last opcode was successfully executed. 932 // 933 // The result of calling Step or any other method is undefined if an error is 934 // returned. 935 func (vm *Engine) Step() (done bool, err error) { 936 // Verify the engine is pointing to a valid program counter. 937 if err := vm.checkValidPC(); err != nil { 938 return true, err 939 } 940 941 // Attempt to parse the next opcode from the current script. 942 if !vm.tokenizer.Next() { 943 // Note that due to the fact that all scripts are checked for parse 944 // failures before this code ever runs, there should never be an error 945 // here, but check again to be safe in case a refactor breaks that 946 // assumption or new script versions are introduced with different 947 // semantics. 948 if err := vm.tokenizer.Err(); err != nil { 949 return false, err 950 } 951 952 str := fmt.Sprintf("attempt to step beyond script index %d (bytes %x)", 953 vm.scriptIdx, vm.scripts[vm.scriptIdx]) 954 return true, scriptError(ErrInvalidProgramCounter, str) 955 } 956 957 // Execute the opcode while taking into account several things such as 958 // disabled opcodes, illegal opcodes, maximum allowed operations per script, 959 // maximum script element sizes, and conditionals. 960 err = vm.executeOpcode(vm.tokenizer.op, vm.tokenizer.Data()) 961 if err != nil { 962 return true, err 963 } 964 965 // The number of elements in the combination of the data and alt stacks 966 // must not exceed the maximum number of stack elements allowed. 967 combinedStackSize := vm.dstack.Depth() + vm.astack.Depth() 968 if combinedStackSize > MaxStackSize { 969 str := fmt.Sprintf("combined stack size %d > max allowed %d", 970 combinedStackSize, MaxStackSize) 971 return false, scriptError(ErrStackOverflow, str) 972 } 973 974 // Prepare for next instruction. 975 vm.opcodeIdx++ 976 if vm.tokenizer.Done() { 977 // Illegal to have a conditional that straddles two scripts. 978 if len(vm.condStack) != 0 { 979 return false, scriptError(ErrUnbalancedConditional, 980 "end of script reached in conditional execution") 981 } 982 983 // Alt stack doesn't persist between scripts. 984 _ = vm.astack.DropN(vm.astack.Depth()) 985 986 // The number of operations is per script. 987 vm.numOps = 0 988 989 // Reset the opcode index for the next script. 990 vm.opcodeIdx = 0 991 992 // Advance to the next script as needed. 993 switch { 994 case vm.scriptIdx == 0 && vm.bip16: 995 vm.scriptIdx++ 996 vm.savedFirstStack = vm.GetStack() 997 998 case vm.scriptIdx == 1 && vm.bip16: 999 // Put us past the end for CheckErrorCondition() 1000 vm.scriptIdx++ 1001 1002 // Check script ran successfully. 1003 err := vm.CheckErrorCondition(false) 1004 if err != nil { 1005 return false, err 1006 } 1007 1008 // Obtain the redeem script from the first stack and ensure it 1009 // parses. 1010 script := vm.savedFirstStack[len(vm.savedFirstStack)-1] 1011 if err := checkScriptParses(vm.version, script); err != nil { 1012 return false, err 1013 } 1014 vm.scripts = append(vm.scripts, script) 1015 1016 // Set stack to be the stack from first script minus the redeem 1017 // script itself 1018 vm.SetStack(vm.savedFirstStack[:len(vm.savedFirstStack)-1]) 1019 1020 case vm.scriptIdx == 1 && vm.witnessProgram != nil, 1021 vm.scriptIdx == 2 && vm.witnessProgram != nil && vm.bip16: // np2sh 1022 1023 vm.scriptIdx++ 1024 1025 witness := vm.tx.TxIn[vm.txIdx].Witness 1026 if err := vm.verifyWitnessProgram(witness); err != nil { 1027 return false, err 1028 } 1029 1030 default: 1031 vm.scriptIdx++ 1032 } 1033 1034 // Skip empty scripts. 1035 if vm.scriptIdx < len(vm.scripts) && len(vm.scripts[vm.scriptIdx]) == 0 { 1036 vm.scriptIdx++ 1037 } 1038 1039 vm.lastCodeSep = 0 1040 if vm.scriptIdx >= len(vm.scripts) { 1041 return true, nil 1042 } 1043 1044 // Finally, update the current tokenizer used to parse through scripts 1045 // one opcode at a time to start from the beginning of the new script 1046 // associated with the program counter. 1047 vm.tokenizer = MakeScriptTokenizer(vm.version, vm.scripts[vm.scriptIdx]) 1048 } 1049 1050 return false, nil 1051 } 1052 1053 // copyStack makes a deep copy of the provided slice. 1054 func copyStack(stk [][]byte) [][]byte { 1055 c := make([][]byte, len(stk)) 1056 for i := range stk { 1057 c[i] = make([]byte, len(stk[i])) 1058 copy(c[i][:], stk[i][:]) 1059 } 1060 1061 return c 1062 } 1063 1064 // Execute will execute all scripts in the script engine and return either nil 1065 // for successful validation or an error if one occurred. 1066 func (vm *Engine) Execute() (err error) { 1067 // All script versions other than 0 currently execute without issue, 1068 // making all outputs to them anyone can pay. In the future this 1069 // will allow for the addition of new scripting languages. 1070 if vm.version != 0 { 1071 return nil 1072 } 1073 1074 // If the stepCallback is set, we start by making a call back with the 1075 // initial engine state. 1076 var stepInfo *StepInfo 1077 if vm.stepCallback != nil { 1078 stepInfo = &StepInfo{ 1079 ScriptIndex: vm.scriptIdx, 1080 OpcodeIndex: vm.opcodeIdx, 1081 Stack: copyStack(vm.dstack.stk), 1082 AltStack: copyStack(vm.astack.stk), 1083 } 1084 err := vm.stepCallback(stepInfo) 1085 if err != nil { 1086 return err 1087 } 1088 } 1089 1090 done := false 1091 for !done { 1092 log.Tracef("%v", newLogClosure(func() string { 1093 dis, err := vm.DisasmPC() 1094 if err != nil { 1095 return fmt.Sprintf("stepping - failed to disasm pc: %v", err) 1096 } 1097 return fmt.Sprintf("stepping %v", dis) 1098 })) 1099 1100 done, err = vm.Step() 1101 if err != nil { 1102 return err 1103 } 1104 log.Tracef("%v", newLogClosure(func() string { 1105 var dstr, astr string 1106 1107 // Log the non-empty stacks when tracing. 1108 if vm.dstack.Depth() != 0 { 1109 dstr = "Stack:\n" + vm.dstack.String() 1110 } 1111 if vm.astack.Depth() != 0 { 1112 astr = "AltStack:\n" + vm.astack.String() 1113 } 1114 1115 return dstr + astr 1116 })) 1117 1118 if vm.stepCallback != nil { 1119 scriptIdx := vm.scriptIdx 1120 opcodeIdx := vm.opcodeIdx 1121 1122 // In case the execution has completed, we keep the 1123 // current script index while increasing the opcode 1124 // index. This is to indicate that no new script is 1125 // being executed. 1126 if done { 1127 scriptIdx = stepInfo.ScriptIndex 1128 opcodeIdx = stepInfo.OpcodeIndex + 1 1129 } 1130 1131 stepInfo = &StepInfo{ 1132 ScriptIndex: scriptIdx, 1133 OpcodeIndex: opcodeIdx, 1134 Stack: copyStack(vm.dstack.stk), 1135 AltStack: copyStack(vm.astack.stk), 1136 } 1137 err := vm.stepCallback(stepInfo) 1138 if err != nil { 1139 return err 1140 } 1141 } 1142 } 1143 1144 return vm.CheckErrorCondition(true) 1145 } 1146 1147 // subScript returns the script since the last OP_CODESEPARATOR. 1148 func (vm *Engine) subScript() []byte { 1149 return vm.scripts[vm.scriptIdx][vm.lastCodeSep:] 1150 } 1151 1152 // checkHashTypeEncoding returns whether or not the passed hashtype adheres to 1153 // the strict encoding requirements if enabled. 1154 func (vm *Engine) checkHashTypeEncoding(hashType SigHashType) error { 1155 if !vm.hasFlag(ScriptVerifyStrictEncoding) { 1156 return nil 1157 } 1158 1159 sigHashType := hashType & ^SigHashAnyOneCanPay 1160 if sigHashType < SigHashAll || sigHashType > SigHashSingle { 1161 str := fmt.Sprintf("invalid hash type 0x%x", hashType) 1162 return scriptError(ErrInvalidSigHashType, str) 1163 } 1164 return nil 1165 } 1166 1167 // isStrictPubKeyEncoding returns whether or not the passed public key adheres 1168 // to the strict encoding requirements. 1169 func isStrictPubKeyEncoding(pubKey []byte) bool { 1170 if len(pubKey) == 33 && (pubKey[0] == 0x02 || pubKey[0] == 0x03) { 1171 // Compressed 1172 return true 1173 } 1174 if len(pubKey) == 65 { 1175 switch pubKey[0] { 1176 case 0x04: 1177 // Uncompressed 1178 return true 1179 1180 case 0x06, 0x07: 1181 // Hybrid 1182 return true 1183 } 1184 } 1185 return false 1186 } 1187 1188 // checkPubKeyEncoding returns whether or not the passed public key adheres to 1189 // the strict encoding requirements if enabled. 1190 func (vm *Engine) checkPubKeyEncoding(pubKey []byte) error { 1191 if vm.hasFlag(ScriptVerifyWitnessPubKeyType) && 1192 vm.isWitnessVersionActive(BaseSegwitWitnessVersion) && 1193 !btcec.IsCompressedPubKey(pubKey) { 1194 1195 str := "only compressed keys are accepted post-segwit" 1196 return scriptError(ErrWitnessPubKeyType, str) 1197 } 1198 1199 if !vm.hasFlag(ScriptVerifyStrictEncoding) { 1200 return nil 1201 } 1202 1203 if len(pubKey) == 33 && (pubKey[0] == 0x02 || pubKey[0] == 0x03) { 1204 // Compressed 1205 return nil 1206 } 1207 if len(pubKey) == 65 && pubKey[0] == 0x04 { 1208 // Uncompressed 1209 return nil 1210 } 1211 1212 return scriptError(ErrPubKeyType, "unsupported public key type") 1213 } 1214 1215 // checkSignatureEncoding returns whether or not the passed signature adheres to 1216 // the strict encoding requirements if enabled. 1217 func (vm *Engine) checkSignatureEncoding(sig []byte) error { 1218 if !vm.hasFlag(ScriptVerifyDERSignatures) && 1219 !vm.hasFlag(ScriptVerifyLowS) && 1220 !vm.hasFlag(ScriptVerifyStrictEncoding) { 1221 1222 return nil 1223 } 1224 1225 // The format of a DER encoded signature is as follows: 1226 // 1227 // 0x30 <total length> 0x02 <length of R> <R> 0x02 <length of S> <S> 1228 // - 0x30 is the ASN.1 identifier for a sequence 1229 // - Total length is 1 byte and specifies length of all remaining data 1230 // - 0x02 is the ASN.1 identifier that specifies an integer follows 1231 // - Length of R is 1 byte and specifies how many bytes R occupies 1232 // - R is the arbitrary length big-endian encoded number which 1233 // represents the R value of the signature. DER encoding dictates 1234 // that the value must be encoded using the minimum possible number 1235 // of bytes. This implies the first byte can only be null if the 1236 // highest bit of the next byte is set in order to prevent it from 1237 // being interpreted as a negative number. 1238 // - 0x02 is once again the ASN.1 integer identifier 1239 // - Length of S is 1 byte and specifies how many bytes S occupies 1240 // - S is the arbitrary length big-endian encoded number which 1241 // represents the S value of the signature. The encoding rules are 1242 // identical as those for R. 1243 const ( 1244 asn1SequenceID = 0x30 1245 asn1IntegerID = 0x02 1246 1247 // minSigLen is the minimum length of a DER encoded signature and is 1248 // when both R and S are 1 byte each. 1249 // 1250 // 0x30 + <1-byte> + 0x02 + 0x01 + <byte> + 0x2 + 0x01 + <byte> 1251 minSigLen = 8 1252 1253 // maxSigLen is the maximum length of a DER encoded signature and is 1254 // when both R and S are 33 bytes each. It is 33 bytes because a 1255 // 256-bit integer requires 32 bytes and an additional leading null byte 1256 // might required if the high bit is set in the value. 1257 // 1258 // 0x30 + <1-byte> + 0x02 + 0x21 + <33 bytes> + 0x2 + 0x21 + <33 bytes> 1259 maxSigLen = 72 1260 1261 // sequenceOffset is the byte offset within the signature of the 1262 // expected ASN.1 sequence identifier. 1263 sequenceOffset = 0 1264 1265 // dataLenOffset is the byte offset within the signature of the expected 1266 // total length of all remaining data in the signature. 1267 dataLenOffset = 1 1268 1269 // rTypeOffset is the byte offset within the signature of the ASN.1 1270 // identifier for R and is expected to indicate an ASN.1 integer. 1271 rTypeOffset = 2 1272 1273 // rLenOffset is the byte offset within the signature of the length of 1274 // R. 1275 rLenOffset = 3 1276 1277 // rOffset is the byte offset within the signature of R. 1278 rOffset = 4 1279 ) 1280 1281 // The signature must adhere to the minimum and maximum allowed length. 1282 sigLen := len(sig) 1283 if sigLen < minSigLen { 1284 str := fmt.Sprintf("malformed signature: too short: %d < %d", sigLen, 1285 minSigLen) 1286 return scriptError(ErrSigTooShort, str) 1287 } 1288 if sigLen > maxSigLen { 1289 str := fmt.Sprintf("malformed signature: too long: %d > %d", sigLen, 1290 maxSigLen) 1291 return scriptError(ErrSigTooLong, str) 1292 } 1293 1294 // The signature must start with the ASN.1 sequence identifier. 1295 if sig[sequenceOffset] != asn1SequenceID { 1296 str := fmt.Sprintf("malformed signature: format has wrong type: %#x", 1297 sig[sequenceOffset]) 1298 return scriptError(ErrSigInvalidSeqID, str) 1299 } 1300 1301 // The signature must indicate the correct amount of data for all elements 1302 // related to R and S. 1303 if int(sig[dataLenOffset]) != sigLen-2 { 1304 str := fmt.Sprintf("malformed signature: bad length: %d != %d", 1305 sig[dataLenOffset], sigLen-2) 1306 return scriptError(ErrSigInvalidDataLen, str) 1307 } 1308 1309 // Calculate the offsets of the elements related to S and ensure S is inside 1310 // the signature. 1311 // 1312 // rLen specifies the length of the big-endian encoded number which 1313 // represents the R value of the signature. 1314 // 1315 // sTypeOffset is the offset of the ASN.1 identifier for S and, like its R 1316 // counterpart, is expected to indicate an ASN.1 integer. 1317 // 1318 // sLenOffset and sOffset are the byte offsets within the signature of the 1319 // length of S and S itself, respectively. 1320 rLen := int(sig[rLenOffset]) 1321 sTypeOffset := rOffset + rLen 1322 sLenOffset := sTypeOffset + 1 1323 if sTypeOffset >= sigLen { 1324 str := "malformed signature: S type indicator missing" 1325 return scriptError(ErrSigMissingSTypeID, str) 1326 } 1327 if sLenOffset >= sigLen { 1328 str := "malformed signature: S length missing" 1329 return scriptError(ErrSigMissingSLen, str) 1330 } 1331 1332 // The lengths of R and S must match the overall length of the signature. 1333 // 1334 // sLen specifies the length of the big-endian encoded number which 1335 // represents the S value of the signature. 1336 sOffset := sLenOffset + 1 1337 sLen := int(sig[sLenOffset]) 1338 if sOffset+sLen != sigLen { 1339 str := "malformed signature: invalid S length" 1340 return scriptError(ErrSigInvalidSLen, str) 1341 } 1342 1343 // R elements must be ASN.1 integers. 1344 if sig[rTypeOffset] != asn1IntegerID { 1345 str := fmt.Sprintf("malformed signature: R integer marker: %#x != %#x", 1346 sig[rTypeOffset], asn1IntegerID) 1347 return scriptError(ErrSigInvalidRIntID, str) 1348 } 1349 1350 // Zero-length integers are not allowed for R. 1351 if rLen == 0 { 1352 str := "malformed signature: R length is zero" 1353 return scriptError(ErrSigZeroRLen, str) 1354 } 1355 1356 // R must not be negative. 1357 if sig[rOffset]&0x80 != 0 { 1358 str := "malformed signature: R is negative" 1359 return scriptError(ErrSigNegativeR, str) 1360 } 1361 1362 // Null bytes at the start of R are not allowed, unless R would otherwise be 1363 // interpreted as a negative number. 1364 if rLen > 1 && sig[rOffset] == 0x00 && sig[rOffset+1]&0x80 == 0 { 1365 str := "malformed signature: R value has too much padding" 1366 return scriptError(ErrSigTooMuchRPadding, str) 1367 } 1368 1369 // S elements must be ASN.1 integers. 1370 if sig[sTypeOffset] != asn1IntegerID { 1371 str := fmt.Sprintf("malformed signature: S integer marker: %#x != %#x", 1372 sig[sTypeOffset], asn1IntegerID) 1373 return scriptError(ErrSigInvalidSIntID, str) 1374 } 1375 1376 // Zero-length integers are not allowed for S. 1377 if sLen == 0 { 1378 str := "malformed signature: S length is zero" 1379 return scriptError(ErrSigZeroSLen, str) 1380 } 1381 1382 // S must not be negative. 1383 if sig[sOffset]&0x80 != 0 { 1384 str := "malformed signature: S is negative" 1385 return scriptError(ErrSigNegativeS, str) 1386 } 1387 1388 // Null bytes at the start of S are not allowed, unless S would otherwise be 1389 // interpreted as a negative number. 1390 if sLen > 1 && sig[sOffset] == 0x00 && sig[sOffset+1]&0x80 == 0 { 1391 str := "malformed signature: S value has too much padding" 1392 return scriptError(ErrSigTooMuchSPadding, str) 1393 } 1394 1395 // Verify the S value is <= half the order of the curve. This check is done 1396 // because when it is higher, the complement modulo the order can be used 1397 // instead which is a shorter encoding by 1 byte. Further, without 1398 // enforcing this, it is possible to replace a signature in a valid 1399 // transaction with the complement while still being a valid signature that 1400 // verifies. This would result in changing the transaction hash and thus is 1401 // a source of malleability. 1402 if vm.hasFlag(ScriptVerifyLowS) { 1403 sValue := new(big.Int).SetBytes(sig[sOffset : sOffset+sLen]) 1404 if sValue.Cmp(halfOrder) > 0 { 1405 return scriptError(ErrSigHighS, "signature is not canonical due "+ 1406 "to unnecessarily high S value") 1407 } 1408 } 1409 1410 return nil 1411 } 1412 1413 // getStack returns the contents of stack as a byte array bottom up 1414 func getStack(stack *stack) [][]byte { 1415 array := make([][]byte, stack.Depth()) 1416 for i := range array { 1417 // PeekByteArry can't fail due to overflow, already checked 1418 array[len(array)-i-1], _ = stack.PeekByteArray(int32(i)) 1419 } 1420 return array 1421 } 1422 1423 // setStack sets the stack to the contents of the array where the last item in 1424 // the array is the top item in the stack. 1425 func setStack(stack *stack, data [][]byte) { 1426 // This can not error. Only errors are for invalid arguments. 1427 _ = stack.DropN(stack.Depth()) 1428 1429 for i := range data { 1430 stack.PushByteArray(data[i]) 1431 } 1432 } 1433 1434 // GetStack returns the contents of the primary stack as an array. where the 1435 // last item in the array is the top of the stack. 1436 func (vm *Engine) GetStack() [][]byte { 1437 return getStack(&vm.dstack) 1438 } 1439 1440 // SetStack sets the contents of the primary stack to the contents of the 1441 // provided array where the last item in the array will be the top of the stack. 1442 func (vm *Engine) SetStack(data [][]byte) { 1443 setStack(&vm.dstack, data) 1444 } 1445 1446 // GetAltStack returns the contents of the alternate stack as an array where the 1447 // last item in the array is the top of the stack. 1448 func (vm *Engine) GetAltStack() [][]byte { 1449 return getStack(&vm.astack) 1450 } 1451 1452 // SetAltStack sets the contents of the alternate stack to the contents of the 1453 // provided array where the last item in the array will be the top of the stack. 1454 func (vm *Engine) SetAltStack(data [][]byte) { 1455 setStack(&vm.astack, data) 1456 } 1457 1458 // NewEngine returns a new script engine for the provided public key script, 1459 // transaction, and input index. The flags modify the behavior of the script 1460 // engine according to the description provided by each flag. 1461 func NewEngine(scriptPubKey []byte, tx *wire.MsgTx, txIdx int, flags ScriptFlags, 1462 sigCache *SigCache, hashCache *TxSigHashes, inputAmount int64, 1463 prevOutFetcher PrevOutputFetcher) (*Engine, error) { 1464 1465 const scriptVersion = 0 1466 1467 // The provided transaction input index must refer to a valid input. 1468 if txIdx < 0 || txIdx >= len(tx.TxIn) { 1469 str := fmt.Sprintf("transaction input index %d is negative or "+ 1470 ">= %d", txIdx, len(tx.TxIn)) 1471 return nil, scriptError(ErrInvalidIndex, str) 1472 } 1473 scriptSig := tx.TxIn[txIdx].SignatureScript 1474 1475 // When both the signature script and public key script are empty the result 1476 // is necessarily an error since the stack would end up being empty which is 1477 // equivalent to a false top element. Thus, just return the relevant error 1478 // now as an optimization. 1479 if len(scriptSig) == 0 && len(scriptPubKey) == 0 { 1480 return nil, scriptError(ErrEvalFalse, 1481 "false stack entry at end of script execution") 1482 } 1483 1484 // The clean stack flag (ScriptVerifyCleanStack) is not allowed without 1485 // either the pay-to-script-hash (P2SH) evaluation (ScriptBip16) 1486 // flag or the Segregated Witness (ScriptVerifyWitness) flag. 1487 // 1488 // Recall that evaluating a P2SH script without the flag set results in 1489 // non-P2SH evaluation which leaves the P2SH inputs on the stack. 1490 // Thus, allowing the clean stack flag without the P2SH flag would make 1491 // it possible to have a situation where P2SH would not be a soft fork 1492 // when it should be. The same goes for segwit which will pull in 1493 // additional scripts for execution from the witness stack. 1494 vm := Engine{ 1495 flags: flags, 1496 sigCache: sigCache, 1497 hashCache: hashCache, 1498 inputAmount: inputAmount, 1499 prevOutFetcher: prevOutFetcher, 1500 } 1501 if vm.hasFlag(ScriptVerifyCleanStack) && (!vm.hasFlag(ScriptBip16) && 1502 !vm.hasFlag(ScriptVerifyWitness)) { 1503 return nil, scriptError(ErrInvalidFlags, 1504 "invalid flags combination") 1505 } 1506 1507 // The signature script must only contain data pushes when the 1508 // associated flag is set. 1509 if vm.hasFlag(ScriptVerifySigPushOnly) && !IsPushOnlyScript(scriptSig) { 1510 return nil, scriptError(ErrNotPushOnly, 1511 "signature script is not push only") 1512 } 1513 1514 // The signature script must only contain data pushes for PS2H which is 1515 // determined based on the form of the public key script. 1516 if vm.hasFlag(ScriptBip16) && isScriptHashScript(scriptPubKey) { 1517 // Only accept input scripts that push data for P2SH. 1518 // Notice that the push only checks have already been done when 1519 // the flag to verify signature scripts are push only is set 1520 // above, so avoid checking again. 1521 alreadyChecked := vm.hasFlag(ScriptVerifySigPushOnly) 1522 if !alreadyChecked && !IsPushOnlyScript(scriptSig) { 1523 return nil, scriptError(ErrNotPushOnly, 1524 "pay to script hash is not push only") 1525 } 1526 vm.bip16 = true 1527 } 1528 1529 // The engine stores the scripts using a slice. This allows multiple 1530 // scripts to be executed in sequence. For example, with a 1531 // pay-to-script-hash transaction, there will be ultimately be a third 1532 // script to execute. 1533 scripts := [][]byte{scriptSig, scriptPubKey} 1534 for _, scr := range scripts { 1535 if len(scr) > MaxScriptSize { 1536 str := fmt.Sprintf("script size %d is larger than max allowed "+ 1537 "size %d", len(scr), MaxScriptSize) 1538 return nil, scriptError(ErrScriptTooBig, str) 1539 } 1540 1541 const scriptVersion = 0 1542 if err := checkScriptParses(scriptVersion, scr); err != nil { 1543 return nil, err 1544 } 1545 } 1546 vm.scripts = scripts 1547 1548 // Advance the program counter to the public key script if the signature 1549 // script is empty since there is nothing to execute for it in that case. 1550 if len(scriptSig) == 0 { 1551 vm.scriptIdx++ 1552 } 1553 if vm.hasFlag(ScriptVerifyMinimalData) { 1554 vm.dstack.verifyMinimalData = true 1555 vm.astack.verifyMinimalData = true 1556 } 1557 1558 // Check to see if we should execute in witness verification mode 1559 // according to the set flags. We check both the pkScript, and sigScript 1560 // here since in the case of nested p2sh, the scriptSig will be a valid 1561 // witness program. For nested p2sh, all the bytes after the first data 1562 // push should *exactly* match the witness program template. 1563 if vm.hasFlag(ScriptVerifyWitness) { 1564 // If witness evaluation is enabled, then P2SH MUST also be 1565 // active. 1566 if !vm.hasFlag(ScriptBip16) { 1567 errStr := "P2SH must be enabled to do witness verification" 1568 return nil, scriptError(ErrInvalidFlags, errStr) 1569 } 1570 1571 var witProgram []byte 1572 1573 switch { 1574 case IsWitnessProgram(vm.scripts[1]): 1575 // The scriptSig must be *empty* for all native witness 1576 // programs, otherwise we introduce malleability. 1577 if len(scriptSig) != 0 { 1578 errStr := "native witness program cannot " + 1579 "also have a signature script" 1580 return nil, scriptError(ErrWitnessMalleated, errStr) 1581 } 1582 1583 witProgram = scriptPubKey 1584 case len(tx.TxIn[txIdx].Witness) != 0 && vm.bip16: 1585 // The sigScript MUST be *exactly* a single canonical 1586 // data push of the witness program, otherwise we 1587 // reintroduce malleability. 1588 sigPops := vm.scripts[0] 1589 if len(sigPops) > 2 && 1590 isCanonicalPush(sigPops[0], sigPops[1:]) && 1591 IsWitnessProgram(sigPops[1:]) { 1592 1593 witProgram = sigPops[1:] 1594 } else { 1595 errStr := "signature script for witness " + 1596 "nested p2sh is not canonical" 1597 return nil, scriptError(ErrWitnessMalleatedP2SH, errStr) 1598 } 1599 } 1600 1601 if witProgram != nil { 1602 var err error 1603 vm.witnessVersion, vm.witnessProgram, err = ExtractWitnessProgramInfo( 1604 witProgram, 1605 ) 1606 if err != nil { 1607 return nil, err 1608 } 1609 } else { 1610 // If we didn't find a witness program in either the 1611 // pkScript or as a datapush within the sigScript, then 1612 // there MUST NOT be any witness data associated with 1613 // the input being validated. 1614 if vm.witnessProgram == nil && len(tx.TxIn[txIdx].Witness) != 0 { 1615 errStr := "non-witness inputs cannot have a witness" 1616 return nil, scriptError(ErrWitnessUnexpected, errStr) 1617 } 1618 } 1619 1620 } 1621 1622 // Setup the current tokenizer used to parse through the script one opcode 1623 // at a time with the script associated with the program counter. 1624 vm.tokenizer = MakeScriptTokenizer(scriptVersion, scripts[vm.scriptIdx]) 1625 1626 vm.tx = *tx 1627 vm.txIdx = txIdx 1628 1629 return &vm, nil 1630 } 1631 1632 // NewEngine returns a new script engine with a script execution callback set. 1633 // This is useful for debugging script execution. 1634 func NewDebugEngine(scriptPubKey []byte, tx *wire.MsgTx, txIdx int, 1635 flags ScriptFlags, sigCache *SigCache, hashCache *TxSigHashes, 1636 inputAmount int64, prevOutFetcher PrevOutputFetcher, 1637 stepCallback func(*StepInfo) error) (*Engine, error) { 1638 1639 vm, err := NewEngine( 1640 scriptPubKey, tx, txIdx, flags, sigCache, hashCache, 1641 inputAmount, prevOutFetcher, 1642 ) 1643 if err != nil { 1644 return nil, err 1645 } 1646 1647 vm.stepCallback = stepCallback 1648 return vm, nil 1649 }