github.com/palcoin-project/palcd@v1.0.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 14 "github.com/palcoin-project/palcd/btcec" 15 "github.com/palcoin-project/palcd/wire" 16 ) 17 18 // ScriptFlags is a bitmask defining additional operations or tests that will be 19 // done when executing a script pair. 20 type ScriptFlags uint32 21 22 const ( 23 // ScriptBip16 defines whether the bip16 threshold has passed and thus 24 // pay-to-script hash transactions will be fully validated. 25 ScriptBip16 ScriptFlags = 1 << iota 26 27 // ScriptStrictMultiSig defines whether to verify the stack item 28 // used by CHECKMULTISIG is zero length. 29 ScriptStrictMultiSig 30 31 // ScriptDiscourageUpgradableNops defines whether to verify that 32 // NOP1 through NOP10 are reserved for future soft-fork upgrades. This 33 // flag must not be used for consensus critical code nor applied to 34 // blocks as this flag is only for stricter standard transaction 35 // checks. This flag is only applied when the above opcodes are 36 // executed. 37 ScriptDiscourageUpgradableNops 38 39 // ScriptVerifyCheckLockTimeVerify defines whether to verify that 40 // a transaction output is spendable based on the locktime. 41 // This is BIP0065. 42 ScriptVerifyCheckLockTimeVerify 43 44 // ScriptVerifyCheckSequenceVerify defines whether to allow execution 45 // pathways of a script to be restricted based on the age of the output 46 // being spent. This is BIP0112. 47 ScriptVerifyCheckSequenceVerify 48 49 // ScriptVerifyCleanStack defines that the stack must contain only 50 // one stack element after evaluation and that the element must be 51 // true if interpreted as a boolean. This is rule 6 of BIP0062. 52 // This flag should never be used without the ScriptBip16 flag nor the 53 // ScriptVerifyWitness flag. 54 ScriptVerifyCleanStack 55 56 // ScriptVerifyDERSignatures defines that signatures are required 57 // to compily with the DER format. 58 ScriptVerifyDERSignatures 59 60 // ScriptVerifyLowS defines that signtures are required to comply with 61 // the DER format and whose S value is <= order / 2. This is rule 5 62 // of BIP0062. 63 ScriptVerifyLowS 64 65 // ScriptVerifyMinimalData defines that signatures must use the smallest 66 // push operator. This is both rules 3 and 4 of BIP0062. 67 ScriptVerifyMinimalData 68 69 // ScriptVerifyNullFail defines that signatures must be empty if 70 // a CHECKSIG or CHECKMULTISIG operation fails. 71 ScriptVerifyNullFail 72 73 // ScriptVerifySigPushOnly defines that signature scripts must contain 74 // only pushed data. This is rule 2 of BIP0062. 75 ScriptVerifySigPushOnly 76 77 // ScriptVerifyStrictEncoding defines that signature scripts and 78 // public keys must follow the strict encoding requirements. 79 ScriptVerifyStrictEncoding 80 81 // ScriptVerifyWitness defines whether or not to verify a transaction 82 // output using a witness program template. 83 ScriptVerifyWitness 84 85 // ScriptVerifyDiscourageUpgradeableWitnessProgram makes witness 86 // program with versions 2-16 non-standard. 87 ScriptVerifyDiscourageUpgradeableWitnessProgram 88 89 // ScriptVerifyMinimalIf makes a script with an OP_IF/OP_NOTIF whose 90 // operand is anything other than empty vector or [0x01] non-standard. 91 ScriptVerifyMinimalIf 92 93 // ScriptVerifyWitnessPubKeyType makes a script within a check-sig 94 // operation whose public key isn't serialized in a compressed format 95 // non-standard. 96 ScriptVerifyWitnessPubKeyType 97 ) 98 99 const ( 100 // MaxStackSize is the maximum combined height of stack and alt stack 101 // during execution. 102 MaxStackSize = 1000 103 104 // MaxScriptSize is the maximum allowed length of a raw script. 105 MaxScriptSize = 10000 106 107 // payToWitnessPubKeyHashDataSize is the size of the witness program's 108 // data push for a pay-to-witness-pub-key-hash output. 109 payToWitnessPubKeyHashDataSize = 20 110 111 // payToWitnessScriptHashDataSize is the size of the witness program's 112 // data push for a pay-to-witness-script-hash output. 113 payToWitnessScriptHashDataSize = 32 114 ) 115 116 // halforder is used to tame ECDSA malleability (see BIP0062). 117 var halfOrder = new(big.Int).Rsh(btcec.S256().N, 1) 118 119 // Engine is the virtual machine that executes scripts. 120 type Engine struct { 121 scripts [][]parsedOpcode 122 scriptIdx int 123 scriptOff int 124 lastCodeSep int 125 dstack stack // data stack 126 astack stack // alt stack 127 tx wire.MsgTx 128 txIdx int 129 condStack []int 130 numOps int 131 flags ScriptFlags 132 sigCache *SigCache 133 hashCache *TxSigHashes 134 bip16 bool // treat execution as pay-to-script-hash 135 savedFirstStack [][]byte // stack from first script for bip16 scripts 136 witnessVersion int 137 witnessProgram []byte 138 inputAmount int64 139 } 140 141 // hasFlag returns whether the script engine instance has the passed flag set. 142 func (vm *Engine) hasFlag(flag ScriptFlags) bool { 143 return vm.flags&flag == flag 144 } 145 146 // isBranchExecuting returns whether or not the current conditional branch is 147 // actively executing. For example, when the data stack has an OP_FALSE on it 148 // and an OP_IF is encountered, the branch is inactive until an OP_ELSE or 149 // OP_ENDIF is encountered. It properly handles nested conditionals. 150 func (vm *Engine) isBranchExecuting() bool { 151 if len(vm.condStack) == 0 { 152 return true 153 } 154 return vm.condStack[len(vm.condStack)-1] == OpCondTrue 155 } 156 157 // executeOpcode peforms execution on the passed opcode. It takes into account 158 // whether or not it is hidden by conditionals, but some rules still must be 159 // tested in this case. 160 func (vm *Engine) executeOpcode(pop *parsedOpcode) error { 161 // Disabled opcodes are fail on program counter. 162 if pop.isDisabled() { 163 str := fmt.Sprintf("attempt to execute disabled opcode %s", 164 pop.opcode.name) 165 return scriptError(ErrDisabledOpcode, str) 166 } 167 168 // Always-illegal opcodes are fail on program counter. 169 if pop.alwaysIllegal() { 170 str := fmt.Sprintf("attempt to execute reserved opcode %s", 171 pop.opcode.name) 172 return scriptError(ErrReservedOpcode, str) 173 } 174 175 // Note that this includes OP_RESERVED which counts as a push operation. 176 if pop.opcode.value > OP_16 { 177 vm.numOps++ 178 if vm.numOps > MaxOpsPerScript { 179 str := fmt.Sprintf("exceeded max operation limit of %d", 180 MaxOpsPerScript) 181 return scriptError(ErrTooManyOperations, str) 182 } 183 184 } else if len(pop.data) > MaxScriptElementSize { 185 str := fmt.Sprintf("element size %d exceeds max allowed size %d", 186 len(pop.data), MaxScriptElementSize) 187 return scriptError(ErrElementTooBig, str) 188 } 189 190 // Nothing left to do when this is not a conditional opcode and it is 191 // not in an executing branch. 192 if !vm.isBranchExecuting() && !pop.isConditional() { 193 return nil 194 } 195 196 // Ensure all executed data push opcodes use the minimal encoding when 197 // the minimal data verification flag is set. 198 if vm.dstack.verifyMinimalData && vm.isBranchExecuting() && 199 pop.opcode.value >= 0 && pop.opcode.value <= OP_PUSHDATA4 { 200 201 if err := pop.checkMinimalDataPush(); err != nil { 202 return err 203 } 204 } 205 206 return pop.opcode.opfunc(pop, vm) 207 } 208 209 // disasm is a helper function to produce the output for DisasmPC and 210 // DisasmScript. It produces the opcode prefixed by the program counter at the 211 // provided position in the script. It does no error checking and leaves that 212 // to the caller to provide a valid offset. 213 func (vm *Engine) disasm(scriptIdx int, scriptOff int) string { 214 return fmt.Sprintf("%02x:%04x: %s", scriptIdx, scriptOff, 215 vm.scripts[scriptIdx][scriptOff].print(false)) 216 } 217 218 // validPC returns an error if the current script position is valid for 219 // execution, nil otherwise. 220 func (vm *Engine) validPC() error { 221 if vm.scriptIdx >= len(vm.scripts) { 222 str := fmt.Sprintf("past input scripts %v:%v %v:xxxx", 223 vm.scriptIdx, vm.scriptOff, len(vm.scripts)) 224 return scriptError(ErrInvalidProgramCounter, str) 225 } 226 if vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { 227 str := fmt.Sprintf("past input scripts %v:%v %v:%04d", 228 vm.scriptIdx, vm.scriptOff, vm.scriptIdx, 229 len(vm.scripts[vm.scriptIdx])) 230 return scriptError(ErrInvalidProgramCounter, str) 231 } 232 return nil 233 } 234 235 // curPC returns either the current script and offset, or an error if the 236 // position isn't valid. 237 func (vm *Engine) curPC() (script int, off int, err error) { 238 err = vm.validPC() 239 if err != nil { 240 return 0, 0, err 241 } 242 return vm.scriptIdx, vm.scriptOff, nil 243 } 244 245 // isWitnessVersionActive returns true if a witness program was extracted 246 // during the initialization of the Engine, and the program's version matches 247 // the specified version. 248 func (vm *Engine) isWitnessVersionActive(version uint) bool { 249 return vm.witnessProgram != nil && uint(vm.witnessVersion) == version 250 } 251 252 // verifyWitnessProgram validates the stored witness program using the passed 253 // witness as input. 254 func (vm *Engine) verifyWitnessProgram(witness [][]byte) error { 255 if vm.isWitnessVersionActive(0) { 256 switch len(vm.witnessProgram) { 257 case payToWitnessPubKeyHashDataSize: // P2WKH 258 // The witness stack should consist of exactly two 259 // items: the signature, and the pubkey. 260 if len(witness) != 2 { 261 err := fmt.Sprintf("should have exactly two "+ 262 "items in witness, instead have %v", len(witness)) 263 return scriptError(ErrWitnessProgramMismatch, err) 264 } 265 266 // Now we'll resume execution as if it were a regular 267 // p2pkh transaction. 268 pkScript, err := payToPubKeyHashScript(vm.witnessProgram) 269 if err != nil { 270 return err 271 } 272 pops, err := parseScript(pkScript) 273 if err != nil { 274 return err 275 } 276 277 // Set the stack to the provided witness stack, then 278 // append the pkScript generated above as the next 279 // script to execute. 280 vm.scripts = append(vm.scripts, pops) 281 vm.SetStack(witness) 282 283 case payToWitnessScriptHashDataSize: // P2WSH 284 // Additionally, The witness stack MUST NOT be empty at 285 // this point. 286 if len(witness) == 0 { 287 return scriptError(ErrWitnessProgramEmpty, "witness "+ 288 "program empty passed empty witness") 289 } 290 291 // Obtain the witness script which should be the last 292 // element in the passed stack. The size of the script 293 // MUST NOT exceed the max script size. 294 witnessScript := witness[len(witness)-1] 295 if len(witnessScript) > MaxScriptSize { 296 str := fmt.Sprintf("witnessScript size %d "+ 297 "is larger than max allowed size %d", 298 len(witnessScript), MaxScriptSize) 299 return scriptError(ErrScriptTooBig, str) 300 } 301 302 // Ensure that the serialized pkScript at the end of 303 // the witness stack matches the witness program. 304 witnessHash := sha256.Sum256(witnessScript) 305 if !bytes.Equal(witnessHash[:], vm.witnessProgram) { 306 return scriptError(ErrWitnessProgramMismatch, 307 "witness program hash mismatch") 308 } 309 310 // With all the validity checks passed, parse the 311 // script into individual op-codes so w can execute it 312 // as the next script. 313 pops, err := parseScript(witnessScript) 314 if err != nil { 315 return err 316 } 317 318 // The hash matched successfully, so use the witness as 319 // the stack, and set the witnessScript to be the next 320 // script executed. 321 vm.scripts = append(vm.scripts, pops) 322 vm.SetStack(witness[:len(witness)-1]) 323 324 default: 325 errStr := fmt.Sprintf("length of witness program "+ 326 "must either be %v or %v bytes, instead is %v bytes", 327 payToWitnessPubKeyHashDataSize, 328 payToWitnessScriptHashDataSize, 329 len(vm.witnessProgram)) 330 return scriptError(ErrWitnessProgramWrongLength, errStr) 331 } 332 } else if vm.hasFlag(ScriptVerifyDiscourageUpgradeableWitnessProgram) { 333 errStr := fmt.Sprintf("new witness program versions "+ 334 "invalid: %v", vm.witnessProgram) 335 return scriptError(ErrDiscourageUpgradableWitnessProgram, errStr) 336 } else { 337 // If we encounter an unknown witness program version and we 338 // aren't discouraging future unknown witness based soft-forks, 339 // then we de-activate the segwit behavior within the VM for 340 // the remainder of execution. 341 vm.witnessProgram = nil 342 } 343 344 if vm.isWitnessVersionActive(0) { 345 // All elements within the witness stack must not be greater 346 // than the maximum bytes which are allowed to be pushed onto 347 // the stack. 348 for _, witElement := range vm.GetStack() { 349 if len(witElement) > MaxScriptElementSize { 350 str := fmt.Sprintf("element size %d exceeds "+ 351 "max allowed size %d", len(witElement), 352 MaxScriptElementSize) 353 return scriptError(ErrElementTooBig, str) 354 } 355 } 356 } 357 358 return nil 359 } 360 361 // DisasmPC returns the string for the disassembly of the opcode that will be 362 // next to execute when Step() is called. 363 func (vm *Engine) DisasmPC() (string, error) { 364 scriptIdx, scriptOff, err := vm.curPC() 365 if err != nil { 366 return "", err 367 } 368 return vm.disasm(scriptIdx, scriptOff), nil 369 } 370 371 // DisasmScript returns the disassembly string for the script at the requested 372 // offset index. Index 0 is the signature script and 1 is the public key 373 // script. 374 func (vm *Engine) DisasmScript(idx int) (string, error) { 375 if idx >= len(vm.scripts) { 376 str := fmt.Sprintf("script index %d >= total scripts %d", idx, 377 len(vm.scripts)) 378 return "", scriptError(ErrInvalidIndex, str) 379 } 380 381 var disstr string 382 for i := range vm.scripts[idx] { 383 disstr = disstr + vm.disasm(idx, i) + "\n" 384 } 385 return disstr, nil 386 } 387 388 // CheckErrorCondition returns nil if the running script has ended and was 389 // successful, leaving a a true boolean on the stack. An error otherwise, 390 // including if the script has not finished. 391 func (vm *Engine) CheckErrorCondition(finalScript bool) error { 392 // Check execution is actually done. When pc is past the end of script 393 // array there are no more scripts to run. 394 if vm.scriptIdx < len(vm.scripts) { 395 return scriptError(ErrScriptUnfinished, 396 "error check when script unfinished") 397 } 398 399 // If we're in version zero witness execution mode, and this was the 400 // final script, then the stack MUST be clean in order to maintain 401 // compatibility with BIP16. 402 if finalScript && vm.isWitnessVersionActive(0) && vm.dstack.Depth() != 1 { 403 return scriptError(ErrEvalFalse, "witness program must "+ 404 "have clean stack") 405 } 406 407 if finalScript && vm.hasFlag(ScriptVerifyCleanStack) && 408 vm.dstack.Depth() != 1 { 409 410 str := fmt.Sprintf("stack contains %d unexpected items", 411 vm.dstack.Depth()-1) 412 return scriptError(ErrCleanStack, str) 413 } else if vm.dstack.Depth() < 1 { 414 return scriptError(ErrEmptyStack, 415 "stack empty at end of script execution") 416 } 417 418 v, err := vm.dstack.PopBool() 419 if err != nil { 420 return err 421 } 422 if !v { 423 // Log interesting data. 424 log.Tracef("%v", newLogClosure(func() string { 425 dis0, _ := vm.DisasmScript(0) 426 dis1, _ := vm.DisasmScript(1) 427 return fmt.Sprintf("scripts failed: script0: %s\n"+ 428 "script1: %s", dis0, dis1) 429 })) 430 return scriptError(ErrEvalFalse, 431 "false stack entry at end of script execution") 432 } 433 return nil 434 } 435 436 // Step will execute the next instruction and move the program counter to the 437 // next opcode in the script, or the next script if the current has ended. Step 438 // will return true in the case that the last opcode was successfully executed. 439 // 440 // The result of calling Step or any other method is undefined if an error is 441 // returned. 442 func (vm *Engine) Step() (done bool, err error) { 443 // Verify that it is pointing to a valid script address. 444 err = vm.validPC() 445 if err != nil { 446 return true, err 447 } 448 opcode := &vm.scripts[vm.scriptIdx][vm.scriptOff] 449 vm.scriptOff++ 450 451 // Execute the opcode while taking into account several things such as 452 // disabled opcodes, illegal opcodes, maximum allowed operations per 453 // script, maximum script element sizes, and conditionals. 454 err = vm.executeOpcode(opcode) 455 if err != nil { 456 return true, err 457 } 458 459 // The number of elements in the combination of the data and alt stacks 460 // must not exceed the maximum number of stack elements allowed. 461 combinedStackSize := vm.dstack.Depth() + vm.astack.Depth() 462 if combinedStackSize > MaxStackSize { 463 str := fmt.Sprintf("combined stack size %d > max allowed %d", 464 combinedStackSize, MaxStackSize) 465 return false, scriptError(ErrStackOverflow, str) 466 } 467 468 // Prepare for next instruction. 469 if vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { 470 // Illegal to have an `if' that straddles two scripts. 471 if err == nil && len(vm.condStack) != 0 { 472 return false, scriptError(ErrUnbalancedConditional, 473 "end of script reached in conditional execution") 474 } 475 476 // Alt stack doesn't persist. 477 _ = vm.astack.DropN(vm.astack.Depth()) 478 479 vm.numOps = 0 // number of ops is per script. 480 vm.scriptOff = 0 481 if vm.scriptIdx == 0 && vm.bip16 { 482 vm.scriptIdx++ 483 vm.savedFirstStack = vm.GetStack() 484 } else if vm.scriptIdx == 1 && vm.bip16 { 485 // Put us past the end for CheckErrorCondition() 486 vm.scriptIdx++ 487 // Check script ran successfully and pull the script 488 // out of the first stack and execute that. 489 err := vm.CheckErrorCondition(false) 490 if err != nil { 491 return false, err 492 } 493 494 script := vm.savedFirstStack[len(vm.savedFirstStack)-1] 495 pops, err := parseScript(script) 496 if err != nil { 497 return false, err 498 } 499 vm.scripts = append(vm.scripts, pops) 500 501 // Set stack to be the stack from first script minus the 502 // script itself 503 vm.SetStack(vm.savedFirstStack[:len(vm.savedFirstStack)-1]) 504 } else if (vm.scriptIdx == 1 && vm.witnessProgram != nil) || 505 (vm.scriptIdx == 2 && vm.witnessProgram != nil && vm.bip16) { // Nested P2SH. 506 507 vm.scriptIdx++ 508 509 witness := vm.tx.TxIn[vm.txIdx].Witness 510 if err := vm.verifyWitnessProgram(witness); err != nil { 511 return false, err 512 } 513 } else { 514 vm.scriptIdx++ 515 } 516 // there are zero length scripts in the wild 517 if vm.scriptIdx < len(vm.scripts) && vm.scriptOff >= len(vm.scripts[vm.scriptIdx]) { 518 vm.scriptIdx++ 519 } 520 vm.lastCodeSep = 0 521 if vm.scriptIdx >= len(vm.scripts) { 522 return true, nil 523 } 524 } 525 return false, nil 526 } 527 528 // Execute will execute all scripts in the script engine and return either nil 529 // for successful validation or an error if one occurred. 530 func (vm *Engine) Execute() (err error) { 531 done := false 532 for !done { 533 log.Tracef("%v", newLogClosure(func() string { 534 dis, err := vm.DisasmPC() 535 if err != nil { 536 return fmt.Sprintf("stepping (%v)", err) 537 } 538 return fmt.Sprintf("stepping %v", dis) 539 })) 540 541 done, err = vm.Step() 542 if err != nil { 543 return err 544 } 545 log.Tracef("%v", newLogClosure(func() string { 546 var dstr, astr string 547 548 // if we're tracing, dump the stacks. 549 if vm.dstack.Depth() != 0 { 550 dstr = "Stack:\n" + vm.dstack.String() 551 } 552 if vm.astack.Depth() != 0 { 553 astr = "AltStack:\n" + vm.astack.String() 554 } 555 556 return dstr + astr 557 })) 558 } 559 560 return vm.CheckErrorCondition(true) 561 } 562 563 // subScript returns the script since the last OP_CODESEPARATOR. 564 func (vm *Engine) subScript() []parsedOpcode { 565 return vm.scripts[vm.scriptIdx][vm.lastCodeSep:] 566 } 567 568 // checkHashTypeEncoding returns whether or not the passed hashtype adheres to 569 // the strict encoding requirements if enabled. 570 func (vm *Engine) checkHashTypeEncoding(hashType SigHashType) error { 571 if !vm.hasFlag(ScriptVerifyStrictEncoding) { 572 return nil 573 } 574 575 sigHashType := hashType & ^SigHashAnyOneCanPay 576 if sigHashType < SigHashAll || sigHashType > SigHashSingle { 577 str := fmt.Sprintf("invalid hash type 0x%x", hashType) 578 return scriptError(ErrInvalidSigHashType, str) 579 } 580 return nil 581 } 582 583 // checkPubKeyEncoding returns whether or not the passed public key adheres to 584 // the strict encoding requirements if enabled. 585 func (vm *Engine) checkPubKeyEncoding(pubKey []byte) error { 586 if vm.hasFlag(ScriptVerifyWitnessPubKeyType) && 587 vm.isWitnessVersionActive(0) && !btcec.IsCompressedPubKey(pubKey) { 588 589 str := "only compressed keys are accepted post-segwit" 590 return scriptError(ErrWitnessPubKeyType, str) 591 } 592 593 if !vm.hasFlag(ScriptVerifyStrictEncoding) { 594 return nil 595 } 596 597 if len(pubKey) == 33 && (pubKey[0] == 0x02 || pubKey[0] == 0x03) { 598 // Compressed 599 return nil 600 } 601 if len(pubKey) == 65 && pubKey[0] == 0x04 { 602 // Uncompressed 603 return nil 604 } 605 606 return scriptError(ErrPubKeyType, "unsupported public key type") 607 } 608 609 // checkSignatureEncoding returns whether or not the passed signature adheres to 610 // the strict encoding requirements if enabled. 611 func (vm *Engine) checkSignatureEncoding(sig []byte) error { 612 if !vm.hasFlag(ScriptVerifyDERSignatures) && 613 !vm.hasFlag(ScriptVerifyLowS) && 614 !vm.hasFlag(ScriptVerifyStrictEncoding) { 615 616 return nil 617 } 618 619 // The format of a DER encoded signature is as follows: 620 // 621 // 0x30 <total length> 0x02 <length of R> <R> 0x02 <length of S> <S> 622 // - 0x30 is the ASN.1 identifier for a sequence 623 // - Total length is 1 byte and specifies length of all remaining data 624 // - 0x02 is the ASN.1 identifier that specifies an integer follows 625 // - Length of R is 1 byte and specifies how many bytes R occupies 626 // - R is the arbitrary length big-endian encoded number which 627 // represents the R value of the signature. DER encoding dictates 628 // that the value must be encoded using the minimum possible number 629 // of bytes. This implies the first byte can only be null if the 630 // highest bit of the next byte is set in order to prevent it from 631 // being interpreted as a negative number. 632 // - 0x02 is once again the ASN.1 integer identifier 633 // - Length of S is 1 byte and specifies how many bytes S occupies 634 // - S is the arbitrary length big-endian encoded number which 635 // represents the S value of the signature. The encoding rules are 636 // identical as those for R. 637 const ( 638 asn1SequenceID = 0x30 639 asn1IntegerID = 0x02 640 641 // minSigLen is the minimum length of a DER encoded signature and is 642 // when both R and S are 1 byte each. 643 // 644 // 0x30 + <1-byte> + 0x02 + 0x01 + <byte> + 0x2 + 0x01 + <byte> 645 minSigLen = 8 646 647 // maxSigLen is the maximum length of a DER encoded signature and is 648 // when both R and S are 33 bytes each. It is 33 bytes because a 649 // 256-bit integer requires 32 bytes and an additional leading null byte 650 // might required if the high bit is set in the value. 651 // 652 // 0x30 + <1-byte> + 0x02 + 0x21 + <33 bytes> + 0x2 + 0x21 + <33 bytes> 653 maxSigLen = 72 654 655 // sequenceOffset is the byte offset within the signature of the 656 // expected ASN.1 sequence identifier. 657 sequenceOffset = 0 658 659 // dataLenOffset is the byte offset within the signature of the expected 660 // total length of all remaining data in the signature. 661 dataLenOffset = 1 662 663 // rTypeOffset is the byte offset within the signature of the ASN.1 664 // identifier for R and is expected to indicate an ASN.1 integer. 665 rTypeOffset = 2 666 667 // rLenOffset is the byte offset within the signature of the length of 668 // R. 669 rLenOffset = 3 670 671 // rOffset is the byte offset within the signature of R. 672 rOffset = 4 673 ) 674 675 // The signature must adhere to the minimum and maximum allowed length. 676 sigLen := len(sig) 677 if sigLen < minSigLen { 678 str := fmt.Sprintf("malformed signature: too short: %d < %d", sigLen, 679 minSigLen) 680 return scriptError(ErrSigTooShort, str) 681 } 682 if sigLen > maxSigLen { 683 str := fmt.Sprintf("malformed signature: too long: %d > %d", sigLen, 684 maxSigLen) 685 return scriptError(ErrSigTooLong, str) 686 } 687 688 // The signature must start with the ASN.1 sequence identifier. 689 if sig[sequenceOffset] != asn1SequenceID { 690 str := fmt.Sprintf("malformed signature: format has wrong type: %#x", 691 sig[sequenceOffset]) 692 return scriptError(ErrSigInvalidSeqID, str) 693 } 694 695 // The signature must indicate the correct amount of data for all elements 696 // related to R and S. 697 if int(sig[dataLenOffset]) != sigLen-2 { 698 str := fmt.Sprintf("malformed signature: bad length: %d != %d", 699 sig[dataLenOffset], sigLen-2) 700 return scriptError(ErrSigInvalidDataLen, str) 701 } 702 703 // Calculate the offsets of the elements related to S and ensure S is inside 704 // the signature. 705 // 706 // rLen specifies the length of the big-endian encoded number which 707 // represents the R value of the signature. 708 // 709 // sTypeOffset is the offset of the ASN.1 identifier for S and, like its R 710 // counterpart, is expected to indicate an ASN.1 integer. 711 // 712 // sLenOffset and sOffset are the byte offsets within the signature of the 713 // length of S and S itself, respectively. 714 rLen := int(sig[rLenOffset]) 715 sTypeOffset := rOffset + rLen 716 sLenOffset := sTypeOffset + 1 717 if sTypeOffset >= sigLen { 718 str := "malformed signature: S type indicator missing" 719 return scriptError(ErrSigMissingSTypeID, str) 720 } 721 if sLenOffset >= sigLen { 722 str := "malformed signature: S length missing" 723 return scriptError(ErrSigMissingSLen, str) 724 } 725 726 // The lengths of R and S must match the overall length of the signature. 727 // 728 // sLen specifies the length of the big-endian encoded number which 729 // represents the S value of the signature. 730 sOffset := sLenOffset + 1 731 sLen := int(sig[sLenOffset]) 732 if sOffset+sLen != sigLen { 733 str := "malformed signature: invalid S length" 734 return scriptError(ErrSigInvalidSLen, str) 735 } 736 737 // R elements must be ASN.1 integers. 738 if sig[rTypeOffset] != asn1IntegerID { 739 str := fmt.Sprintf("malformed signature: R integer marker: %#x != %#x", 740 sig[rTypeOffset], asn1IntegerID) 741 return scriptError(ErrSigInvalidRIntID, str) 742 } 743 744 // Zero-length integers are not allowed for R. 745 if rLen == 0 { 746 str := "malformed signature: R length is zero" 747 return scriptError(ErrSigZeroRLen, str) 748 } 749 750 // R must not be negative. 751 if sig[rOffset]&0x80 != 0 { 752 str := "malformed signature: R is negative" 753 return scriptError(ErrSigNegativeR, str) 754 } 755 756 // Null bytes at the start of R are not allowed, unless R would otherwise be 757 // interpreted as a negative number. 758 if rLen > 1 && sig[rOffset] == 0x00 && sig[rOffset+1]&0x80 == 0 { 759 str := "malformed signature: R value has too much padding" 760 return scriptError(ErrSigTooMuchRPadding, str) 761 } 762 763 // S elements must be ASN.1 integers. 764 if sig[sTypeOffset] != asn1IntegerID { 765 str := fmt.Sprintf("malformed signature: S integer marker: %#x != %#x", 766 sig[sTypeOffset], asn1IntegerID) 767 return scriptError(ErrSigInvalidSIntID, str) 768 } 769 770 // Zero-length integers are not allowed for S. 771 if sLen == 0 { 772 str := "malformed signature: S length is zero" 773 return scriptError(ErrSigZeroSLen, str) 774 } 775 776 // S must not be negative. 777 if sig[sOffset]&0x80 != 0 { 778 str := "malformed signature: S is negative" 779 return scriptError(ErrSigNegativeS, str) 780 } 781 782 // Null bytes at the start of S are not allowed, unless S would otherwise be 783 // interpreted as a negative number. 784 if sLen > 1 && sig[sOffset] == 0x00 && sig[sOffset+1]&0x80 == 0 { 785 str := "malformed signature: S value has too much padding" 786 return scriptError(ErrSigTooMuchSPadding, str) 787 } 788 789 // Verify the S value is <= half the order of the curve. This check is done 790 // because when it is higher, the complement modulo the order can be used 791 // instead which is a shorter encoding by 1 byte. Further, without 792 // enforcing this, it is possible to replace a signature in a valid 793 // transaction with the complement while still being a valid signature that 794 // verifies. This would result in changing the transaction hash and thus is 795 // a source of malleability. 796 if vm.hasFlag(ScriptVerifyLowS) { 797 sValue := new(big.Int).SetBytes(sig[sOffset : sOffset+sLen]) 798 if sValue.Cmp(halfOrder) > 0 { 799 return scriptError(ErrSigHighS, "signature is not canonical due "+ 800 "to unnecessarily high S value") 801 } 802 } 803 804 return nil 805 } 806 807 // getStack returns the contents of stack as a byte array bottom up 808 func getStack(stack *stack) [][]byte { 809 array := make([][]byte, stack.Depth()) 810 for i := range array { 811 // PeekByteArry can't fail due to overflow, already checked 812 array[len(array)-i-1], _ = stack.PeekByteArray(int32(i)) 813 } 814 return array 815 } 816 817 // setStack sets the stack to the contents of the array where the last item in 818 // the array is the top item in the stack. 819 func setStack(stack *stack, data [][]byte) { 820 // This can not error. Only errors are for invalid arguments. 821 _ = stack.DropN(stack.Depth()) 822 823 for i := range data { 824 stack.PushByteArray(data[i]) 825 } 826 } 827 828 // GetStack returns the contents of the primary stack as an array. where the 829 // last item in the array is the top of the stack. 830 func (vm *Engine) GetStack() [][]byte { 831 return getStack(&vm.dstack) 832 } 833 834 // SetStack sets the contents of the primary stack to the contents of the 835 // provided array where the last item in the array will be the top of the stack. 836 func (vm *Engine) SetStack(data [][]byte) { 837 setStack(&vm.dstack, data) 838 } 839 840 // GetAltStack returns the contents of the alternate stack as an array where the 841 // last item in the array is the top of the stack. 842 func (vm *Engine) GetAltStack() [][]byte { 843 return getStack(&vm.astack) 844 } 845 846 // SetAltStack sets the contents of the alternate stack to the contents of the 847 // provided array where the last item in the array will be the top of the stack. 848 func (vm *Engine) SetAltStack(data [][]byte) { 849 setStack(&vm.astack, data) 850 } 851 852 // NewEngine returns a new script engine for the provided public key script, 853 // transaction, and input index. The flags modify the behavior of the script 854 // engine according to the description provided by each flag. 855 func NewEngine(scriptPubKey []byte, tx *wire.MsgTx, txIdx int, flags ScriptFlags, 856 sigCache *SigCache, hashCache *TxSigHashes, inputAmount int64) (*Engine, error) { 857 858 // The provided transaction input index must refer to a valid input. 859 if txIdx < 0 || txIdx >= len(tx.TxIn) { 860 str := fmt.Sprintf("transaction input index %d is negative or "+ 861 ">= %d", txIdx, len(tx.TxIn)) 862 return nil, scriptError(ErrInvalidIndex, str) 863 } 864 scriptSig := tx.TxIn[txIdx].SignatureScript 865 866 // When both the signature script and public key script are empty the 867 // result is necessarily an error since the stack would end up being 868 // empty which is equivalent to a false top element. Thus, just return 869 // the relevant error now as an optimization. 870 if len(scriptSig) == 0 && len(scriptPubKey) == 0 { 871 return nil, scriptError(ErrEvalFalse, 872 "false stack entry at end of script execution") 873 } 874 875 // The clean stack flag (ScriptVerifyCleanStack) is not allowed without 876 // either the pay-to-script-hash (P2SH) evaluation (ScriptBip16) 877 // flag or the Segregated Witness (ScriptVerifyWitness) flag. 878 // 879 // Recall that evaluating a P2SH script without the flag set results in 880 // non-P2SH evaluation which leaves the P2SH inputs on the stack. 881 // Thus, allowing the clean stack flag without the P2SH flag would make 882 // it possible to have a situation where P2SH would not be a soft fork 883 // when it should be. The same goes for segwit which will pull in 884 // additional scripts for execution from the witness stack. 885 vm := Engine{flags: flags, sigCache: sigCache, hashCache: hashCache, 886 inputAmount: inputAmount} 887 if vm.hasFlag(ScriptVerifyCleanStack) && (!vm.hasFlag(ScriptBip16) && 888 !vm.hasFlag(ScriptVerifyWitness)) { 889 return nil, scriptError(ErrInvalidFlags, 890 "invalid flags combination") 891 } 892 893 // The signature script must only contain data pushes when the 894 // associated flag is set. 895 if vm.hasFlag(ScriptVerifySigPushOnly) && !IsPushOnlyScript(scriptSig) { 896 return nil, scriptError(ErrNotPushOnly, 897 "signature script is not push only") 898 } 899 900 // The engine stores the scripts in parsed form using a slice. This 901 // allows multiple scripts to be executed in sequence. For example, 902 // with a pay-to-script-hash transaction, there will be ultimately be 903 // a third script to execute. 904 scripts := [][]byte{scriptSig, scriptPubKey} 905 vm.scripts = make([][]parsedOpcode, len(scripts)) 906 for i, scr := range scripts { 907 if len(scr) > MaxScriptSize { 908 str := fmt.Sprintf("script size %d is larger than max "+ 909 "allowed size %d", len(scr), MaxScriptSize) 910 return nil, scriptError(ErrScriptTooBig, str) 911 } 912 var err error 913 vm.scripts[i], err = parseScript(scr) 914 if err != nil { 915 return nil, err 916 } 917 } 918 919 // Advance the program counter to the public key script if the signature 920 // script is empty since there is nothing to execute for it in that 921 // case. 922 if len(scripts[0]) == 0 { 923 vm.scriptIdx++ 924 } 925 926 if vm.hasFlag(ScriptBip16) && isScriptHash(vm.scripts[1]) { 927 // Only accept input scripts that push data for P2SH. 928 if !isPushOnly(vm.scripts[0]) { 929 return nil, scriptError(ErrNotPushOnly, 930 "pay to script hash is not push only") 931 } 932 vm.bip16 = true 933 } 934 if vm.hasFlag(ScriptVerifyMinimalData) { 935 vm.dstack.verifyMinimalData = true 936 vm.astack.verifyMinimalData = true 937 } 938 939 // Check to see if we should execute in witness verification mode 940 // according to the set flags. We check both the pkScript, and sigScript 941 // here since in the case of nested p2sh, the scriptSig will be a valid 942 // witness program. For nested p2sh, all the bytes after the first data 943 // push should *exactly* match the witness program template. 944 if vm.hasFlag(ScriptVerifyWitness) { 945 // If witness evaluation is enabled, then P2SH MUST also be 946 // active. 947 if !vm.hasFlag(ScriptBip16) { 948 errStr := "P2SH must be enabled to do witness verification" 949 return nil, scriptError(ErrInvalidFlags, errStr) 950 } 951 952 var witProgram []byte 953 954 switch { 955 case isWitnessProgram(vm.scripts[1]): 956 // The scriptSig must be *empty* for all native witness 957 // programs, otherwise we introduce malleability. 958 if len(scriptSig) != 0 { 959 errStr := "native witness program cannot " + 960 "also have a signature script" 961 return nil, scriptError(ErrWitnessMalleated, errStr) 962 } 963 964 witProgram = scriptPubKey 965 case len(tx.TxIn[txIdx].Witness) != 0 && vm.bip16: 966 // The sigScript MUST be *exactly* a single canonical 967 // data push of the witness program, otherwise we 968 // reintroduce malleability. 969 sigPops := vm.scripts[0] 970 if len(sigPops) == 1 && canonicalPush(sigPops[0]) && 971 IsWitnessProgram(sigPops[0].data) { 972 973 witProgram = sigPops[0].data 974 } else { 975 errStr := "signature script for witness " + 976 "nested p2sh is not canonical" 977 return nil, scriptError(ErrWitnessMalleatedP2SH, errStr) 978 } 979 } 980 981 if witProgram != nil { 982 var err error 983 vm.witnessVersion, vm.witnessProgram, err = ExtractWitnessProgramInfo(witProgram) 984 if err != nil { 985 return nil, err 986 } 987 } else { 988 // If we didn't find a witness program in either the 989 // pkScript or as a datapush within the sigScript, then 990 // there MUST NOT be any witness data associated with 991 // the input being validated. 992 if vm.witnessProgram == nil && len(tx.TxIn[txIdx].Witness) != 0 { 993 errStr := "non-witness inputs cannot have a witness" 994 return nil, scriptError(ErrWitnessUnexpected, errStr) 995 } 996 } 997 998 } 999 1000 vm.tx = *tx 1001 vm.txIdx = txIdx 1002 1003 return &vm, nil 1004 }