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