github.com/lbryio/lbcd@v0.22.119/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/lbryio/lbcd/btcec" 16 "github.com/lbryio/lbcd/wire" 17 ) 18 19 // ScriptFlags is a bitmask defining additional operations or tests that will be 20 // done when executing a script pair. 21 type ScriptFlags uint32 22 23 const ( 24 // ScriptBip16 defines whether the bip16 threshold has passed and thus 25 // pay-to-script hash transactions will be fully validated. 26 ScriptBip16 ScriptFlags = 1 << iota 27 28 // ScriptStrictMultiSig defines whether to verify the stack item 29 // used by CHECKMULTISIG is zero length. 30 ScriptStrictMultiSig 31 32 // ScriptDiscourageUpgradableNops defines whether to verify that 33 // NOP1 through NOP10 are reserved for future soft-fork upgrades. This 34 // flag must not be used for consensus critical code nor applied to 35 // blocks as this flag is only for stricter standard transaction 36 // checks. This flag is only applied when the above opcodes are 37 // executed. 38 ScriptDiscourageUpgradableNops 39 40 // ScriptVerifyCheckLockTimeVerify defines whether to verify that 41 // a transaction output is spendable based on the locktime. 42 // This is BIP0065. 43 ScriptVerifyCheckLockTimeVerify 44 45 // ScriptVerifyCheckSequenceVerify defines whether to allow execution 46 // pathways of a script to be restricted based on the age of the output 47 // being spent. This is BIP0112. 48 ScriptVerifyCheckSequenceVerify 49 50 // ScriptVerifyCleanStack defines that the stack must contain only 51 // one stack element after evaluation and that the element must be 52 // true if interpreted as a boolean. This is rule 6 of BIP0062. 53 // This flag should never be used without the ScriptBip16 flag nor the 54 // ScriptVerifyWitness flag. 55 ScriptVerifyCleanStack 56 57 // ScriptVerifyDERSignatures defines that signatures are required 58 // to compily with the DER format. 59 ScriptVerifyDERSignatures 60 61 // ScriptVerifyLowS defines that signtures are required to comply with 62 // the DER format and whose S value is <= order / 2. This is rule 5 63 // of BIP0062. 64 ScriptVerifyLowS 65 66 // ScriptVerifyMinimalData defines that signatures must use the smallest 67 // push operator. This is both rules 3 and 4 of BIP0062. 68 ScriptVerifyMinimalData 69 70 // ScriptVerifyNullFail defines that signatures must be empty if 71 // a CHECKSIG or CHECKMULTISIG operation fails. 72 ScriptVerifyNullFail 73 74 // ScriptVerifySigPushOnly defines that signature scripts must contain 75 // only pushed data. This is rule 2 of BIP0062. 76 ScriptVerifySigPushOnly 77 78 // ScriptVerifyStrictEncoding defines that signature scripts and 79 // public keys must follow the strict encoding requirements. 80 ScriptVerifyStrictEncoding 81 82 // ScriptVerifyWitness defines whether or not to verify a transaction 83 // output using a witness program template. 84 ScriptVerifyWitness 85 86 // ScriptVerifyDiscourageUpgradeableWitnessProgram makes witness 87 // program with versions 2-16 non-standard. 88 ScriptVerifyDiscourageUpgradeableWitnessProgram 89 90 // ScriptVerifyMinimalIf makes a script with an OP_IF/OP_NOTIF whose 91 // operand is anything other than empty vector or [0x01] non-standard. 92 ScriptVerifyMinimalIf 93 94 // ScriptVerifyWitnessPubKeyType makes a script within a check-sig 95 // operation whose public key isn't serialized in a compressed format 96 // non-standard. 97 ScriptVerifyWitnessPubKeyType 98 ) 99 100 const ( 101 // MaxStackSize is the maximum combined height of stack and alt stack 102 // during execution. 103 MaxStackSize = 1000 104 105 // MaxScriptSize is the maximum allowed length of a raw script. 106 MaxScriptSize = 20005 107 108 // payToWitnessPubKeyHashDataSize is the size of the witness program's 109 // data push for a pay-to-witness-pub-key-hash output. 110 payToWitnessPubKeyHashDataSize = 20 111 112 // payToWitnessScriptHashDataSize is the size of the witness program's 113 // data push for a pay-to-witness-script-hash output. 114 payToWitnessScriptHashDataSize = 32 115 ) 116 117 // halforder is used to tame ECDSA malleability (see BIP0062). 118 var halfOrder = new(big.Int).Rsh(btcec.S256().N, 1) 119 120 // Engine is the virtual machine that executes scripts. 121 type Engine struct { 122 // The following fields are set when the engine is created and must not be 123 // changed afterwards. The entries of the signature cache are mutated 124 // during execution, however, the cache pointer itself is not changed. 125 // 126 // flags specifies the additional flags which modify the execution behavior 127 // of the engine. 128 // 129 // tx identifies the transaction that contains the input which in turn 130 // contains the signature script being executed. 131 // 132 // txIdx identifies the input index within the transaction that contains 133 // the signature script being executed. 134 // 135 // version specifies the version of the public key script to execute. Since 136 // signature scripts redeem public keys scripts, this means the same version 137 // also extends to signature scripts and redeem scripts in the case of 138 // pay-to-script-hash. 139 // 140 // bip16 specifies that the public key script is of a special form that 141 // indicates it is a BIP16 pay-to-script-hash and therefore the 142 // execution must be treated as such. 143 // 144 // sigCache caches the results of signature verifications. This is useful 145 // since transaction scripts are often executed more than once from various 146 // contexts (e.g. new block templates, when transactions are first seen 147 // prior to being mined, part of full block verification, etc). 148 flags ScriptFlags 149 tx wire.MsgTx 150 txIdx int 151 version uint16 152 bip16 bool 153 sigCache *SigCache 154 hashCache *TxSigHashes 155 156 // The following fields handle keeping track of the current execution state 157 // of the engine. 158 // 159 // scripts houses the raw scripts that are executed by the engine. This 160 // includes the signature script as well as the public key script. It also 161 // includes the redeem script in the case of pay-to-script-hash. 162 // 163 // scriptIdx tracks the index into the scripts array for the current program 164 // counter. 165 // 166 // opcodeIdx tracks the number of the opcode within the current script for 167 // the current program counter. Note that it differs from the actual byte 168 // index into the script and is really only used for disassembly purposes. 169 // 170 // lastCodeSep specifies the position within the current script of the last 171 // OP_CODESEPARATOR. 172 // 173 // tokenizer provides the token stream of the current script being executed 174 // and doubles as state tracking for the program counter within the script. 175 // 176 // savedFirstStack keeps a copy of the stack from the first script when 177 // performing pay-to-script-hash execution. 178 // 179 // dstack is the primary data stack the various opcodes push and pop data 180 // to and from during execution. 181 // 182 // astack is the alternate data stack the various opcodes push and pop data 183 // to and from during execution. 184 // 185 // condStack tracks the conditional execution state with support for 186 // multiple nested conditional execution opcodes. 187 // 188 // numOps tracks the total number of non-push operations in a script and is 189 // primarily used to enforce maximum limits. 190 scripts [][]byte 191 scriptIdx int 192 opcodeIdx int 193 lastCodeSep int 194 tokenizer ScriptTokenizer 195 savedFirstStack [][]byte 196 dstack stack 197 astack stack 198 condStack []int 199 numOps int 200 witnessVersion int 201 witnessProgram []byte 202 inputAmount int64 203 } 204 205 // hasFlag returns whether the script engine instance has the passed flag set. 206 func (vm *Engine) hasFlag(flag ScriptFlags) bool { 207 return vm.flags&flag == flag 208 } 209 210 // isBranchExecuting returns whether or not the current conditional branch is 211 // actively executing. For example, when the data stack has an OP_FALSE on it 212 // and an OP_IF is encountered, the branch is inactive until an OP_ELSE or 213 // OP_ENDIF is encountered. It properly handles nested conditionals. 214 func (vm *Engine) isBranchExecuting() bool { 215 if len(vm.condStack) == 0 { 216 return true 217 } 218 return vm.condStack[len(vm.condStack)-1] == OpCondTrue 219 } 220 221 // isOpcodeDisabled returns whether or not the opcode is disabled and thus is 222 // always bad to see in the instruction stream (even if turned off by a 223 // conditional). 224 func isOpcodeDisabled(opcode byte) bool { 225 switch opcode { 226 case OP_CAT: 227 return true 228 case OP_SUBSTR: 229 return true 230 case OP_LEFT: 231 return true 232 case OP_RIGHT: 233 return true 234 case OP_INVERT: 235 return true 236 case OP_AND: 237 return true 238 case OP_OR: 239 return true 240 case OP_XOR: 241 return true 242 case OP_2MUL: 243 return true 244 case OP_2DIV: 245 return true 246 case OP_MUL: 247 return true 248 case OP_DIV: 249 return true 250 case OP_MOD: 251 return true 252 case OP_LSHIFT: 253 return true 254 case OP_RSHIFT: 255 return true 256 default: 257 return false 258 } 259 } 260 261 // isOpcodeAlwaysIllegal returns whether or not the opcode is always illegal 262 // when passed over by the program counter even if in a non-executed branch (it 263 // isn't a coincidence that they are conditionals). 264 func isOpcodeAlwaysIllegal(opcode byte) bool { 265 switch opcode { 266 case OP_VERIF: 267 return true 268 case OP_VERNOTIF: 269 return true 270 default: 271 return false 272 } 273 } 274 275 // isOpcodeConditional returns whether or not the opcode is a conditional opcode 276 // which changes the conditional execution stack when executed. 277 func isOpcodeConditional(opcode byte) bool { 278 switch opcode { 279 case OP_IF: 280 return true 281 case OP_NOTIF: 282 return true 283 case OP_ELSE: 284 return true 285 case OP_ENDIF: 286 return true 287 default: 288 return false 289 } 290 } 291 292 // checkMinimalDataPush returns whether or not the provided opcode is the 293 // smallest possible way to represent the given data. For example, the value 15 294 // could be pushed with OP_DATA_1 15 (among other variations); however, OP_15 is 295 // a single opcode that represents the same value and is only a single byte 296 // versus two bytes. 297 func checkMinimalDataPush(op *opcode, data []byte) error { 298 opcodeVal := op.value 299 dataLen := len(data) 300 switch { 301 case dataLen == 0 && opcodeVal != OP_0: 302 str := fmt.Sprintf("zero length data push is encoded with opcode %s "+ 303 "instead of OP_0", op.name) 304 return scriptError(ErrMinimalData, str) 305 case dataLen == 1 && data[0] >= 1 && data[0] <= 16: 306 if opcodeVal != OP_1+data[0]-1 { 307 // Should have used OP_1 .. OP_16 308 str := fmt.Sprintf("data push of the value %d encoded with opcode "+ 309 "%s instead of OP_%d", data[0], op.name, data[0]) 310 return scriptError(ErrMinimalData, str) 311 } 312 case dataLen == 1 && data[0] == 0x81: 313 if opcodeVal != OP_1NEGATE { 314 str := fmt.Sprintf("data push of the value -1 encoded with opcode "+ 315 "%s instead of OP_1NEGATE", op.name) 316 return scriptError(ErrMinimalData, str) 317 } 318 case dataLen <= 75: 319 if int(opcodeVal) != dataLen { 320 // Should have used a direct push 321 str := fmt.Sprintf("data push of %d bytes encoded with opcode %s "+ 322 "instead of OP_DATA_%d", dataLen, op.name, dataLen) 323 return scriptError(ErrMinimalData, str) 324 } 325 case dataLen <= 255: 326 if opcodeVal != OP_PUSHDATA1 { 327 str := fmt.Sprintf("data push of %d bytes encoded with opcode %s "+ 328 "instead of OP_PUSHDATA1", dataLen, op.name) 329 return scriptError(ErrMinimalData, str) 330 } 331 case dataLen <= 65535: 332 if opcodeVal != OP_PUSHDATA2 { 333 str := fmt.Sprintf("data push of %d bytes encoded with opcode %s "+ 334 "instead of OP_PUSHDATA2", dataLen, op.name) 335 return scriptError(ErrMinimalData, str) 336 } 337 } 338 return nil 339 } 340 341 // executeOpcode peforms execution on the passed opcode. It takes into account 342 // whether or not it is hidden by conditionals, but some rules still must be 343 // tested in this case. 344 func (vm *Engine) executeOpcode(op *opcode, data []byte) error { 345 // Disabled opcodes are fail on program counter. 346 if isOpcodeDisabled(op.value) { 347 str := fmt.Sprintf("attempt to execute disabled opcode %s", op.name) 348 return scriptError(ErrDisabledOpcode, str) 349 } 350 351 // Always-illegal opcodes are fail on program counter. 352 if isOpcodeAlwaysIllegal(op.value) { 353 str := fmt.Sprintf("attempt to execute reserved opcode %s", op.name) 354 return scriptError(ErrReservedOpcode, str) 355 } 356 357 // Note that this includes OP_RESERVED which counts as a push operation. 358 if op.value > OP_16 { 359 vm.numOps++ 360 if vm.numOps > MaxOpsPerScript { 361 str := fmt.Sprintf("exceeded max operation limit of %d", 362 MaxOpsPerScript) 363 return scriptError(ErrTooManyOperations, str) 364 } 365 366 } else if len(data) > MaxScriptElementSize { 367 str := fmt.Sprintf("element size %d exceeds max allowed size %d", 368 len(data), MaxScriptElementSize) 369 return scriptError(ErrElementTooBig, str) 370 } 371 372 // Nothing left to do when this is not a conditional opcode and it is 373 // not in an executing branch. 374 if !vm.isBranchExecuting() && !isOpcodeConditional(op.value) { 375 return nil 376 } 377 378 // Ensure all executed data push opcodes use the minimal encoding when 379 // the minimal data verification flag is set. 380 if vm.dstack.verifyMinimalData && vm.isBranchExecuting() && 381 op.value >= 0 && op.value <= OP_PUSHDATA4 { 382 383 if err := checkMinimalDataPush(op, data); err != nil { 384 return err 385 } 386 } 387 388 return op.opfunc(op, data, vm) 389 } 390 391 // checkValidPC returns an error if the current script position is not valid for 392 // execution. 393 func (vm *Engine) checkValidPC() error { 394 if vm.scriptIdx >= len(vm.scripts) { 395 str := fmt.Sprintf("script index %d beyond total scripts %d", 396 vm.scriptIdx, len(vm.scripts)) 397 return scriptError(ErrInvalidProgramCounter, str) 398 } 399 return nil 400 } 401 402 // isWitnessVersionActive returns true if a witness program was extracted 403 // during the initialization of the Engine, and the program's version matches 404 // the specified version. 405 func (vm *Engine) isWitnessVersionActive(version uint) bool { 406 return vm.witnessProgram != nil && uint(vm.witnessVersion) == version 407 } 408 409 // verifyWitnessProgram validates the stored witness program using the passed 410 // witness as input. 411 func (vm *Engine) verifyWitnessProgram(witness [][]byte) error { 412 if vm.isWitnessVersionActive(0) { 413 switch len(vm.witnessProgram) { 414 case payToWitnessPubKeyHashDataSize: // P2WKH 415 // The witness stack should consist of exactly two 416 // items: the signature, and the pubkey. 417 if len(witness) != 2 { 418 err := fmt.Sprintf("should have exactly two "+ 419 "items in witness, instead have %v", len(witness)) 420 return scriptError(ErrWitnessProgramMismatch, err) 421 } 422 423 // Now we'll resume execution as if it were a regular 424 // p2pkh transaction. 425 pkScript, err := payToPubKeyHashScript(vm.witnessProgram) 426 if err != nil { 427 return err 428 } 429 430 const scriptVersion = 0 431 err = checkScriptParses(vm.version, pkScript) 432 if err != nil { 433 return err 434 } 435 436 // Set the stack to the provided witness stack, then 437 // append the pkScript generated above as the next 438 // script to execute. 439 vm.scripts = append(vm.scripts, pkScript) 440 vm.SetStack(witness) 441 442 case payToWitnessScriptHashDataSize: // P2WSH 443 // Additionally, The witness stack MUST NOT be empty at 444 // this point. 445 if len(witness) == 0 { 446 return scriptError(ErrWitnessProgramEmpty, "witness "+ 447 "program empty passed empty witness") 448 } 449 450 // Obtain the witness script which should be the last 451 // element in the passed stack. The size of the script 452 // MUST NOT exceed the max script size. 453 witnessScript := witness[len(witness)-1] 454 if len(witnessScript) > MaxScriptSize { 455 str := fmt.Sprintf("witnessScript size %d "+ 456 "is larger than max allowed size %d", 457 len(witnessScript), MaxScriptSize) 458 return scriptError(ErrScriptTooBig, str) 459 } 460 461 // Ensure that the serialized pkScript at the end of 462 // the witness stack matches the witness program. 463 witnessHash := sha256.Sum256(witnessScript) 464 if !bytes.Equal(witnessHash[:], vm.witnessProgram) { 465 return scriptError(ErrWitnessProgramMismatch, 466 "witness program hash mismatch") 467 } 468 469 // With all the validity checks passed, assert that the 470 // script parses without failure. 471 const scriptVersion = 0 472 err := checkScriptParses(vm.version, witnessScript) 473 if err != nil { 474 return err 475 } 476 477 // The hash matched successfully, so use the witness as 478 // the stack, and set the witnessScript to be the next 479 // script executed. 480 vm.scripts = append(vm.scripts, witnessScript) 481 vm.SetStack(witness[:len(witness)-1]) 482 483 default: 484 errStr := fmt.Sprintf("length of witness program "+ 485 "must either be %v or %v bytes, instead is %v bytes", 486 payToWitnessPubKeyHashDataSize, 487 payToWitnessScriptHashDataSize, 488 len(vm.witnessProgram)) 489 return scriptError(ErrWitnessProgramWrongLength, errStr) 490 } 491 } else if vm.hasFlag(ScriptVerifyDiscourageUpgradeableWitnessProgram) { 492 errStr := fmt.Sprintf("new witness program versions "+ 493 "invalid: %v", vm.witnessProgram) 494 return scriptError(ErrDiscourageUpgradableWitnessProgram, errStr) 495 } else { 496 // If we encounter an unknown witness program version and we 497 // aren't discouraging future unknown witness based soft-forks, 498 // then we de-activate the segwit behavior within the VM for 499 // the remainder of execution. 500 vm.witnessProgram = nil 501 } 502 503 if vm.isWitnessVersionActive(0) { 504 // All elements within the witness stack must not be greater 505 // than the maximum bytes which are allowed to be pushed onto 506 // the stack. 507 for _, witElement := range vm.GetStack() { 508 if len(witElement) > MaxScriptElementSize { 509 str := fmt.Sprintf("element size %d exceeds "+ 510 "max allowed size %d", len(witElement), 511 MaxScriptElementSize) 512 return scriptError(ErrElementTooBig, str) 513 } 514 } 515 } 516 517 return nil 518 } 519 520 // DisasmPC returns the string for the disassembly of the opcode that will be 521 // next to execute when Step is called. 522 func (vm *Engine) DisasmPC() (string, error) { 523 if err := vm.checkValidPC(); err != nil { 524 return "", err 525 } 526 527 // Create a copy of the current tokenizer and parse the next opcode in the 528 // copy to avoid mutating the current one. 529 peekTokenizer := vm.tokenizer 530 if !peekTokenizer.Next() { 531 // Note that due to the fact that all scripts are checked for parse 532 // failures before this code ever runs, there should never be an error 533 // here, but check again to be safe in case a refactor breaks that 534 // assumption or new script versions are introduced with different 535 // semantics. 536 if err := peekTokenizer.Err(); err != nil { 537 return "", err 538 } 539 540 // Note that this should be impossible to hit in practice because the 541 // only way it could happen would be for the final opcode of a script to 542 // already be parsed without the script index having been updated, which 543 // is not the case since stepping the script always increments the 544 // script index when parsing and executing the final opcode of a script. 545 // 546 // However, check again to be safe in case a refactor breaks that 547 // assumption or new script versions are introduced with different 548 // semantics. 549 str := fmt.Sprintf("program counter beyond script index %d (bytes %x)", 550 vm.scriptIdx, vm.scripts[vm.scriptIdx]) 551 return "", scriptError(ErrInvalidProgramCounter, str) 552 } 553 554 var buf strings.Builder 555 disasmOpcode(&buf, peekTokenizer.op, peekTokenizer.Data(), false) 556 return fmt.Sprintf("%02x:%04x: %s", vm.scriptIdx, vm.opcodeIdx, 557 buf.String()), nil 558 } 559 560 // DisasmScript returns the disassembly string for the script at the requested 561 // offset index. Index 0 is the signature script and 1 is the public key 562 // script. In the case of pay-to-script-hash, index 2 is the redeem script once 563 // the execution has progressed far enough to have successfully verified script 564 // hash and thus add the script to the scripts to execute. 565 func (vm *Engine) DisasmScript(idx int) (string, error) { 566 if idx >= len(vm.scripts) { 567 str := fmt.Sprintf("script index %d >= total scripts %d", idx, 568 len(vm.scripts)) 569 return "", scriptError(ErrInvalidIndex, str) 570 } 571 572 var disbuf strings.Builder 573 script := vm.scripts[idx] 574 tokenizer := MakeScriptTokenizer(vm.version, script) 575 var opcodeIdx int 576 for tokenizer.Next() { 577 disbuf.WriteString(fmt.Sprintf("%02x:%04x: ", idx, opcodeIdx)) 578 disasmOpcode(&disbuf, tokenizer.op, tokenizer.Data(), false) 579 disbuf.WriteByte('\n') 580 opcodeIdx++ 581 } 582 return disbuf.String(), tokenizer.Err() 583 } 584 585 // CheckErrorCondition returns nil if the running script has ended and was 586 // successful, leaving a a true boolean on the stack. An error otherwise, 587 // including if the script has not finished. 588 func (vm *Engine) CheckErrorCondition(finalScript bool) error { 589 // Check execution is actually done by ensuring the script index is after 590 // the final script in the array script. 591 if vm.scriptIdx < len(vm.scripts) { 592 return scriptError(ErrScriptUnfinished, 593 "error check when script unfinished") 594 } 595 596 // If we're in version zero witness execution mode, and this was the 597 // final script, then the stack MUST be clean in order to maintain 598 // compatibility with BIP16. 599 if finalScript && vm.isWitnessVersionActive(0) && vm.dstack.Depth() != 1 { 600 return scriptError(ErrEvalFalse, "witness program must "+ 601 "have clean stack") 602 } 603 604 // The final script must end with exactly one data stack item when the 605 // verify clean stack flag is set. Otherwise, there must be at least one 606 // data stack item in order to interpret it as a boolean. 607 if finalScript && vm.hasFlag(ScriptVerifyCleanStack) && 608 vm.dstack.Depth() != 1 { 609 610 str := fmt.Sprintf("stack must contain exactly one item (contains %d)", 611 vm.dstack.Depth()) 612 return scriptError(ErrCleanStack, str) 613 } else if vm.dstack.Depth() < 1 { 614 return scriptError(ErrEmptyStack, 615 "stack empty at end of script execution") 616 } 617 618 v, err := vm.dstack.PopBool() 619 if err != nil { 620 return err 621 } 622 if !v { 623 // Log interesting data. 624 log.Tracef("%v", newLogClosure(func() string { 625 var buf strings.Builder 626 buf.WriteString("scripts failed:\n") 627 for i := range vm.scripts { 628 dis, _ := vm.DisasmScript(i) 629 buf.WriteString(fmt.Sprintf("script%d:\n", i)) 630 buf.WriteString(dis) 631 } 632 return buf.String() 633 })) 634 return scriptError(ErrEvalFalse, 635 "false stack entry at end of script execution") 636 } 637 return nil 638 } 639 640 // Step executes the next instruction and moves the program counter to the next 641 // opcode in the script, or the next script if the current has ended. Step will 642 // return true in the case that the last opcode was successfully executed. 643 // 644 // The result of calling Step or any other method is undefined if an error is 645 // returned. 646 func (vm *Engine) Step() (done bool, err error) { 647 // Verify the engine is pointing to a valid program counter. 648 if err := vm.checkValidPC(); err != nil { 649 return true, err 650 } 651 652 // Attempt to parse the next opcode from the current script. 653 if !vm.tokenizer.Next() { 654 // Note that due to the fact that all scripts are checked for parse 655 // failures before this code ever runs, there should never be an error 656 // here, but check again to be safe in case a refactor breaks that 657 // assumption or new script versions are introduced with different 658 // semantics. 659 if err := vm.tokenizer.Err(); err != nil { 660 return false, err 661 } 662 663 str := fmt.Sprintf("attempt to step beyond script index %d (bytes %x)", 664 vm.scriptIdx, vm.scripts[vm.scriptIdx]) 665 return true, scriptError(ErrInvalidProgramCounter, str) 666 } 667 668 // Execute the opcode while taking into account several things such as 669 // disabled opcodes, illegal opcodes, maximum allowed operations per script, 670 // maximum script element sizes, and conditionals. 671 err = vm.executeOpcode(vm.tokenizer.op, vm.tokenizer.Data()) 672 if err != nil { 673 return true, err 674 } 675 676 // The number of elements in the combination of the data and alt stacks 677 // must not exceed the maximum number of stack elements allowed. 678 combinedStackSize := vm.dstack.Depth() + vm.astack.Depth() 679 if combinedStackSize > MaxStackSize { 680 str := fmt.Sprintf("combined stack size %d > max allowed %d", 681 combinedStackSize, MaxStackSize) 682 return false, scriptError(ErrStackOverflow, str) 683 } 684 685 // Prepare for next instruction. 686 vm.opcodeIdx++ 687 if vm.tokenizer.Done() { 688 // Illegal to have a conditional that straddles two scripts. 689 if len(vm.condStack) != 0 { 690 return false, scriptError(ErrUnbalancedConditional, 691 "end of script reached in conditional execution") 692 } 693 694 // Alt stack doesn't persist between scripts. 695 _ = vm.astack.DropN(vm.astack.Depth()) 696 697 // The number of operations is per script. 698 vm.numOps = 0 699 700 // Reset the opcode index for the next script. 701 vm.opcodeIdx = 0 702 703 // Advance to the next script as needed. 704 switch { 705 case vm.scriptIdx == 0 && vm.bip16: 706 vm.scriptIdx++ 707 vm.savedFirstStack = vm.GetStack() 708 709 case vm.scriptIdx == 1 && vm.bip16: 710 // Put us past the end for CheckErrorCondition() 711 vm.scriptIdx++ 712 713 // Check script ran successfully. 714 err := vm.CheckErrorCondition(false) 715 if err != nil { 716 return false, err 717 } 718 719 // Obtain the redeem script from the first stack and ensure it 720 // parses. 721 script := vm.savedFirstStack[len(vm.savedFirstStack)-1] 722 if err := checkScriptParses(vm.version, script); err != nil { 723 return false, err 724 } 725 vm.scripts = append(vm.scripts, script) 726 727 // Set stack to be the stack from first script minus the redeem 728 // script itself 729 vm.SetStack(vm.savedFirstStack[:len(vm.savedFirstStack)-1]) 730 731 case vm.scriptIdx == 1 && vm.witnessProgram != nil, 732 vm.scriptIdx == 2 && vm.witnessProgram != nil && vm.bip16: // np2sh 733 734 vm.scriptIdx++ 735 736 witness := vm.tx.TxIn[vm.txIdx].Witness 737 if err := vm.verifyWitnessProgram(witness); err != nil { 738 return false, err 739 } 740 741 default: 742 vm.scriptIdx++ 743 } 744 745 // Skip empty scripts. 746 if vm.scriptIdx < len(vm.scripts) && len(vm.scripts[vm.scriptIdx]) == 0 { 747 vm.scriptIdx++ 748 } 749 750 vm.lastCodeSep = 0 751 if vm.scriptIdx >= len(vm.scripts) { 752 return true, nil 753 } 754 755 // Finally, update the current tokenizer used to parse through scripts 756 // one opcode at a time to start from the beginning of the new script 757 // associated with the program counter. 758 vm.tokenizer = MakeScriptTokenizer(vm.version, vm.scripts[vm.scriptIdx]) 759 } 760 761 return false, nil 762 } 763 764 // Execute will execute all scripts in the script engine and return either nil 765 // for successful validation or an error if one occurred. 766 func (vm *Engine) Execute() (err error) { 767 // All script versions other than 0 currently execute without issue, 768 // making all outputs to them anyone can pay. In the future this 769 // will allow for the addition of new scripting languages. 770 if vm.version != 0 { 771 return nil 772 } 773 774 done := false 775 for !done { 776 log.Tracef("%v", newLogClosure(func() string { 777 dis, err := vm.DisasmPC() 778 if err != nil { 779 return fmt.Sprintf("stepping - failed to disasm pc: %v", err) 780 } 781 return fmt.Sprintf("stepping %v", dis) 782 })) 783 784 done, err = vm.Step() 785 if err != nil { 786 return err 787 } 788 log.Tracef("%v", newLogClosure(func() string { 789 var dstr, astr string 790 791 // Log the non-empty stacks when tracing. 792 if vm.dstack.Depth() != 0 { 793 dstr = "Stack:\n" + vm.dstack.String() 794 } 795 if vm.astack.Depth() != 0 { 796 astr = "AltStack:\n" + vm.astack.String() 797 } 798 799 return dstr + astr 800 })) 801 } 802 803 return vm.CheckErrorCondition(true) 804 } 805 806 // subScript returns the script since the last OP_CODESEPARATOR. 807 func (vm *Engine) subScript() []byte { 808 return vm.scripts[vm.scriptIdx][vm.lastCodeSep:] 809 } 810 811 // checkHashTypeEncoding returns whether or not the passed hashtype adheres to 812 // the strict encoding requirements if enabled. 813 func (vm *Engine) checkHashTypeEncoding(hashType SigHashType) error { 814 if !vm.hasFlag(ScriptVerifyStrictEncoding) { 815 return nil 816 } 817 818 sigHashType := hashType & ^SigHashAnyOneCanPay 819 if sigHashType < SigHashAll || sigHashType > SigHashSingle { 820 str := fmt.Sprintf("invalid hash type 0x%x", hashType) 821 return scriptError(ErrInvalidSigHashType, str) 822 } 823 return nil 824 } 825 826 // isStrictPubKeyEncoding returns whether or not the passed public key adheres 827 // to the strict encoding requirements. 828 func isStrictPubKeyEncoding(pubKey []byte) bool { 829 if len(pubKey) == 33 && (pubKey[0] == 0x02 || pubKey[0] == 0x03) { 830 // Compressed 831 return true 832 } 833 if len(pubKey) == 65 { 834 switch pubKey[0] { 835 case 0x04: 836 // Uncompressed 837 return true 838 839 case 0x06, 0x07: 840 // Hybrid 841 return true 842 } 843 } 844 return false 845 } 846 847 // checkPubKeyEncoding returns whether or not the passed public key adheres to 848 // the strict encoding requirements if enabled. 849 func (vm *Engine) checkPubKeyEncoding(pubKey []byte) error { 850 if vm.hasFlag(ScriptVerifyWitnessPubKeyType) && 851 vm.isWitnessVersionActive(0) && !btcec.IsCompressedPubKey(pubKey) { 852 853 str := "only compressed keys are accepted post-segwit" 854 return scriptError(ErrWitnessPubKeyType, str) 855 } 856 857 if !vm.hasFlag(ScriptVerifyStrictEncoding) { 858 return nil 859 } 860 861 if len(pubKey) == 33 && (pubKey[0] == 0x02 || pubKey[0] == 0x03) { 862 // Compressed 863 return nil 864 } 865 if len(pubKey) == 65 && pubKey[0] == 0x04 { 866 // Uncompressed 867 return nil 868 } 869 870 return scriptError(ErrPubKeyType, "unsupported public key type") 871 } 872 873 // checkSignatureEncoding returns whether or not the passed signature adheres to 874 // the strict encoding requirements if enabled. 875 func (vm *Engine) checkSignatureEncoding(sig []byte) error { 876 if !vm.hasFlag(ScriptVerifyDERSignatures) && 877 !vm.hasFlag(ScriptVerifyLowS) && 878 !vm.hasFlag(ScriptVerifyStrictEncoding) { 879 880 return nil 881 } 882 883 // The format of a DER encoded signature is as follows: 884 // 885 // 0x30 <total length> 0x02 <length of R> <R> 0x02 <length of S> <S> 886 // - 0x30 is the ASN.1 identifier for a sequence 887 // - Total length is 1 byte and specifies length of all remaining data 888 // - 0x02 is the ASN.1 identifier that specifies an integer follows 889 // - Length of R is 1 byte and specifies how many bytes R occupies 890 // - R is the arbitrary length big-endian encoded number which 891 // represents the R value of the signature. DER encoding dictates 892 // that the value must be encoded using the minimum possible number 893 // of bytes. This implies the first byte can only be null if the 894 // highest bit of the next byte is set in order to prevent it from 895 // being interpreted as a negative number. 896 // - 0x02 is once again the ASN.1 integer identifier 897 // - Length of S is 1 byte and specifies how many bytes S occupies 898 // - S is the arbitrary length big-endian encoded number which 899 // represents the S value of the signature. The encoding rules are 900 // identical as those for R. 901 const ( 902 asn1SequenceID = 0x30 903 asn1IntegerID = 0x02 904 905 // minSigLen is the minimum length of a DER encoded signature and is 906 // when both R and S are 1 byte each. 907 // 908 // 0x30 + <1-byte> + 0x02 + 0x01 + <byte> + 0x2 + 0x01 + <byte> 909 minSigLen = 8 910 911 // maxSigLen is the maximum length of a DER encoded signature and is 912 // when both R and S are 33 bytes each. It is 33 bytes because a 913 // 256-bit integer requires 32 bytes and an additional leading null byte 914 // might required if the high bit is set in the value. 915 // 916 // 0x30 + <1-byte> + 0x02 + 0x21 + <33 bytes> + 0x2 + 0x21 + <33 bytes> 917 maxSigLen = 72 918 919 // sequenceOffset is the byte offset within the signature of the 920 // expected ASN.1 sequence identifier. 921 sequenceOffset = 0 922 923 // dataLenOffset is the byte offset within the signature of the expected 924 // total length of all remaining data in the signature. 925 dataLenOffset = 1 926 927 // rTypeOffset is the byte offset within the signature of the ASN.1 928 // identifier for R and is expected to indicate an ASN.1 integer. 929 rTypeOffset = 2 930 931 // rLenOffset is the byte offset within the signature of the length of 932 // R. 933 rLenOffset = 3 934 935 // rOffset is the byte offset within the signature of R. 936 rOffset = 4 937 ) 938 939 // The signature must adhere to the minimum and maximum allowed length. 940 sigLen := len(sig) 941 if sigLen < minSigLen { 942 str := fmt.Sprintf("malformed signature: too short: %d < %d", sigLen, 943 minSigLen) 944 return scriptError(ErrSigTooShort, str) 945 } 946 if sigLen > maxSigLen { 947 str := fmt.Sprintf("malformed signature: too long: %d > %d", sigLen, 948 maxSigLen) 949 return scriptError(ErrSigTooLong, str) 950 } 951 952 // The signature must start with the ASN.1 sequence identifier. 953 if sig[sequenceOffset] != asn1SequenceID { 954 str := fmt.Sprintf("malformed signature: format has wrong type: %#x", 955 sig[sequenceOffset]) 956 return scriptError(ErrSigInvalidSeqID, str) 957 } 958 959 // The signature must indicate the correct amount of data for all elements 960 // related to R and S. 961 if int(sig[dataLenOffset]) != sigLen-2 { 962 str := fmt.Sprintf("malformed signature: bad length: %d != %d", 963 sig[dataLenOffset], sigLen-2) 964 return scriptError(ErrSigInvalidDataLen, str) 965 } 966 967 // Calculate the offsets of the elements related to S and ensure S is inside 968 // the signature. 969 // 970 // rLen specifies the length of the big-endian encoded number which 971 // represents the R value of the signature. 972 // 973 // sTypeOffset is the offset of the ASN.1 identifier for S and, like its R 974 // counterpart, is expected to indicate an ASN.1 integer. 975 // 976 // sLenOffset and sOffset are the byte offsets within the signature of the 977 // length of S and S itself, respectively. 978 rLen := int(sig[rLenOffset]) 979 sTypeOffset := rOffset + rLen 980 sLenOffset := sTypeOffset + 1 981 if sTypeOffset >= sigLen { 982 str := "malformed signature: S type indicator missing" 983 return scriptError(ErrSigMissingSTypeID, str) 984 } 985 if sLenOffset >= sigLen { 986 str := "malformed signature: S length missing" 987 return scriptError(ErrSigMissingSLen, str) 988 } 989 990 // The lengths of R and S must match the overall length of the signature. 991 // 992 // sLen specifies the length of the big-endian encoded number which 993 // represents the S value of the signature. 994 sOffset := sLenOffset + 1 995 sLen := int(sig[sLenOffset]) 996 if sOffset+sLen != sigLen { 997 str := "malformed signature: invalid S length" 998 return scriptError(ErrSigInvalidSLen, str) 999 } 1000 1001 // R elements must be ASN.1 integers. 1002 if sig[rTypeOffset] != asn1IntegerID { 1003 str := fmt.Sprintf("malformed signature: R integer marker: %#x != %#x", 1004 sig[rTypeOffset], asn1IntegerID) 1005 return scriptError(ErrSigInvalidRIntID, str) 1006 } 1007 1008 // Zero-length integers are not allowed for R. 1009 if rLen == 0 { 1010 str := "malformed signature: R length is zero" 1011 return scriptError(ErrSigZeroRLen, str) 1012 } 1013 1014 // R must not be negative. 1015 if sig[rOffset]&0x80 != 0 { 1016 str := "malformed signature: R is negative" 1017 return scriptError(ErrSigNegativeR, str) 1018 } 1019 1020 // Null bytes at the start of R are not allowed, unless R would otherwise be 1021 // interpreted as a negative number. 1022 if rLen > 1 && sig[rOffset] == 0x00 && sig[rOffset+1]&0x80 == 0 { 1023 str := "malformed signature: R value has too much padding" 1024 return scriptError(ErrSigTooMuchRPadding, str) 1025 } 1026 1027 // S elements must be ASN.1 integers. 1028 if sig[sTypeOffset] != asn1IntegerID { 1029 str := fmt.Sprintf("malformed signature: S integer marker: %#x != %#x", 1030 sig[sTypeOffset], asn1IntegerID) 1031 return scriptError(ErrSigInvalidSIntID, str) 1032 } 1033 1034 // Zero-length integers are not allowed for S. 1035 if sLen == 0 { 1036 str := "malformed signature: S length is zero" 1037 return scriptError(ErrSigZeroSLen, str) 1038 } 1039 1040 // S must not be negative. 1041 if sig[sOffset]&0x80 != 0 { 1042 str := "malformed signature: S is negative" 1043 return scriptError(ErrSigNegativeS, str) 1044 } 1045 1046 // Null bytes at the start of S are not allowed, unless S would otherwise be 1047 // interpreted as a negative number. 1048 if sLen > 1 && sig[sOffset] == 0x00 && sig[sOffset+1]&0x80 == 0 { 1049 str := "malformed signature: S value has too much padding" 1050 return scriptError(ErrSigTooMuchSPadding, str) 1051 } 1052 1053 // Verify the S value is <= half the order of the curve. This check is done 1054 // because when it is higher, the complement modulo the order can be used 1055 // instead which is a shorter encoding by 1 byte. Further, without 1056 // enforcing this, it is possible to replace a signature in a valid 1057 // transaction with the complement while still being a valid signature that 1058 // verifies. This would result in changing the transaction hash and thus is 1059 // a source of malleability. 1060 if vm.hasFlag(ScriptVerifyLowS) { 1061 sValue := new(big.Int).SetBytes(sig[sOffset : sOffset+sLen]) 1062 if sValue.Cmp(halfOrder) > 0 { 1063 return scriptError(ErrSigHighS, "signature is not canonical due "+ 1064 "to unnecessarily high S value") 1065 } 1066 } 1067 1068 return nil 1069 } 1070 1071 // getStack returns the contents of stack as a byte array bottom up 1072 func getStack(stack *stack) [][]byte { 1073 array := make([][]byte, stack.Depth()) 1074 for i := range array { 1075 // PeekByteArry can't fail due to overflow, already checked 1076 array[len(array)-i-1], _ = stack.PeekByteArray(int32(i)) 1077 } 1078 return array 1079 } 1080 1081 // setStack sets the stack to the contents of the array where the last item in 1082 // the array is the top item in the stack. 1083 func setStack(stack *stack, data [][]byte) { 1084 // This can not error. Only errors are for invalid arguments. 1085 _ = stack.DropN(stack.Depth()) 1086 1087 for i := range data { 1088 stack.PushByteArray(data[i]) 1089 } 1090 } 1091 1092 // GetStack returns the contents of the primary stack as an array. where the 1093 // last item in the array is the top of the stack. 1094 func (vm *Engine) GetStack() [][]byte { 1095 return getStack(&vm.dstack) 1096 } 1097 1098 // SetStack sets the contents of the primary stack to the contents of the 1099 // provided array where the last item in the array will be the top of the stack. 1100 func (vm *Engine) SetStack(data [][]byte) { 1101 setStack(&vm.dstack, data) 1102 } 1103 1104 // GetAltStack returns the contents of the alternate stack as an array where the 1105 // last item in the array is the top of the stack. 1106 func (vm *Engine) GetAltStack() [][]byte { 1107 return getStack(&vm.astack) 1108 } 1109 1110 // SetAltStack sets the contents of the alternate stack to the contents of the 1111 // provided array where the last item in the array will be the top of the stack. 1112 func (vm *Engine) SetAltStack(data [][]byte) { 1113 setStack(&vm.astack, data) 1114 } 1115 1116 // NewEngine returns a new script engine for the provided public key script, 1117 // transaction, and input index. The flags modify the behavior of the script 1118 // engine according to the description provided by each flag. 1119 func NewEngine(scriptPubKey []byte, tx *wire.MsgTx, txIdx int, flags ScriptFlags, 1120 sigCache *SigCache, hashCache *TxSigHashes, inputAmount int64) (*Engine, error) { 1121 const scriptVersion = 0 1122 1123 // The provided transaction input index must refer to a valid input. 1124 if txIdx < 0 || txIdx >= len(tx.TxIn) { 1125 str := fmt.Sprintf("transaction input index %d is negative or "+ 1126 ">= %d", txIdx, len(tx.TxIn)) 1127 return nil, scriptError(ErrInvalidIndex, str) 1128 } 1129 scriptSig := tx.TxIn[txIdx].SignatureScript 1130 1131 // When both the signature script and public key script are empty the result 1132 // is necessarily an error since the stack would end up being empty which is 1133 // equivalent to a false top element. Thus, just return the relevant error 1134 // now as an optimization. 1135 if len(scriptSig) == 0 && len(scriptPubKey) == 0 { 1136 return nil, scriptError(ErrEvalFalse, 1137 "false stack entry at end of script execution") 1138 } 1139 1140 // The clean stack flag (ScriptVerifyCleanStack) is not allowed without 1141 // either the pay-to-script-hash (P2SH) evaluation (ScriptBip16) 1142 // flag or the Segregated Witness (ScriptVerifyWitness) flag. 1143 // 1144 // Recall that evaluating a P2SH script without the flag set results in 1145 // non-P2SH evaluation which leaves the P2SH inputs on the stack. 1146 // Thus, allowing the clean stack flag without the P2SH flag would make 1147 // it possible to have a situation where P2SH would not be a soft fork 1148 // when it should be. The same goes for segwit which will pull in 1149 // additional scripts for execution from the witness stack. 1150 vm := Engine{flags: flags, sigCache: sigCache, hashCache: hashCache, 1151 inputAmount: inputAmount} 1152 if vm.hasFlag(ScriptVerifyCleanStack) && (!vm.hasFlag(ScriptBip16) && 1153 !vm.hasFlag(ScriptVerifyWitness)) { 1154 return nil, scriptError(ErrInvalidFlags, 1155 "invalid flags combination") 1156 } 1157 1158 // The signature script must only contain data pushes when the 1159 // associated flag is set. 1160 if vm.hasFlag(ScriptVerifySigPushOnly) && !IsPushOnlyScript(scriptSig) { 1161 return nil, scriptError(ErrNotPushOnly, 1162 "signature script is not push only") 1163 } 1164 1165 // The signature script must only contain data pushes for PS2H which is 1166 // determined based on the form of the public key script. 1167 if vm.hasFlag(ScriptBip16) && isScriptHashScript(scriptPubKey) { 1168 // Only accept input scripts that push data for P2SH. 1169 // Notice that the push only checks have already been done when 1170 // the flag to verify signature scripts are push only is set 1171 // above, so avoid checking again. 1172 alreadyChecked := vm.hasFlag(ScriptVerifySigPushOnly) 1173 if !alreadyChecked && !IsPushOnlyScript(scriptSig) { 1174 return nil, scriptError(ErrNotPushOnly, 1175 "pay to script hash is not push only") 1176 } 1177 vm.bip16 = true 1178 } 1179 1180 // The engine stores the scripts using a slice. This allows multiple 1181 // scripts to be executed in sequence. For example, with a 1182 // pay-to-script-hash transaction, there will be ultimately be a third 1183 // script to execute. 1184 scripts := [][]byte{scriptSig, scriptPubKey} 1185 for _, scr := range scripts { 1186 if len(scr) > MaxScriptSize { 1187 str := fmt.Sprintf("script size %d is larger than max allowed "+ 1188 "size %d", len(scr), MaxScriptSize) 1189 return nil, scriptError(ErrScriptTooBig, str) 1190 } 1191 1192 const scriptVersion = 0 1193 if err := checkScriptParses(scriptVersion, scr); err != nil { 1194 return nil, err 1195 } 1196 } 1197 vm.scripts = scripts 1198 1199 // Advance the program counter to the public key script if the signature 1200 // script is empty since there is nothing to execute for it in that case. 1201 if len(scriptSig) == 0 { 1202 vm.scriptIdx++ 1203 } 1204 if vm.hasFlag(ScriptVerifyMinimalData) { 1205 vm.dstack.verifyMinimalData = true 1206 vm.astack.verifyMinimalData = true 1207 } 1208 1209 // Check to see if we should execute in witness verification mode 1210 // according to the set flags. We check both the pkScript, and sigScript 1211 // here since in the case of nested p2sh, the scriptSig will be a valid 1212 // witness program. For nested p2sh, all the bytes after the first data 1213 // push should *exactly* match the witness program template. 1214 if vm.hasFlag(ScriptVerifyWitness) { 1215 // If witness evaluation is enabled, then P2SH MUST also be 1216 // active. 1217 if !vm.hasFlag(ScriptBip16) { 1218 errStr := "P2SH must be enabled to do witness verification" 1219 return nil, scriptError(ErrInvalidFlags, errStr) 1220 } 1221 1222 var witProgram []byte 1223 1224 switch { 1225 case IsWitnessProgram(vm.scripts[1]): 1226 // The scriptSig must be *empty* for all native witness 1227 // programs, otherwise we introduce malleability. 1228 if len(scriptSig) != 0 { 1229 errStr := "native witness program cannot " + 1230 "also have a signature script" 1231 return nil, scriptError(ErrWitnessMalleated, errStr) 1232 } 1233 1234 witProgram = scriptPubKey 1235 case len(tx.TxIn[txIdx].Witness) != 0 && vm.bip16: 1236 // The sigScript MUST be *exactly* a single canonical 1237 // data push of the witness program, otherwise we 1238 // reintroduce malleability. 1239 sigPops := vm.scripts[0] 1240 if len(sigPops) > 2 && 1241 isCanonicalPush(sigPops[0], sigPops[1:]) && 1242 IsWitnessProgram(sigPops[1:]) { 1243 1244 witProgram = sigPops[1:] 1245 } else { 1246 errStr := "signature script for witness " + 1247 "nested p2sh is not canonical" 1248 return nil, scriptError(ErrWitnessMalleatedP2SH, errStr) 1249 } 1250 } 1251 1252 if witProgram != nil { 1253 var err error 1254 vm.witnessVersion, vm.witnessProgram, err = ExtractWitnessProgramInfo(witProgram) 1255 if err != nil { 1256 return nil, err 1257 } 1258 } else { 1259 // If we didn't find a witness program in either the 1260 // pkScript or as a datapush within the sigScript, then 1261 // there MUST NOT be any witness data associated with 1262 // the input being validated. 1263 if vm.witnessProgram == nil && len(tx.TxIn[txIdx].Witness) != 0 { 1264 errStr := "non-witness inputs cannot have a witness" 1265 return nil, scriptError(ErrWitnessUnexpected, errStr) 1266 } 1267 } 1268 1269 } 1270 1271 // Setup the current tokenizer used to parse through the script one opcode 1272 // at a time with the script associated with the program counter. 1273 vm.tokenizer = MakeScriptTokenizer(scriptVersion, scripts[vm.scriptIdx]) 1274 1275 vm.tx = *tx 1276 vm.txIdx = txIdx 1277 1278 return &vm, nil 1279 }