github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/btcutil/txscript/engine.go (about) 1 // Copyright (c) 2013-2015 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 txscript 6 7 import ( 8 "bytes" 9 "fmt" 10 "math/big" 11 12 "github.com/mit-dci/lit/crypto/fastsha256" 13 "github.com/mit-dci/lit/crypto/koblitz" 14 "github.com/mit-dci/lit/wire" 15 ) 16 17 // ScriptFlags is a bitmask defining additional operations or tests that will be 18 // done when executing a script pair. 19 type ScriptFlags uint32 20 21 const ( 22 // ScriptBip16 defines whether the bip16 threshold has passed and thus 23 // pay-to-script hash transactions will be fully validated. 24 ScriptBip16 ScriptFlags = 1 << iota 25 26 // ScriptStrictMultiSig defines whether to verify the stack item 27 // used by CHECKMULTISIG is zero length. 28 ScriptStrictMultiSig 29 30 // ScriptDiscourageUpgradableNops defines whether to verify that 31 // NOP1 through NOP10 are reserved for future soft-fork upgrades. This 32 // flag must not be used for consensus critical code nor applied to 33 // blocks as this flag is only for stricter standard transaction 34 // checks. This flag is only applied when the above opcodes are 35 // executed. 36 ScriptDiscourageUpgradableNops 37 38 // ScriptVerifyCheckLockTimeVerify defines whether to verify that 39 // a transaction output is spendable based on the locktime. 40 // This is BIP0065. 41 ScriptVerifyCheckLockTimeVerify 42 43 // ScriptVerifyCleanStack defines that the stack must contain only 44 // one stack element after evaluation and that the element must be 45 // true if interpreted as a boolean. This is rule 6 of BIP0062. 46 // This flag should never be used without the ScriptBip16 flag nor the 47 // ScriptVerifyWitness flag. 48 ScriptVerifyCleanStack 49 50 // ScriptVerifyDERSignatures defines that signatures are required 51 // to compily with the DER format. 52 ScriptVerifyDERSignatures 53 54 // ScriptVerifyLowS defines that signtures are required to comply with 55 // the DER format and whose S value is <= order / 2. This is rule 5 56 // of BIP0062. 57 ScriptVerifyLowS 58 59 // ScriptVerifyMinimalData defines that signatures must use the smallest 60 // push operator. This is both rules 3 and 4 of BIP0062. 61 ScriptVerifyMinimalData 62 63 // ScriptVerifySigPushOnly defines that signature scripts must contain 64 // only pushed data. This is rule 2 of BIP0062. 65 ScriptVerifySigPushOnly 66 67 // ScriptVerifyStrictEncoding defines that signature scripts and 68 // public keys must follow the strict encoding requirements. 69 ScriptVerifyStrictEncoding 70 71 // ScriptVerifyWitness defines whether or not to verify a transaction 72 // output using a witness program template. 73 ScriptVerifyWitness 74 75 // ScriptVerifyDiscourageUpgradeableWitnessProgram makes witness 76 // program with versions 2-16 non-standard. 77 ScriptVerifyDiscourageUpgradeableWitnessProgram 78 ) 79 80 const ( 81 // maxStackSize is the maximum combined height of stack and alt stack 82 // during execution. 83 maxStackSize = 1000 84 85 // maxScriptSize is the maximum allowed length of a raw script. 86 maxScriptSize = 10000 87 88 // payToWitnessPubKeyHashDataSize is the size of the witness program's 89 // data push for a pay-to-witness-pub-key-hash output. 90 payToWitnessPubKeyHashDataSize = 20 91 92 // payToWitnessScriptHashDataSize is the size of the witness program's 93 // data push for a pay-to-witness-script-hash output. 94 payToWitnessScriptHashDataSize = 32 95 ) 96 97 // halforder is used to tame ECDSA malleability (see BIP0062). 98 var halfOrder = new(big.Int).Rsh(koblitz.S256().N, 1) 99 100 // Engine is the virtual machine that executes scripts. 101 type Engine struct { 102 scripts [][]parsedOpcode 103 scriptIdx int 104 scriptOff int 105 lastCodeSep int 106 dstack stack // data stack 107 astack stack // alt stack 108 tx wire.MsgTx 109 txIdx int 110 condStack []int 111 numOps int 112 flags ScriptFlags 113 sigCache *SigCache 114 hashCache *TxSigHashes 115 bip16 bool // treat execution as pay-to-script-hash 116 savedFirstStack [][]byte // stack from first script for bip16 scripts 117 witness bool // treat execution as a witness program 118 witnessVersion int 119 witnessProgram []byte 120 inputAmount int64 121 } 122 123 // hasFlag returns whether the script engine instance has the passed flag set. 124 func (vm *Engine) hasFlag(flag ScriptFlags) bool { 125 return vm.flags&flag == flag 126 } 127 128 // isBranchExecuting returns whether or not the current conditional branch is 129 // actively executing. For example, when the data stack has an OP_FALSE on it 130 // and an OP_IF is encountered, the branch is inactive until an OP_ELSE or 131 // OP_ENDIF is encountered. It properly handles nested conditionals. 132 func (vm *Engine) isBranchExecuting() bool { 133 if len(vm.condStack) == 0 { 134 return true 135 } 136 return vm.condStack[len(vm.condStack)-1] == OpCondTrue 137 } 138 139 // executeOpcode peforms execution on the passed opcode. It takes into account 140 // whether or not it is hidden by conditionals, but some rules still must be 141 // tested in this case. 142 func (vm *Engine) executeOpcode(pop *parsedOpcode) error { 143 // Disabled opcodes are fail on program counter. 144 if pop.isDisabled() { 145 return ErrStackOpDisabled 146 } 147 148 // Always-illegal opcodes are fail on program counter. 149 if pop.alwaysIllegal() { 150 return ErrStackReservedOpcode 151 } 152 153 // Note that this includes OP_RESERVED which counts as a push operation. 154 if pop.opcode.value > OP_16 { 155 vm.numOps++ 156 if vm.numOps > MaxOpsPerScript { 157 return ErrStackTooManyOperations 158 } 159 160 } else if len(pop.data) > MaxScriptElementSize { 161 return ErrStackElementTooBig 162 } 163 164 // Nothing left to do when this is not a conditional opcode and it is 165 // not in an executing branch. 166 if !vm.isBranchExecuting() && !pop.isConditional() { 167 return nil 168 } 169 170 // Ensure all executed data push opcodes use the minimal encoding when 171 // the minimal data verification flag is set. 172 if vm.dstack.verifyMinimalData && vm.isBranchExecuting() && 173 pop.opcode.value >= 0 && pop.opcode.value <= OP_PUSHDATA4 { 174 175 if err := pop.checkMinimalDataPush(); err != nil { 176 return err 177 } 178 } 179 180 return pop.opcode.opfunc(pop, vm) 181 } 182 183 // disasm is a helper function to produce the output for DisasmPC and 184 // DisasmScript. It produces the opcode prefixed by the program counter at the 185 // provided position in the script. It does no error checking and leaves that 186 // to the caller to provide a valid offset. 187 func (vm *Engine) disasm(scriptIdx int, scriptOff int) string { 188 return fmt.Sprintf("%02x:%04x: %s", scriptIdx, scriptOff, 189 vm.scripts[scriptIdx][scriptOff].print(false)) 190 } 191 192 // validPC returns an error if the current script position is valid for 193 // execution, nil otherwise. 194 func (vm *Engine) validPC() error { 195 if vm.scriptIdx >= len(vm.scripts) { 196 return fmt.Errorf("past input scripts %v:%v %v:xxxx", 197 vm.scriptIdx, vm.scriptOff, len(vm.scripts)) 198 } 199 if vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { 200 return fmt.Errorf("past input scripts %v:%v %v:%04d", 201 vm.scriptIdx, vm.scriptOff, vm.scriptIdx, 202 len(vm.scripts[vm.scriptIdx])) 203 } 204 return nil 205 } 206 207 // curPC returns either the current script and offset, or an error if the 208 // position isn't valid. 209 func (vm *Engine) curPC() (script int, off int, err error) { 210 err = vm.validPC() 211 if err != nil { 212 return 0, 0, err 213 } 214 return vm.scriptIdx, vm.scriptOff, nil 215 } 216 217 // verifyWitnessProgram validates the stored witness program using the passed 218 // witness as input. 219 func (vm *Engine) verifyWitnessProgram(witness [][]byte) error { 220 // All elements within the witness stack must not be greater than the 221 // maximum bytes which are allowed to be pushed onto the stack. 222 for _, witElement := range witness { 223 if len(witElement) > MaxScriptElementSize { 224 return ErrStackElementTooBig 225 } 226 } 227 228 if vm.witnessVersion == 0 { 229 switch len(vm.witnessProgram) { 230 case payToWitnessPubKeyHashDataSize: // P2WKH 231 // The witness stack should consist of exactly two 232 // items: the signature, and the pubkey. 233 if len(witness) != 2 { 234 return ErrWitnessScriptMismatch 235 } 236 237 // Now we'll resume execution as if it were a 238 // regular p2pkh transaction. 239 pkScript, err := payToPubKeyHashScript(vm.witnessProgram) 240 if err != nil { 241 return err 242 } 243 pops, err := ParseScript(pkScript) 244 if err != nil { 245 return err 246 } 247 248 // Set the stack to the provided witness 249 // stack, then append the pkScript 250 // generated above as the next script to execute. 251 vm.scripts = append(vm.scripts, pops) 252 vm.SetStack(witness) 253 case payToWitnessScriptHashDataSize: // P2WSH 254 255 // Additionally, The witness stack MUST NOT be empty at 256 // this point. 257 if len(witness) == 0 { 258 return ErrWitnessProgramEmpty 259 } 260 261 // Ensure that the serialized pkScript 262 // at the end of the witness stack 263 // matches the witness program. 264 pkScript := witness[len(witness)-1] 265 witnessHash := fastsha256.Sum256(pkScript) 266 if !bytes.Equal(witnessHash[:], vm.witnessProgram) { 267 return fmt.Errorf("witness program mismatch") 268 } 269 270 pops, err := ParseScript(pkScript) 271 if err != nil { 272 return err 273 } 274 275 // The hash matched successfully, so 276 // use the witness as the stack, and 277 // set the pkScript to be the next script 278 // executed. 279 vm.scripts = append(vm.scripts, pops) 280 vm.SetStack(witness[:len(witness)-1]) 281 default: 282 return ErrWitnessProgramWrongLength 283 } 284 } else if vm.hasFlag(ScriptVerifyDiscourageUpgradeableWitnessProgram) { 285 return fmt.Errorf("new witness program versions invalid: %v", 286 vm.witnessVersion) 287 } else { 288 // If we encounter an unknown witness program version and we 289 // aren't discouraging future unknown witness based soft-forks, 290 // then we de-activate the segwit behavior within the VM for 291 // the remainder of execution. 292 vm.witness = false 293 } 294 295 return nil 296 } 297 298 // DisasmPC returns the string for the disassembly of the opcode that will be 299 // next to execute when Step() is called. 300 func (vm *Engine) DisasmPC() (string, error) { 301 scriptIdx, scriptOff, err := vm.curPC() 302 if err != nil { 303 return "", err 304 } 305 return vm.disasm(scriptIdx, scriptOff), nil 306 } 307 308 // DisasmScript returns the disassembly string for the script at the requested 309 // offset index. Index 0 is the signature script and 1 is the public key 310 // script. 311 func (vm *Engine) DisasmScript(idx int) (string, error) { 312 if idx >= len(vm.scripts) { 313 return "", ErrStackInvalidIndex 314 } 315 316 var disstr string 317 for i := range vm.scripts[idx] { 318 disstr = disstr + vm.disasm(idx, i) + "\n" 319 } 320 return disstr, nil 321 } 322 323 // CheckErrorCondition returns nil if the running script has ended and was 324 // successful, leaving a a true boolean on the stack. An error otherwise, 325 // including if the script has not finished. 326 func (vm *Engine) CheckErrorCondition(finalScript bool) error { 327 // Check execution is actually done. When pc is past the end of script 328 // array there are no more scripts to run. 329 if vm.scriptIdx < len(vm.scripts) { 330 return ErrStackScriptUnfinished 331 } 332 333 // If we're in witness execution mode, and this was the final script, 334 // then the stack MUST be clean in order to maintain compatibility with 335 // BIP16. 336 if finalScript && vm.witness && vm.dstack.Depth() != 1 { 337 return ErrStackCleanStack 338 } 339 340 if finalScript && vm.hasFlag(ScriptVerifyCleanStack) && 341 vm.dstack.Depth() != 1 { 342 343 return ErrStackCleanStack 344 } else if vm.dstack.Depth() < 1 { 345 return ErrStackEmptyStack 346 } 347 348 v, err := vm.dstack.PopBool() 349 if err != nil { 350 return err 351 } 352 if v == false { 353 return ErrStackScriptFailed 354 } 355 return nil 356 } 357 358 // Step will execute the next instruction and move the program counter to the 359 // next opcode in the script, or the next script if the current has ended. Step 360 // will return true in the case that the last opcode was successfully executed. 361 // 362 // The result of calling Step or any other method is undefined if an error is 363 // returned. 364 func (vm *Engine) Step() (done bool, err error) { 365 // Verify that it is pointing to a valid script address. 366 err = vm.validPC() 367 if err != nil { 368 return true, err 369 } 370 opcode := &vm.scripts[vm.scriptIdx][vm.scriptOff] 371 vm.scriptOff++ 372 373 // Execute the opcode while taking into account several things such as 374 // disabled opcodes, illegal opcodes, maximum allowed operations per 375 // script, maximum script element sizes, and conditionals. 376 err = vm.executeOpcode(opcode) 377 if err != nil { 378 return true, err 379 } 380 381 // The number of elements in the combination of the data and alt stacks 382 // must not exceed the maximum number of stack elements allowed. 383 if vm.dstack.Depth()+vm.astack.Depth() > maxStackSize { 384 return false, ErrStackOverflow 385 } 386 387 // Prepare for next instruction. 388 if vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { 389 // Illegal to have an `if' that straddles two scripts. 390 if err == nil && len(vm.condStack) != 0 { 391 return false, ErrStackMissingEndif 392 } 393 394 // Alt stack doesn't persist. 395 _ = vm.astack.DropN(vm.astack.Depth()) 396 397 vm.numOps = 0 // number of ops is per script. 398 vm.scriptOff = 0 399 if vm.scriptIdx == 0 && vm.bip16 { 400 vm.scriptIdx++ 401 vm.savedFirstStack = vm.GetStack() 402 } else if vm.scriptIdx == 1 && vm.bip16 { 403 // Put us past the end for CheckErrorCondition() 404 vm.scriptIdx++ 405 // Check script ran successfully and pull the script 406 // out of the first stack and execute that. 407 err := vm.CheckErrorCondition(false) 408 if err != nil { 409 return false, err 410 } 411 412 script := vm.savedFirstStack[len(vm.savedFirstStack)-1] 413 pops, err := ParseScript(script) 414 if err != nil { 415 return false, err 416 } 417 vm.scripts = append(vm.scripts, pops) 418 419 // Set stack to be the stack from first script minus the 420 // script itself 421 vm.SetStack(vm.savedFirstStack[:len(vm.savedFirstStack)-1]) 422 } else if (vm.scriptIdx == 1 && vm.witness) || 423 (vm.witness && vm.bip16 && vm.scriptIdx == 2) { // Nested P2SH. 424 vm.scriptIdx++ 425 426 witness := vm.tx.TxIn[vm.txIdx].Witness 427 if err := vm.verifyWitnessProgram(witness); err != nil { 428 return false, err 429 } 430 } else { 431 vm.scriptIdx++ 432 } 433 // there are zero length scripts in the wild 434 if vm.scriptIdx < len(vm.scripts) && vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { 435 vm.scriptIdx++ 436 } 437 vm.lastCodeSep = 0 438 if vm.scriptIdx >= len(vm.scripts) { 439 return true, nil 440 } 441 } 442 return false, nil 443 } 444 445 // Execute will execute all scripts in the script engine and return either nil 446 // for successful validation or an error if one occurred. 447 func (vm *Engine) Execute() (err error) { 448 done := false 449 for done != true { 450 done, err = vm.Step() 451 if err != nil { 452 return err 453 } 454 } 455 456 return vm.CheckErrorCondition(true) 457 } 458 459 // subScript returns the script since the last OP_CODESEPARATOR. 460 func (vm *Engine) subScript() []parsedOpcode { 461 return vm.scripts[vm.scriptIdx][vm.lastCodeSep:] 462 } 463 464 // checkHashTypeEncoding returns whether or not the passed hashtype adheres to 465 // the strict encoding requirements if enabled. 466 func (vm *Engine) checkHashTypeEncoding(hashType SigHashType) error { 467 if !vm.hasFlag(ScriptVerifyStrictEncoding) { 468 return nil 469 } 470 471 sigHashType := hashType & ^SigHashAnyOneCanPay 472 if sigHashType < SigHashAll || sigHashType > SigHashSingle { 473 return fmt.Errorf("invalid hashtype: 0x%x\n", hashType) 474 } 475 return nil 476 } 477 478 // checkPubKeyEncoding returns whether or not the passed public key adheres to 479 // the strict encoding requirements if enabled. 480 func (vm *Engine) checkPubKeyEncoding(pubKey []byte) error { 481 if !vm.hasFlag(ScriptVerifyStrictEncoding) { 482 return nil 483 } 484 485 if len(pubKey) == 33 && (pubKey[0] == 0x02 || pubKey[0] == 0x03) { 486 // Compressed 487 return nil 488 } 489 if len(pubKey) == 65 && pubKey[0] == 0x04 { 490 // Uncompressed 491 return nil 492 } 493 return ErrStackInvalidPubKey 494 } 495 496 // checkSignatureEncoding returns whether or not the passed signature adheres to 497 // the strict encoding requirements if enabled. 498 func (vm *Engine) checkSignatureEncoding(sig []byte) error { 499 if !vm.hasFlag(ScriptVerifyDERSignatures) && 500 !vm.hasFlag(ScriptVerifyLowS) && 501 !vm.hasFlag(ScriptVerifyStrictEncoding) { 502 503 return nil 504 } 505 506 // The format of a DER encoded signature is as follows: 507 // 508 // 0x30 <total length> 0x02 <length of R> <R> 0x02 <length of S> <S> 509 // - 0x30 is the ASN.1 identifier for a sequence 510 // - Total length is 1 byte and specifies length of all remaining data 511 // - 0x02 is the ASN.1 identifier that specifies an integer follows 512 // - Length of R is 1 byte and specifies how many bytes R occupies 513 // - R is the arbitrary length big-endian encoded number which 514 // represents the R value of the signature. DER encoding dictates 515 // that the value must be encoded using the minimum possible number 516 // of bytes. This implies the first byte can only be null if the 517 // highest bit of the next byte is set in order to prevent it from 518 // being interpreted as a negative number. 519 // - 0x02 is once again the ASN.1 integer identifier 520 // - Length of S is 1 byte and specifies how many bytes S occupies 521 // - S is the arbitrary length big-endian encoded number which 522 // represents the S value of the signature. The encoding rules are 523 // identical as those for R. 524 525 // Minimum length is when both numbers are 1 byte each. 526 // 0x30 + <1-byte> + 0x02 + 0x01 + <byte> + 0x2 + 0x01 + <byte> 527 if len(sig) < 8 { 528 // Too short 529 return fmt.Errorf("malformed signature: too short: %d < 8", 530 len(sig)) 531 } 532 533 // Maximum length is when both numbers are 33 bytes each. It is 33 534 // bytes because a 256-bit integer requires 32 bytes and an additional 535 // leading null byte might required if the high bit is set in the value. 536 // 0x30 + <1-byte> + 0x02 + 0x21 + <33 bytes> + 0x2 + 0x21 + <33 bytes> 537 if len(sig) > 72 { 538 // Too long 539 return fmt.Errorf("malformed signature: too long: %d > 72", 540 len(sig)) 541 } 542 if sig[0] != 0x30 { 543 // Wrong type 544 return fmt.Errorf("malformed signature: format has wrong type: 0x%x", 545 sig[0]) 546 } 547 if int(sig[1]) != len(sig)-2 { 548 // Invalid length 549 return fmt.Errorf("malformed signature: bad length: %d != %d", 550 sig[1], len(sig)-2) 551 } 552 553 rLen := int(sig[3]) 554 555 // Make sure S is inside the signature. 556 if rLen+5 > len(sig) { 557 return fmt.Errorf("malformed signature: S out of bounds") 558 } 559 560 sLen := int(sig[rLen+5]) 561 562 // The length of the elements does not match the length of the 563 // signature. 564 if rLen+sLen+6 != len(sig) { 565 return fmt.Errorf("malformed signature: invalid R length") 566 } 567 568 // R elements must be integers. 569 if sig[2] != 0x02 { 570 return fmt.Errorf("malformed signature: missing first integer marker") 571 } 572 573 // Zero-length integers are not allowed for R. 574 if rLen == 0 { 575 return fmt.Errorf("malformed signature: R length is zero") 576 } 577 578 // R must not be negative. 579 if sig[4]&0x80 != 0 { 580 return fmt.Errorf("malformed signature: R value is negative") 581 } 582 583 // Null bytes at the start of R are not allowed, unless R would 584 // otherwise be interpreted as a negative number. 585 if rLen > 1 && sig[4] == 0x00 && sig[5]&0x80 == 0 { 586 return fmt.Errorf("malformed signature: invalid R value") 587 } 588 589 // S elements must be integers. 590 if sig[rLen+4] != 0x02 { 591 return fmt.Errorf("malformed signature: missing second integer marker") 592 } 593 594 // Zero-length integers are not allowed for S. 595 if sLen == 0 { 596 return fmt.Errorf("malformed signature: S length is zero") 597 } 598 599 // S must not be negative. 600 if sig[rLen+6]&0x80 != 0 { 601 return fmt.Errorf("malformed signature: S value is negative") 602 } 603 604 // Null bytes at the start of S are not allowed, unless S would 605 // otherwise be interpreted as a negative number. 606 if sLen > 1 && sig[rLen+6] == 0x00 && sig[rLen+7]&0x80 == 0 { 607 return fmt.Errorf("malformed signature: invalid S value") 608 } 609 610 // Verify the S value is <= half the order of the curve. This check is 611 // done because when it is higher, the complement modulo the order can 612 // be used instead which is a shorter encoding by 1 byte. Further, 613 // without enforcing this, it is possible to replace a signature in a 614 // valid transaction with the complement while still being a valid 615 // signature that verifies. This would result in changing the 616 // transaction hash and thus is source of malleability. 617 if vm.hasFlag(ScriptVerifyLowS) { 618 sValue := new(big.Int).SetBytes(sig[rLen+6 : rLen+6+sLen]) 619 if sValue.Cmp(halfOrder) > 0 { 620 return ErrStackInvalidLowSSignature 621 } 622 } 623 624 return nil 625 } 626 627 // getStack returns the contents of stack as a byte array bottom up 628 func getStack(stack *stack) [][]byte { 629 array := make([][]byte, stack.Depth()) 630 for i := range array { 631 // PeekByteArry can't fail due to overflow, already checked 632 array[len(array)-i-1], _ = stack.PeekByteArray(int32(i)) 633 } 634 return array 635 } 636 637 // setStack sets the stack to the contents of the array where the last item in 638 // the array is the top item in the stack. 639 func setStack(stack *stack, data [][]byte) { 640 // This can not error. Only errors are for invalid arguments. 641 _ = stack.DropN(stack.Depth()) 642 643 for i := range data { 644 stack.PushByteArray(data[i]) 645 } 646 } 647 648 // GetStack returns the contents of the primary stack as an array. where the 649 // last item in the array is the top of the stack. 650 func (vm *Engine) GetStack() [][]byte { 651 return getStack(&vm.dstack) 652 } 653 654 // SetStack sets the contents of the primary stack to the contents of the 655 // provided array where the last item in the array will be the top of the stack. 656 func (vm *Engine) SetStack(data [][]byte) { 657 setStack(&vm.dstack, data) 658 } 659 660 // GetAltStack returns the contents of the alternate stack as an array where the 661 // last item in the array is the top of the stack. 662 func (vm *Engine) GetAltStack() [][]byte { 663 return getStack(&vm.astack) 664 } 665 666 // SetAltStack sets the contents of the alternate stack to the contents of the 667 // provided array where the last item in the array will be the top of the stack. 668 func (vm *Engine) SetAltStack(data [][]byte) { 669 setStack(&vm.astack, data) 670 } 671 672 // NewEngine returns a new script engine for the provided public key script, 673 // transaction, and input index. The flags modify the behavior of the script 674 // engine according to the description provided by each flag. 675 func NewEngine(scriptPubKey []byte, tx *wire.MsgTx, txIdx int, flags ScriptFlags, 676 sigCache *SigCache, hashCache *TxSigHashes, inputAmount int64) (*Engine, error) { 677 678 // The provided transaction input index must refer to a valid input. 679 if txIdx < 0 || txIdx >= len(tx.TxIn) { 680 return nil, ErrInvalidIndex 681 } 682 scriptSig := tx.TxIn[txIdx].SignatureScript 683 684 // The clean stack flag (ScriptVerifyCleanStack) is not allowed without 685 // the pay-to-script-hash (P2SH) evaluation (ScriptBip16) flag. 686 // 687 // Recall that evaluating a P2SH script without the flag set results in 688 // non-P2SH evaluation which leaves the P2SH inputs on the stack. Thus, 689 // allowing the clean stack flag without the P2SH flag would make it 690 // possible to have a situation where P2SH would not be a soft fork when 691 // it should be. 692 vm := Engine{flags: flags, sigCache: sigCache, hashCache: hashCache, 693 inputAmount: inputAmount} 694 if vm.hasFlag(ScriptVerifyCleanStack) && !vm.hasFlag(ScriptBip16) { 695 return nil, ErrInvalidFlags 696 } 697 698 // The signature script must only contain data pushes when the 699 // associated flag is set. 700 if vm.hasFlag(ScriptVerifySigPushOnly) && !IsPushOnlyScript(scriptSig) { 701 return nil, ErrStackNonPushOnly 702 } 703 704 // The engine stores the scripts in parsed form using a slice. This 705 // allows multiple scripts to be executed in sequence. For example, 706 // with a pay-to-script-hash transaction, there will be ultimately be 707 // a third script to execute. 708 scripts := [][]byte{scriptSig, scriptPubKey} 709 vm.scripts = make([][]parsedOpcode, len(scripts)) 710 for i, scr := range scripts { 711 if len(scr) > maxScriptSize { 712 return nil, ErrStackLongScript 713 } 714 var err error 715 vm.scripts[i], err = ParseScript(scr) 716 if err != nil { 717 return nil, err 718 } 719 } 720 721 // Advance the program counter to the public key script if the signature 722 // script is empty since there is nothing to execute for it in that 723 // case. 724 if len(scripts[0]) == 0 { 725 vm.scriptIdx++ 726 } 727 728 if vm.hasFlag(ScriptBip16) && isScriptHash(vm.scripts[1]) { 729 // Only accept input scripts that push data for P2SH. 730 if !isPushOnly(vm.scripts[0]) { 731 return nil, ErrStackP2SHNonPushOnly 732 } 733 vm.bip16 = true 734 735 } 736 737 // Check to see if we should execute in witness verification mode 738 // according to the set flags. We check both the pkScript, and sigScript 739 // here since in the case of nested p2sh, the scriptSig will be a valid 740 // witness program. For nested p2sh, all the bytes after the first data 741 // push should *exactly* match the witness program template. 742 if vm.hasFlag(ScriptVerifyWitness) { 743 // If witness evaluation is enabled, then P2SH MUST also be 744 // active. 745 if !vm.hasFlag(ScriptBip16) { 746 return nil, ErrInvalidFlags 747 } 748 749 var err error 750 var witProgram []byte 751 752 switch { 753 case IsWitnessProgram(scriptPubKey): 754 // The scriptSig must be *empty* for all native witness 755 // programs, otherwise we introduce malleability. 756 if len(scriptSig) != 0 { 757 return nil, ErrWitnessMalleated 758 } 759 760 witProgram = scriptPubKey 761 case len(scriptSig) > 1 && vm.bip16 && IsWitnessProgram(scriptSig[1:]): 762 // The sigScript MUST be *exactly* a single canonical 763 // data push of the witness program, otherwise we 764 // reintroduce malleability. 765 b := NewScriptBuilder() 766 b.AddData(scriptSig[1:]) 767 script, err := b.Script() 768 if err != nil { 769 return nil, err 770 } 771 if !bytes.Equal(scriptSig, script) { 772 return nil, ErrWitnessMalleatedP2SH 773 } 774 775 witProgram = scriptSig[1:] 776 } 777 778 if witProgram != nil { 779 vm.witness = true 780 vm.witnessVersion, vm.witnessProgram, err = ExtractWitnessProgramInfo(witProgram) 781 if err != nil { 782 return nil, err 783 } 784 } else { 785 // If we didn't find a witness program in either the 786 // pkScript or as a datapush within the sigScript, then 787 // there MUST NOT be any witness data associated with 788 // the input being validated. 789 if !vm.witness && len(tx.TxIn[txIdx].Witness) != 0 { 790 return nil, ErrWitnessUnexpected 791 } 792 } 793 794 } 795 796 if vm.hasFlag(ScriptVerifyMinimalData) { 797 vm.dstack.verifyMinimalData = true 798 vm.astack.verifyMinimalData = true 799 } 800 801 vm.tx = *tx 802 vm.txIdx = txIdx 803 804 return &vm, nil 805 }