engine.go 34 KB

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