opcode.go 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421
  1. // Copyright (c) 2013-2017 The btcsuite developers
  2. // Copyright (c) 2019 Caleb James DeLisle
  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. "encoding/binary"
  9. "fmt"
  10. sha256 "github.com/minio/sha256-simd"
  11. "github.com/pkt-cash/pktd/btcutil/sha1"
  12. "github.com/pkt-cash/pktd/btcutil"
  13. "github.com/pkt-cash/pktd/btcutil/er"
  14. "github.com/pkt-cash/pktd/txscript/opcode"
  15. "github.com/pkt-cash/pktd/txscript/params"
  16. "github.com/pkt-cash/pktd/txscript/parsescript"
  17. "github.com/pkt-cash/pktd/txscript/scriptnum"
  18. "github.com/pkt-cash/pktd/txscript/txscripterr"
  19. "github.com/pkt-cash/pktd/wire/constants"
  20. "github.com/pkt-cash/pktd/btcec"
  21. "github.com/pkt-cash/pktd/chaincfg/chainhash"
  22. )
  23. // Conditional execution constants.
  24. const (
  25. OpCondFalse = 0
  26. OpCondTrue = 1
  27. OpCondSkip = 2
  28. )
  29. func executeOp(po *parsescript.ParsedOpcode, e *Engine) er.R {
  30. switch po.Opcode.Value {
  31. case opcode.OP_FALSE:
  32. return opcodeFalse(po, e)
  33. case opcode.OP_DATA_1:
  34. return opcodePushData(po, e)
  35. case opcode.OP_DATA_2:
  36. return opcodePushData(po, e)
  37. case opcode.OP_DATA_3:
  38. return opcodePushData(po, e)
  39. case opcode.OP_DATA_4:
  40. return opcodePushData(po, e)
  41. case opcode.OP_DATA_5:
  42. return opcodePushData(po, e)
  43. case opcode.OP_DATA_6:
  44. return opcodePushData(po, e)
  45. case opcode.OP_DATA_7:
  46. return opcodePushData(po, e)
  47. case opcode.OP_DATA_8:
  48. return opcodePushData(po, e)
  49. case opcode.OP_DATA_9:
  50. return opcodePushData(po, e)
  51. case opcode.OP_DATA_10:
  52. return opcodePushData(po, e)
  53. case opcode.OP_DATA_11:
  54. return opcodePushData(po, e)
  55. case opcode.OP_DATA_12:
  56. return opcodePushData(po, e)
  57. case opcode.OP_DATA_13:
  58. return opcodePushData(po, e)
  59. case opcode.OP_DATA_14:
  60. return opcodePushData(po, e)
  61. case opcode.OP_DATA_15:
  62. return opcodePushData(po, e)
  63. case opcode.OP_DATA_16:
  64. return opcodePushData(po, e)
  65. case opcode.OP_DATA_17:
  66. return opcodePushData(po, e)
  67. case opcode.OP_DATA_18:
  68. return opcodePushData(po, e)
  69. case opcode.OP_DATA_19:
  70. return opcodePushData(po, e)
  71. case opcode.OP_DATA_20:
  72. return opcodePushData(po, e)
  73. case opcode.OP_DATA_21:
  74. return opcodePushData(po, e)
  75. case opcode.OP_DATA_22:
  76. return opcodePushData(po, e)
  77. case opcode.OP_DATA_23:
  78. return opcodePushData(po, e)
  79. case opcode.OP_DATA_24:
  80. return opcodePushData(po, e)
  81. case opcode.OP_DATA_25:
  82. return opcodePushData(po, e)
  83. case opcode.OP_DATA_26:
  84. return opcodePushData(po, e)
  85. case opcode.OP_DATA_27:
  86. return opcodePushData(po, e)
  87. case opcode.OP_DATA_28:
  88. return opcodePushData(po, e)
  89. case opcode.OP_DATA_29:
  90. return opcodePushData(po, e)
  91. case opcode.OP_DATA_30:
  92. return opcodePushData(po, e)
  93. case opcode.OP_DATA_31:
  94. return opcodePushData(po, e)
  95. case opcode.OP_DATA_32:
  96. return opcodePushData(po, e)
  97. case opcode.OP_DATA_33:
  98. return opcodePushData(po, e)
  99. case opcode.OP_DATA_34:
  100. return opcodePushData(po, e)
  101. case opcode.OP_DATA_35:
  102. return opcodePushData(po, e)
  103. case opcode.OP_DATA_36:
  104. return opcodePushData(po, e)
  105. case opcode.OP_DATA_37:
  106. return opcodePushData(po, e)
  107. case opcode.OP_DATA_38:
  108. return opcodePushData(po, e)
  109. case opcode.OP_DATA_39:
  110. return opcodePushData(po, e)
  111. case opcode.OP_DATA_40:
  112. return opcodePushData(po, e)
  113. case opcode.OP_DATA_41:
  114. return opcodePushData(po, e)
  115. case opcode.OP_DATA_42:
  116. return opcodePushData(po, e)
  117. case opcode.OP_DATA_43:
  118. return opcodePushData(po, e)
  119. case opcode.OP_DATA_44:
  120. return opcodePushData(po, e)
  121. case opcode.OP_DATA_45:
  122. return opcodePushData(po, e)
  123. case opcode.OP_DATA_46:
  124. return opcodePushData(po, e)
  125. case opcode.OP_DATA_47:
  126. return opcodePushData(po, e)
  127. case opcode.OP_DATA_48:
  128. return opcodePushData(po, e)
  129. case opcode.OP_DATA_49:
  130. return opcodePushData(po, e)
  131. case opcode.OP_DATA_50:
  132. return opcodePushData(po, e)
  133. case opcode.OP_DATA_51:
  134. return opcodePushData(po, e)
  135. case opcode.OP_DATA_52:
  136. return opcodePushData(po, e)
  137. case opcode.OP_DATA_53:
  138. return opcodePushData(po, e)
  139. case opcode.OP_DATA_54:
  140. return opcodePushData(po, e)
  141. case opcode.OP_DATA_55:
  142. return opcodePushData(po, e)
  143. case opcode.OP_DATA_56:
  144. return opcodePushData(po, e)
  145. case opcode.OP_DATA_57:
  146. return opcodePushData(po, e)
  147. case opcode.OP_DATA_58:
  148. return opcodePushData(po, e)
  149. case opcode.OP_DATA_59:
  150. return opcodePushData(po, e)
  151. case opcode.OP_DATA_60:
  152. return opcodePushData(po, e)
  153. case opcode.OP_DATA_61:
  154. return opcodePushData(po, e)
  155. case opcode.OP_DATA_62:
  156. return opcodePushData(po, e)
  157. case opcode.OP_DATA_63:
  158. return opcodePushData(po, e)
  159. case opcode.OP_DATA_64:
  160. return opcodePushData(po, e)
  161. case opcode.OP_DATA_65:
  162. return opcodePushData(po, e)
  163. case opcode.OP_DATA_66:
  164. return opcodePushData(po, e)
  165. case opcode.OP_DATA_67:
  166. return opcodePushData(po, e)
  167. case opcode.OP_DATA_68:
  168. return opcodePushData(po, e)
  169. case opcode.OP_DATA_69:
  170. return opcodePushData(po, e)
  171. case opcode.OP_DATA_70:
  172. return opcodePushData(po, e)
  173. case opcode.OP_DATA_71:
  174. return opcodePushData(po, e)
  175. case opcode.OP_DATA_72:
  176. return opcodePushData(po, e)
  177. case opcode.OP_DATA_73:
  178. return opcodePushData(po, e)
  179. case opcode.OP_DATA_74:
  180. return opcodePushData(po, e)
  181. case opcode.OP_DATA_75:
  182. return opcodePushData(po, e)
  183. case opcode.OP_PUSHDATA1:
  184. return opcodePushData(po, e)
  185. case opcode.OP_PUSHDATA2:
  186. return opcodePushData(po, e)
  187. case opcode.OP_PUSHDATA4:
  188. return opcodePushData(po, e)
  189. case opcode.OP_1NEGATE:
  190. return opcode1Negate(po, e)
  191. case opcode.OP_RESERVED:
  192. return opcodeReserved(po, e)
  193. case opcode.OP_TRUE:
  194. return opcodeN(po, e)
  195. case opcode.OP_2:
  196. return opcodeN(po, e)
  197. case opcode.OP_3:
  198. return opcodeN(po, e)
  199. case opcode.OP_4:
  200. return opcodeN(po, e)
  201. case opcode.OP_5:
  202. return opcodeN(po, e)
  203. case opcode.OP_6:
  204. return opcodeN(po, e)
  205. case opcode.OP_7:
  206. return opcodeN(po, e)
  207. case opcode.OP_8:
  208. return opcodeN(po, e)
  209. case opcode.OP_9:
  210. return opcodeN(po, e)
  211. case opcode.OP_10:
  212. return opcodeN(po, e)
  213. case opcode.OP_11:
  214. return opcodeN(po, e)
  215. case opcode.OP_12:
  216. return opcodeN(po, e)
  217. case opcode.OP_13:
  218. return opcodeN(po, e)
  219. case opcode.OP_14:
  220. return opcodeN(po, e)
  221. case opcode.OP_15:
  222. return opcodeN(po, e)
  223. case opcode.OP_16:
  224. return opcodeN(po, e)
  225. // Control opcodes.
  226. case opcode.OP_NOP:
  227. return opcodeNop(po, e)
  228. case opcode.OP_VER:
  229. return opcodeReserved(po, e)
  230. case opcode.OP_IF:
  231. return opcodeIf(po, e)
  232. case opcode.OP_NOTIF:
  233. return opcodeNotIf(po, e)
  234. case opcode.OP_VERIF:
  235. return opcodeReserved(po, e)
  236. case opcode.OP_VOTE:
  237. return opcode2Drop(po, e)
  238. case opcode.OP_ELSE:
  239. return opcodeElse(po, e)
  240. case opcode.OP_ENDIF:
  241. return opcodeEndif(po, e)
  242. case opcode.OP_VERIFY:
  243. return opcodeVerify(po, e)
  244. case opcode.OP_RETURN:
  245. return opcodeReturn(po, e)
  246. case opcode.OP_CHECKLOCKTIMEVERIFY:
  247. return opcodeCheckLockTimeVerify(po, e)
  248. case opcode.OP_CHECKSEQUENCEVERIFY:
  249. return opcodeCheckSequenceVerify(po, e)
  250. // Stack opcodes.
  251. case opcode.OP_TOALTSTACK:
  252. return opcodeToAltStack(po, e)
  253. case opcode.OP_FROMALTSTACK:
  254. return opcodeFromAltStack(po, e)
  255. case opcode.OP_2DROP:
  256. return opcode2Drop(po, e)
  257. case opcode.OP_2DUP:
  258. return opcode2Dup(po, e)
  259. case opcode.OP_3DUP:
  260. return opcode3Dup(po, e)
  261. case opcode.OP_2OVER:
  262. return opcode2Over(po, e)
  263. case opcode.OP_2ROT:
  264. return opcode2Rot(po, e)
  265. case opcode.OP_2SWAP:
  266. return opcode2Swap(po, e)
  267. case opcode.OP_IFDUP:
  268. return opcodeIfDup(po, e)
  269. case opcode.OP_DEPTH:
  270. return opcodeDepth(po, e)
  271. case opcode.OP_DROP:
  272. return opcodeDrop(po, e)
  273. case opcode.OP_DUP:
  274. return opcodeDup(po, e)
  275. case opcode.OP_NIP:
  276. return opcodeNip(po, e)
  277. case opcode.OP_OVER:
  278. return opcodeOver(po, e)
  279. case opcode.OP_PICK:
  280. return opcodePick(po, e)
  281. case opcode.OP_ROLL:
  282. return opcodeRoll(po, e)
  283. case opcode.OP_ROT:
  284. return opcodeRot(po, e)
  285. case opcode.OP_SWAP:
  286. return opcodeSwap(po, e)
  287. case opcode.OP_TUCK:
  288. return opcodeTuck(po, e)
  289. // Splice opcodes.
  290. case opcode.OP_CAT:
  291. return opcodeDisabled(po, e)
  292. case opcode.OP_SUBSTR:
  293. return opcodeDisabled(po, e)
  294. case opcode.OP_LEFT:
  295. return opcodeDisabled(po, e)
  296. case opcode.OP_RIGHT:
  297. return opcodeDisabled(po, e)
  298. case opcode.OP_SIZE:
  299. return opcodeSize(po, e)
  300. // Bitwise logic opcodes.
  301. case opcode.OP_INVERT:
  302. return opcodeDisabled(po, e)
  303. case opcode.OP_AND:
  304. return opcodeDisabled(po, e)
  305. case opcode.OP_OR:
  306. return opcodeDisabled(po, e)
  307. case opcode.OP_XOR:
  308. return opcodeDisabled(po, e)
  309. case opcode.OP_EQUAL:
  310. return opcodeEqual(po, e)
  311. case opcode.OP_EQUALVERIFY:
  312. return opcodeEqualVerify(po, e)
  313. case opcode.OP_RESERVED1:
  314. return opcodeReserved(po, e)
  315. case opcode.OP_RESERVED2:
  316. return opcodeReserved(po, e)
  317. // Numeric related opcodes.
  318. case opcode.OP_1ADD:
  319. return opcode1Add(po, e)
  320. case opcode.OP_1SUB:
  321. return opcode1Sub(po, e)
  322. case opcode.OP_2MUL:
  323. return opcodeDisabled(po, e)
  324. case opcode.OP_2DIV:
  325. return opcodeDisabled(po, e)
  326. case opcode.OP_NEGATE:
  327. return opcodeNegate(po, e)
  328. case opcode.OP_ABS:
  329. return opcodeAbs(po, e)
  330. case opcode.OP_NOT:
  331. return opcodeNot(po, e)
  332. case opcode.OP_0NOTEQUAL:
  333. return opcode0NotEqual(po, e)
  334. case opcode.OP_ADD:
  335. return opcodeAdd(po, e)
  336. case opcode.OP_SUB:
  337. return opcodeSub(po, e)
  338. case opcode.OP_MUL:
  339. return opcodeDisabled(po, e)
  340. case opcode.OP_DIV:
  341. return opcodeDisabled(po, e)
  342. case opcode.OP_MOD:
  343. return opcodeDisabled(po, e)
  344. case opcode.OP_LSHIFT:
  345. return opcodeDisabled(po, e)
  346. case opcode.OP_RSHIFT:
  347. return opcodeDisabled(po, e)
  348. case opcode.OP_BOOLAND:
  349. return opcodeBoolAnd(po, e)
  350. case opcode.OP_BOOLOR:
  351. return opcodeBoolOr(po, e)
  352. case opcode.OP_NUMEQUAL:
  353. return opcodeNumEqual(po, e)
  354. case opcode.OP_NUMEQUALVERIFY:
  355. return opcodeNumEqualVerify(po, e)
  356. case opcode.OP_NUMNOTEQUAL:
  357. return opcodeNumNotEqual(po, e)
  358. case opcode.OP_LESSTHAN:
  359. return opcodeLessThan(po, e)
  360. case opcode.OP_GREATERTHAN:
  361. return opcodeGreaterThan(po, e)
  362. case opcode.OP_LESSTHANOREQUAL:
  363. return opcodeLessThanOrEqual(po, e)
  364. case opcode.OP_GREATERTHANOREQUAL:
  365. return opcodeGreaterThanOrEqual(po, e)
  366. case opcode.OP_MIN:
  367. return opcodeMin(po, e)
  368. case opcode.OP_MAX:
  369. return opcodeMax(po, e)
  370. case opcode.OP_WITHIN:
  371. return opcodeWithin(po, e)
  372. // Crypto opcodes.
  373. case opcode.OP_RIPEMD160:
  374. return opcodeRipemd160(po, e)
  375. case opcode.OP_SHA1:
  376. return opcodeSha1(po, e)
  377. case opcode.OP_SHA256:
  378. return opcodeSha256(po, e)
  379. case opcode.OP_HASH160:
  380. return opcodeHash160(po, e)
  381. case opcode.OP_HASH256:
  382. return opcodeHash256(po, e)
  383. case opcode.OP_CODESEPARATOR:
  384. return opcodeCodeSeparator(po, e)
  385. case opcode.OP_CHECKSIG:
  386. return opcodeCheckSig(po, e)
  387. case opcode.OP_CHECKSIGVERIFY:
  388. return opcodeCheckSigVerify(po, e)
  389. case opcode.OP_CHECKMULTISIG:
  390. return opcodeCheckMultiSig(po, e)
  391. case opcode.OP_CHECKMULTISIGVERIFY:
  392. return opcodeCheckMultiSigVerify(po, e)
  393. // Reserved opcodes.
  394. case opcode.OP_NOP1:
  395. return opcodeNop(po, e)
  396. case opcode.OP_NOP4:
  397. return opcodeNop(po, e)
  398. case opcode.OP_NOP5:
  399. return opcodeNop(po, e)
  400. case opcode.OP_NOP6:
  401. return opcodeNop(po, e)
  402. case opcode.OP_NOP7:
  403. return opcodeNop(po, e)
  404. case opcode.OP_NOP8:
  405. return opcodeNop(po, e)
  406. case opcode.OP_NOP9:
  407. return opcodeNop(po, e)
  408. case opcode.OP_NOP10:
  409. return opcodeNop(po, e)
  410. // Undefined opcodes.
  411. case opcode.OP_UNKNOWN186:
  412. return opcodeInvalid(po, e)
  413. case opcode.OP_UNKNOWN187:
  414. return opcodeInvalid(po, e)
  415. case opcode.OP_UNKNOWN188:
  416. return opcodeInvalid(po, e)
  417. case opcode.OP_UNKNOWN189:
  418. return opcodeInvalid(po, e)
  419. case opcode.OP_UNKNOWN190:
  420. return opcodeInvalid(po, e)
  421. case opcode.OP_UNKNOWN191:
  422. return opcodeInvalid(po, e)
  423. case opcode.OP_UNKNOWN192:
  424. return opcodeInvalid(po, e)
  425. case opcode.OP_UNKNOWN193:
  426. return opcodeInvalid(po, e)
  427. case opcode.OP_UNKNOWN194:
  428. return opcodeInvalid(po, e)
  429. case opcode.OP_UNKNOWN195:
  430. return opcodeInvalid(po, e)
  431. case opcode.OP_UNKNOWN196:
  432. return opcodeInvalid(po, e)
  433. case opcode.OP_UNKNOWN197:
  434. return opcodeInvalid(po, e)
  435. case opcode.OP_UNKNOWN198:
  436. return opcodeInvalid(po, e)
  437. case opcode.OP_UNKNOWN199:
  438. return opcodeInvalid(po, e)
  439. case opcode.OP_UNKNOWN200:
  440. return opcodeInvalid(po, e)
  441. case opcode.OP_UNKNOWN201:
  442. return opcodeInvalid(po, e)
  443. case opcode.OP_UNKNOWN202:
  444. return opcodeInvalid(po, e)
  445. case opcode.OP_UNKNOWN203:
  446. return opcodeInvalid(po, e)
  447. case opcode.OP_UNKNOWN204:
  448. return opcodeInvalid(po, e)
  449. case opcode.OP_UNKNOWN205:
  450. return opcodeInvalid(po, e)
  451. case opcode.OP_UNKNOWN206:
  452. return opcodeInvalid(po, e)
  453. case opcode.OP_UNKNOWN207:
  454. return opcodeInvalid(po, e)
  455. case opcode.OP_UNKNOWN208:
  456. return opcodeInvalid(po, e)
  457. case opcode.OP_UNKNOWN209:
  458. return opcodeInvalid(po, e)
  459. case opcode.OP_UNKNOWN210:
  460. return opcodeInvalid(po, e)
  461. case opcode.OP_UNKNOWN211:
  462. return opcodeInvalid(po, e)
  463. case opcode.OP_UNKNOWN212:
  464. return opcodeInvalid(po, e)
  465. case opcode.OP_UNKNOWN213:
  466. return opcodeInvalid(po, e)
  467. case opcode.OP_UNKNOWN214:
  468. return opcodeInvalid(po, e)
  469. case opcode.OP_UNKNOWN215:
  470. return opcodeInvalid(po, e)
  471. case opcode.OP_UNKNOWN216:
  472. return opcodeInvalid(po, e)
  473. case opcode.OP_UNKNOWN217:
  474. return opcodeInvalid(po, e)
  475. case opcode.OP_UNKNOWN218:
  476. return opcodeInvalid(po, e)
  477. case opcode.OP_UNKNOWN219:
  478. return opcodeInvalid(po, e)
  479. case opcode.OP_UNKNOWN220:
  480. return opcodeInvalid(po, e)
  481. case opcode.OP_UNKNOWN221:
  482. return opcodeInvalid(po, e)
  483. case opcode.OP_UNKNOWN222:
  484. return opcodeInvalid(po, e)
  485. case opcode.OP_UNKNOWN223:
  486. return opcodeInvalid(po, e)
  487. case opcode.OP_UNKNOWN224:
  488. return opcodeInvalid(po, e)
  489. case opcode.OP_UNKNOWN225:
  490. return opcodeInvalid(po, e)
  491. case opcode.OP_UNKNOWN226:
  492. return opcodeInvalid(po, e)
  493. case opcode.OP_UNKNOWN227:
  494. return opcodeInvalid(po, e)
  495. case opcode.OP_UNKNOWN228:
  496. return opcodeInvalid(po, e)
  497. case opcode.OP_UNKNOWN229:
  498. return opcodeInvalid(po, e)
  499. case opcode.OP_UNKNOWN230:
  500. return opcodeInvalid(po, e)
  501. case opcode.OP_UNKNOWN231:
  502. return opcodeInvalid(po, e)
  503. case opcode.OP_UNKNOWN232:
  504. return opcodeInvalid(po, e)
  505. case opcode.OP_UNKNOWN233:
  506. return opcodeInvalid(po, e)
  507. case opcode.OP_UNKNOWN234:
  508. return opcodeInvalid(po, e)
  509. case opcode.OP_UNKNOWN235:
  510. return opcodeInvalid(po, e)
  511. case opcode.OP_UNKNOWN236:
  512. return opcodeInvalid(po, e)
  513. case opcode.OP_UNKNOWN237:
  514. return opcodeInvalid(po, e)
  515. case opcode.OP_UNKNOWN238:
  516. return opcodeInvalid(po, e)
  517. case opcode.OP_UNKNOWN239:
  518. return opcodeInvalid(po, e)
  519. case opcode.OP_UNKNOWN240:
  520. return opcodeInvalid(po, e)
  521. case opcode.OP_UNKNOWN241:
  522. return opcodeInvalid(po, e)
  523. case opcode.OP_UNKNOWN242:
  524. return opcodeInvalid(po, e)
  525. case opcode.OP_UNKNOWN243:
  526. return opcodeInvalid(po, e)
  527. case opcode.OP_UNKNOWN244:
  528. return opcodeInvalid(po, e)
  529. case opcode.OP_UNKNOWN245:
  530. return opcodeInvalid(po, e)
  531. case opcode.OP_UNKNOWN246:
  532. return opcodeInvalid(po, e)
  533. case opcode.OP_UNKNOWN247:
  534. return opcodeInvalid(po, e)
  535. case opcode.OP_UNKNOWN248:
  536. return opcodeInvalid(po, e)
  537. case opcode.OP_UNKNOWN249:
  538. return opcodeInvalid(po, e)
  539. // Bitcoin Core internal use opcode. Defined here for completeness.
  540. case opcode.OP_SMALLINTEGER:
  541. return opcodeInvalid(po, e)
  542. case opcode.OP_PUBKEYS:
  543. return opcodeInvalid(po, e)
  544. case opcode.OP_UNKNOWN252:
  545. return opcodeInvalid(po, e)
  546. case opcode.OP_PUBKEYHASH:
  547. return opcodeInvalid(po, e)
  548. case opcode.OP_PUBKEY:
  549. return opcodeInvalid(po, e)
  550. case opcode.OP_INVALIDOPCODE:
  551. return opcodeInvalid(po, e)
  552. }
  553. // Should never happen
  554. return opcodeInvalid(po, e)
  555. }
  556. // opcodeOnelineRepls defines opcode names which are replaced when doing a
  557. // one-line disassembly. This is done to match the output of the reference
  558. // implementation while not changing the opcode names in the nicer full
  559. // disassembly.
  560. var opcodeOnelineRepls = map[string]string{
  561. "OP_1NEGATE": "-1",
  562. "OP_0": "0",
  563. "OP_1": "1",
  564. "OP_2": "2",
  565. "OP_3": "3",
  566. "OP_4": "4",
  567. "OP_5": "5",
  568. "OP_6": "6",
  569. "OP_7": "7",
  570. "OP_8": "8",
  571. "OP_9": "9",
  572. "OP_10": "10",
  573. "OP_11": "11",
  574. "OP_12": "12",
  575. "OP_13": "13",
  576. "OP_14": "14",
  577. "OP_15": "15",
  578. "OP_16": "16",
  579. }
  580. // popIsDisabled returns whether or not the opcode is disabled and thus is always
  581. // bad to see in the instruction stream (even if turned off by a conditional).
  582. func popIsDisabled(pop *parsescript.ParsedOpcode) bool {
  583. switch pop.Opcode.Value {
  584. case opcode.OP_CAT:
  585. return true
  586. case opcode.OP_SUBSTR:
  587. return true
  588. case opcode.OP_LEFT:
  589. return true
  590. case opcode.OP_RIGHT:
  591. return true
  592. case opcode.OP_INVERT:
  593. return true
  594. case opcode.OP_AND:
  595. return true
  596. case opcode.OP_OR:
  597. return true
  598. case opcode.OP_XOR:
  599. return true
  600. case opcode.OP_2MUL:
  601. return true
  602. case opcode.OP_2DIV:
  603. return true
  604. case opcode.OP_MUL:
  605. return true
  606. case opcode.OP_DIV:
  607. return true
  608. case opcode.OP_MOD:
  609. return true
  610. case opcode.OP_LSHIFT:
  611. return true
  612. case opcode.OP_RSHIFT:
  613. return true
  614. default:
  615. return false
  616. }
  617. }
  618. // popAlwaysIllegal returns whether or not the opcode is always illegal when passed
  619. // over by the program counter even if in a non-executed branch (it isn't a
  620. // coincidence that they are conditionals).
  621. func popAlwaysIllegal(pop *parsescript.ParsedOpcode) bool {
  622. switch pop.Opcode.Value {
  623. case opcode.OP_VERIF:
  624. return true
  625. default:
  626. return false
  627. }
  628. }
  629. // popIsConditional returns whether or not the opcode is a conditional opcode which
  630. // changes the conditional execution stack when executed.
  631. func popIsConditional(pop *parsescript.ParsedOpcode) bool {
  632. switch pop.Opcode.Value {
  633. case opcode.OP_IF:
  634. return true
  635. case opcode.OP_NOTIF:
  636. return true
  637. case opcode.OP_ELSE:
  638. return true
  639. case opcode.OP_ENDIF:
  640. return true
  641. default:
  642. return false
  643. }
  644. }
  645. // popCheckMinimalDataPush returns whether or not the current data push uses the
  646. // smallest possible opcode to represent it. For example, the value 15 could
  647. // be pushed with OP_DATA_1 15 (among other variations); however, OP_15 is a
  648. // single opcode that represents the same value and is only a single byte versus
  649. // two bytes.
  650. func popCheckMinimalDataPush(pop *parsescript.ParsedOpcode) er.R {
  651. data := pop.Data
  652. dataLen := len(data)
  653. op := pop.Opcode.Value
  654. if dataLen == 0 && op != opcode.OP_0 {
  655. str := fmt.Sprintf("zero length data push is encoded with "+
  656. "opcode %s instead of OP_0", opcode.OpcodeName(pop.Opcode.Value))
  657. return txscripterr.ScriptError(txscripterr.ErrMinimalData, str)
  658. } else if dataLen == 1 && data[0] >= 1 && data[0] <= 16 {
  659. if op != opcode.OP_1+data[0]-1 {
  660. // Should have used OP_1 .. OP_16
  661. str := fmt.Sprintf("data push of the value %d encoded "+
  662. "with opcode %s instead of OP_%d", data[0],
  663. opcode.OpcodeName(pop.Opcode.Value), data[0])
  664. return txscripterr.ScriptError(txscripterr.ErrMinimalData, str)
  665. }
  666. } else if dataLen == 1 && data[0] == 0x81 {
  667. if op != opcode.OP_1NEGATE {
  668. str := fmt.Sprintf("data push of the value -1 encoded "+
  669. "with opcode %s instead of OP_1NEGATE",
  670. opcode.OpcodeName(pop.Opcode.Value))
  671. return txscripterr.ScriptError(txscripterr.ErrMinimalData, str)
  672. }
  673. } else if dataLen <= 75 {
  674. if int(op) != dataLen {
  675. // Should have used a direct push
  676. str := fmt.Sprintf("data push of %d bytes encoded "+
  677. "with opcode %s instead of OP_DATA_%d", dataLen,
  678. opcode.OpcodeName(pop.Opcode.Value), dataLen)
  679. return txscripterr.ScriptError(txscripterr.ErrMinimalData, str)
  680. }
  681. } else if dataLen <= 255 {
  682. if op != opcode.OP_PUSHDATA1 {
  683. str := fmt.Sprintf("data push of %d bytes encoded "+
  684. "with opcode %s instead of OP_PUSHDATA1",
  685. dataLen, opcode.OpcodeName(pop.Opcode.Value))
  686. return txscripterr.ScriptError(txscripterr.ErrMinimalData, str)
  687. }
  688. } else if dataLen <= 65535 {
  689. if op != opcode.OP_PUSHDATA2 {
  690. str := fmt.Sprintf("data push of %d bytes encoded "+
  691. "with opcode %s instead of OP_PUSHDATA2",
  692. dataLen, opcode.OpcodeName(pop.Opcode.Value))
  693. return txscripterr.ScriptError(txscripterr.ErrMinimalData, str)
  694. }
  695. }
  696. return nil
  697. }
  698. // popPrint returns a human-readable string representation of the opcode for use
  699. // in script disassembly.
  700. func popPrint(pop *parsescript.ParsedOpcode, oneline bool) string {
  701. // The reference implementation one-line disassembly replaces opcodes
  702. // which represent values (e.g. OP_0 through OP_16 and OP_1NEGATE)
  703. // with the raw value. However, when not doing a one-line dissassembly,
  704. // we prefer to show the actual opcode names. Thus, only replace the
  705. // opcodes in question when the oneline flag is set.
  706. opcodeName := opcode.OpcodeName(pop.Opcode.Value)
  707. if oneline {
  708. if replName, ok := opcodeOnelineRepls[opcodeName]; ok {
  709. opcodeName = replName
  710. }
  711. // Nothing more to do for non-data push opcodes.
  712. if pop.Opcode.Length == 1 {
  713. return opcodeName
  714. }
  715. return fmt.Sprintf("%x", pop.Data)
  716. }
  717. // Nothing more to do for non-data push opcodes.
  718. if pop.Opcode.Length == 1 {
  719. return opcodeName
  720. }
  721. // Add length for the OP_PUSHDATA# opcodes.
  722. retString := opcodeName
  723. switch pop.Opcode.Length {
  724. case -1:
  725. retString += fmt.Sprintf(" 0x%02x", len(pop.Data))
  726. case -2:
  727. retString += fmt.Sprintf(" 0x%04x", len(pop.Data))
  728. case -4:
  729. retString += fmt.Sprintf(" 0x%08x", len(pop.Data))
  730. }
  731. return fmt.Sprintf("%s 0x%02x", retString, pop.Data)
  732. }
  733. // popBytes returns any data associated with the opcode encoded as it would be in
  734. // a script. This is used for unparsing scripts from parsed opcodes.
  735. func popBytes(pop *parsescript.ParsedOpcode) ([]byte, er.R) {
  736. var retbytes []byte
  737. if pop.Opcode.Length > 0 {
  738. retbytes = make([]byte, 1, pop.Opcode.Length)
  739. } else {
  740. retbytes = make([]byte, 1, 1+len(pop.Data)-
  741. pop.Opcode.Length)
  742. }
  743. retbytes[0] = pop.Opcode.Value
  744. if pop.Opcode.Length == 1 {
  745. if len(pop.Data) != 0 {
  746. str := fmt.Sprintf("internal consistency error - "+
  747. "parsed opcode %s has data length %d when %d "+
  748. "was expected", opcode.OpcodeName(pop.Opcode.Value), len(pop.Data),
  749. 0)
  750. return nil, txscripterr.ScriptError(txscripterr.ErrInternal, str)
  751. }
  752. return retbytes, nil
  753. }
  754. nbytes := pop.Opcode.Length
  755. if pop.Opcode.Length < 0 {
  756. l := len(pop.Data)
  757. // tempting just to hardcode to avoid the complexity here.
  758. switch pop.Opcode.Length {
  759. case -1:
  760. retbytes = append(retbytes, byte(l))
  761. nbytes = int(retbytes[1]) + len(retbytes)
  762. case -2:
  763. retbytes = append(retbytes, byte(l&0xff),
  764. byte(l>>8&0xff))
  765. nbytes = int(binary.LittleEndian.Uint16(retbytes[1:])) +
  766. len(retbytes)
  767. case -4:
  768. retbytes = append(retbytes, byte(l&0xff),
  769. byte((l>>8)&0xff), byte((l>>16)&0xff),
  770. byte((l>>24)&0xff))
  771. nbytes = int(binary.LittleEndian.Uint32(retbytes[1:])) +
  772. len(retbytes)
  773. }
  774. }
  775. retbytes = append(retbytes, pop.Data...)
  776. if len(retbytes) != nbytes {
  777. str := fmt.Sprintf("internal consistency error - "+
  778. "parsed opcode %s has data length %d when %d was "+
  779. "expected", opcode.OpcodeName(pop.Opcode.Value), len(retbytes), nbytes)
  780. return nil, txscripterr.ScriptError(txscripterr.ErrInternal, str)
  781. }
  782. return retbytes, nil
  783. }
  784. // *******************************************
  785. // Opcode implementation functions start here.
  786. // *******************************************
  787. // opcodeDisabled is a common handler for disabled opcodes. It returns an
  788. // appropriate error indicating the opcode is disabled. While it would
  789. // ordinarily make more sense to detect if the script contains any disabled
  790. // opcodes before executing in an initial parse step, the consensus rules
  791. // dictate the script doesn't fail until the program counter passes over a
  792. // disabled opcode (even when they appear in a branch that is not executed).
  793. func opcodeDisabled(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  794. str := fmt.Sprintf("attempt to execute disabled opcode %s",
  795. opcode.OpcodeName(op.Opcode.Value))
  796. return txscripterr.ScriptError(txscripterr.ErrDisabledOpcode, str)
  797. }
  798. // opcodeReserved is a common handler for all reserved opcodes. It returns an
  799. // appropriate error indicating the opcode is reserved.
  800. func opcodeReserved(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  801. str := fmt.Sprintf("attempt to execute reserved opcode %s",
  802. opcode.OpcodeName(op.Opcode.Value))
  803. return txscripterr.ScriptError(txscripterr.ErrReservedOpcode, str)
  804. }
  805. // opcodeInvalid is a common handler for all invalid opcodes. It returns an
  806. // appropriate error indicating the opcode is invalid.
  807. func opcodeInvalid(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  808. str := fmt.Sprintf("attempt to execute invalid opcode %s",
  809. opcode.OpcodeName(op.Opcode.Value))
  810. return txscripterr.ScriptError(txscripterr.ErrReservedOpcode, str)
  811. }
  812. // opcodeFalse pushes an empty array to the data stack to represent false. Note
  813. // that 0, when encoded as a number according to the numeric encoding consensus
  814. // rules, is an empty array.
  815. func opcodeFalse(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  816. vm.dstack.PushByteArray(nil)
  817. return nil
  818. }
  819. // opcodePushData is a common handler for the vast majority of opcodes that push
  820. // raw data (bytes) to the data stack.
  821. func opcodePushData(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  822. vm.dstack.PushByteArray(op.Data)
  823. return nil
  824. }
  825. // opcode1Negate pushes -1, encoded as a number, to the data stack.
  826. func opcode1Negate(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  827. vm.dstack.PushInt(scriptnum.ScriptNum(-1))
  828. return nil
  829. }
  830. // opcodeN is a common handler for the small integer data push opcodes. It
  831. // pushes the numeric value the opcode represents (which will be from 1 to 16)
  832. // onto the data stack.
  833. func opcodeN(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  834. // The opcodes are all defined consecutively, so the numeric value is
  835. // the difference.
  836. vm.dstack.PushInt(scriptnum.ScriptNum((op.Opcode.Value - (opcode.OP_1 - 1))))
  837. return nil
  838. }
  839. // opcodeNop is a common handler for the NOP family of opcodes. As the name
  840. // implies it generally does nothing, however, it will return an error when
  841. // the flag to discourage use of NOPs is set for select opcodes.
  842. func opcodeNop(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  843. switch op.Opcode.Value {
  844. case opcode.OP_NOP1, opcode.OP_NOP4, opcode.OP_NOP5,
  845. opcode.OP_NOP6, opcode.OP_NOP7, opcode.OP_NOP8, opcode.OP_NOP9, opcode.OP_NOP10:
  846. if vm.hasFlag(ScriptDiscourageUpgradableNops) {
  847. str := fmt.Sprintf("OP_NOP%d reserved for soft-fork "+
  848. "upgrades", op.Opcode.Value-(opcode.OP_NOP1-1))
  849. return txscripterr.ScriptError(txscripterr.ErrDiscourageUpgradableNOPs, str)
  850. }
  851. }
  852. return nil
  853. }
  854. // popIfBool enforces the "minimal if" policy during script execution if the
  855. // particular flag is set. If so, in order to eliminate an additional source
  856. // of nuisance malleability, post-segwit for version 0 witness programs, we now
  857. // require the following: for OP_IF and OP_NOT_IF, the top stack item MUST
  858. // either be an empty byte slice, or [0x01]. Otherwise, the item at the top of
  859. // the stack will be popped and interpreted as a boolean.
  860. func popIfBool(vm *Engine) (bool, er.R) {
  861. // When not in witness execution mode, not executing a v0 witness
  862. // program, or the minimal if flag isn't set pop the top stack item as
  863. // a normal bool.
  864. if !vm.isWitnessVersionActive(0) || !vm.hasFlag(ScriptVerifyMinimalIf) {
  865. return vm.dstack.PopBool()
  866. }
  867. // At this point, a v0 witness program is being executed and the minimal
  868. // if flag is set, so enforce additional constraints on the top stack
  869. // item.
  870. so, err := vm.dstack.PopByteArray()
  871. if err != nil {
  872. return false, err
  873. }
  874. // The top element MUST have a length of at least one.
  875. if len(so) > 1 {
  876. str := fmt.Sprintf("minimal if is active, top element MUST "+
  877. "have a length of at least, instead length is %v",
  878. len(so))
  879. return false, txscripterr.ScriptError(txscripterr.ErrMinimalIf, str)
  880. }
  881. // Additionally, if the length is one, then the value MUST be 0x01.
  882. if len(so) == 1 && so[0] != 0x01 {
  883. str := fmt.Sprintf("minimal if is active, top stack item MUST "+
  884. "be an empty byte array or 0x01, is instead: %v",
  885. so[0])
  886. return false, txscripterr.ScriptError(txscripterr.ErrMinimalIf, str)
  887. }
  888. return asBool(so), nil
  889. }
  890. // opcodeIf treats the top item on the data stack as a boolean and removes it.
  891. //
  892. // An appropriate entry is added to the conditional stack depending on whether
  893. // the boolean is true and whether this if is on an executing branch in order
  894. // to allow proper execution of further opcodes depending on the conditional
  895. // logic. When the boolean is true, the first branch will be executed (unless
  896. // this opcode is nested in a non-executed branch).
  897. //
  898. // <expression> if [statements] [else [statements]] endif
  899. //
  900. // Note that, unlike for all non-conditional opcodes, this is executed even when
  901. // it is on a non-executing branch so proper nesting is maintained.
  902. //
  903. // Data stack transformation: [... bool] -> [...]
  904. // Conditional stack transformation: [...] -> [... OpCondValue]
  905. func opcodeIf(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  906. condVal := OpCondFalse
  907. if vm.isBranchExecuting() {
  908. ok, err := popIfBool(vm)
  909. if err != nil {
  910. return err
  911. }
  912. if ok {
  913. condVal = OpCondTrue
  914. }
  915. } else {
  916. condVal = OpCondSkip
  917. }
  918. vm.condStack = append(vm.condStack, condVal)
  919. return nil
  920. }
  921. // opcodeNotIf treats the top item on the data stack as a boolean and removes
  922. // it.
  923. //
  924. // An appropriate entry is added to the conditional stack depending on whether
  925. // the boolean is true and whether this if is on an executing branch in order
  926. // to allow proper execution of further opcodes depending on the conditional
  927. // logic. When the boolean is false, the first branch will be executed (unless
  928. // this opcode is nested in a non-executed branch).
  929. //
  930. // <expression> notif [statements] [else [statements]] endif
  931. //
  932. // Note that, unlike for all non-conditional opcodes, this is executed even when
  933. // it is on a non-executing branch so proper nesting is maintained.
  934. //
  935. // Data stack transformation: [... bool] -> [...]
  936. // Conditional stack transformation: [...] -> [... OpCondValue]
  937. func opcodeNotIf(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  938. condVal := OpCondFalse
  939. if vm.isBranchExecuting() {
  940. ok, err := popIfBool(vm)
  941. if err != nil {
  942. return err
  943. }
  944. if !ok {
  945. condVal = OpCondTrue
  946. }
  947. } else {
  948. condVal = OpCondSkip
  949. }
  950. vm.condStack = append(vm.condStack, condVal)
  951. return nil
  952. }
  953. // opcodeElse inverts conditional execution for other half of if/else/endif.
  954. //
  955. // An error is returned if there has not already been a matching OP_IF.
  956. //
  957. // Conditional stack transformation: [... OpCondValue] -> [... !OpCondValue]
  958. func opcodeElse(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  959. if len(vm.condStack) == 0 {
  960. str := fmt.Sprintf("encountered opcode %s with no matching "+
  961. "opcode to begin conditional execution", opcode.OpcodeName(op.Opcode.Value))
  962. return txscripterr.ScriptError(txscripterr.ErrUnbalancedConditional, str)
  963. }
  964. conditionalIdx := len(vm.condStack) - 1
  965. switch vm.condStack[conditionalIdx] {
  966. case OpCondTrue:
  967. vm.condStack[conditionalIdx] = OpCondFalse
  968. case OpCondFalse:
  969. vm.condStack[conditionalIdx] = OpCondTrue
  970. case OpCondSkip:
  971. // Value doesn't change in skip since it indicates this opcode
  972. // is nested in a non-executed branch.
  973. }
  974. return nil
  975. }
  976. // opcodeEndif terminates a conditional block, removing the value from the
  977. // conditional execution stack.
  978. //
  979. // An error is returned if there has not already been a matching OP_IF.
  980. //
  981. // Conditional stack transformation: [... OpCondValue] -> [...]
  982. func opcodeEndif(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  983. if len(vm.condStack) == 0 {
  984. str := fmt.Sprintf("encountered opcode %s with no matching "+
  985. "opcode to begin conditional execution", opcode.OpcodeName(op.Opcode.Value))
  986. return txscripterr.ScriptError(txscripterr.ErrUnbalancedConditional, str)
  987. }
  988. vm.condStack = vm.condStack[:len(vm.condStack)-1]
  989. return nil
  990. }
  991. // abstractVerify examines the top item on the data stack as a boolean value and
  992. // verifies it evaluates to true. An error is returned either when there is no
  993. // item on the stack or when that item evaluates to false. In the latter case
  994. // where the verification fails specifically due to the top item evaluating
  995. // to false, the returned error will use the passed error code.
  996. func abstractVerify(op *parsescript.ParsedOpcode, vm *Engine, c *er.ErrorCode) er.R {
  997. verified, err := vm.dstack.PopBool()
  998. if err != nil {
  999. return err
  1000. }
  1001. if !verified {
  1002. str := fmt.Sprintf("%s failed", opcode.OpcodeName(op.Opcode.Value))
  1003. return txscripterr.ScriptError(c, str)
  1004. }
  1005. return nil
  1006. }
  1007. // opcodeVerify examines the top item on the data stack as a boolean value and
  1008. // verifies it evaluates to true. An error is returned if it does not.
  1009. func opcodeVerify(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1010. return abstractVerify(op, vm, txscripterr.ErrVerify)
  1011. }
  1012. // opcodeReturn returns an appropriate error since it is always an error to
  1013. // return early from a script.
  1014. func opcodeReturn(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1015. return txscripterr.ScriptError(txscripterr.ErrEarlyReturn, "script returned early")
  1016. }
  1017. // verifyLockTime is a helper function used to validate locktimes.
  1018. func verifyLockTime(txLockTime, threshold, lockTime int64) er.R {
  1019. // The lockTimes in both the script and transaction must be of the same
  1020. // type.
  1021. if !((txLockTime < threshold && lockTime < threshold) ||
  1022. (txLockTime >= threshold && lockTime >= threshold)) {
  1023. str := fmt.Sprintf("mismatched locktime types -- tx locktime "+
  1024. "%d, stack locktime %d", txLockTime, lockTime)
  1025. return txscripterr.ScriptError(txscripterr.ErrUnsatisfiedLockTime, str)
  1026. }
  1027. if lockTime > txLockTime {
  1028. str := fmt.Sprintf("locktime requirement not satisfied -- "+
  1029. "locktime is greater than the transaction locktime: "+
  1030. "%d > %d", lockTime, txLockTime)
  1031. return txscripterr.ScriptError(txscripterr.ErrUnsatisfiedLockTime, str)
  1032. }
  1033. return nil
  1034. }
  1035. // opcodeCheckLockTimeVerify compares the top item on the data stack to the
  1036. // LockTime field of the transaction containing the script signature
  1037. // validating if the transaction outputs are spendable yet. If flag
  1038. // ScriptVerifyCheckLockTimeVerify is not set, the code continues as if OP_NOP2
  1039. // were executed.
  1040. func opcodeCheckLockTimeVerify(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1041. // If the ScriptVerifyCheckLockTimeVerify script flag is not set, treat
  1042. // opcode as OP_NOP2 instead.
  1043. if !vm.hasFlag(ScriptVerifyCheckLockTimeVerify) {
  1044. if vm.hasFlag(ScriptDiscourageUpgradableNops) {
  1045. return txscripterr.ScriptError(txscripterr.ErrDiscourageUpgradableNOPs,
  1046. "OP_NOP2 reserved for soft-fork upgrades")
  1047. }
  1048. return nil
  1049. }
  1050. // The current transaction locktime is a uint32 resulting in a maximum
  1051. // locktime of 2^32-1 (the year 2106). However, scriptNums are signed
  1052. // and therefore a standard 4-byte scriptNum would only support up to a
  1053. // maximum of 2^31-1 (the year 2038). Thus, a 5-byte scriptNum is used
  1054. // here since it will support up to 2^39-1 which allows dates beyond the
  1055. // current locktime limit.
  1056. //
  1057. // PeekByteArray is used here instead of PeekInt because we do not want
  1058. // to be limited to a 4-byte integer for reasons specified above.
  1059. so, err := vm.dstack.PeekByteArray(0)
  1060. if err != nil {
  1061. return err
  1062. }
  1063. lockTime, err := scriptnum.MakeScriptNum(so, vm.dstack.verifyMinimalData, 5)
  1064. if err != nil {
  1065. return err
  1066. }
  1067. // In the rare event that the argument needs to be < 0 due to some
  1068. // arithmetic being done first, you can always use
  1069. // 0 OP_MAX OP_CHECKLOCKTIMEVERIFY.
  1070. if lockTime < 0 {
  1071. str := fmt.Sprintf("negative lock time: %d", lockTime)
  1072. return txscripterr.ScriptError(txscripterr.ErrNegativeLockTime, str)
  1073. }
  1074. // The lock time field of a transaction is either a block height at
  1075. // which the transaction is finalized or a timestamp depending on if the
  1076. // value is before the txscript.LockTimeThreshold. When it is under the
  1077. // threshold it is a block height.
  1078. err = verifyLockTime(int64(vm.tx.LockTime), params.LockTimeThreshold,
  1079. int64(lockTime))
  1080. if err != nil {
  1081. return err
  1082. }
  1083. // The lock time feature can also be disabled, thereby bypassing
  1084. // OP_CHECKLOCKTIMEVERIFY, if every transaction input has been finalized by
  1085. // setting its sequence to the maximum value (constants.MaxTxInSequenceNum). This
  1086. // condition would result in the transaction being allowed into the blockchain
  1087. // making the opcode ineffective.
  1088. //
  1089. // This condition is prevented by enforcing that the input being used by
  1090. // the opcode is unlocked (its sequence number is less than the max
  1091. // value). This is sufficient to prove correctness without having to
  1092. // check every input.
  1093. //
  1094. // NOTE: This implies that even if the transaction is not finalized due to
  1095. // another input being unlocked, the opcode execution will still fail when the
  1096. // input being used by the opcode is locked.
  1097. if vm.tx.TxIn[vm.txIdx].Sequence == constants.MaxTxInSequenceNum {
  1098. return txscripterr.ScriptError(txscripterr.ErrUnsatisfiedLockTime,
  1099. "transaction input is finalized")
  1100. }
  1101. return nil
  1102. }
  1103. // opcodeCheckSequenceVerify compares the top item on the data stack to the
  1104. // LockTime field of the transaction containing the script signature
  1105. // validating if the transaction outputs are spendable yet. If flag
  1106. // ScriptVerifyCheckSequenceVerify is not set, the code continues as if OP_NOP3
  1107. // were executed.
  1108. func opcodeCheckSequenceVerify(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1109. // If the ScriptVerifyCheckSequenceVerify script flag is not set, treat
  1110. // opcode as OP_NOP3 instead.
  1111. if !vm.hasFlag(ScriptVerifyCheckSequenceVerify) {
  1112. if vm.hasFlag(ScriptDiscourageUpgradableNops) {
  1113. return txscripterr.ScriptError(txscripterr.ErrDiscourageUpgradableNOPs,
  1114. "OP_NOP3 reserved for soft-fork upgrades")
  1115. }
  1116. return nil
  1117. }
  1118. // The current transaction sequence is a uint32 resulting in a maximum
  1119. // sequence of 2^32-1. However, scriptNums are signed and therefore a
  1120. // standard 4-byte scriptNum would only support up to a maximum of
  1121. // 2^31-1. Thus, a 5-byte scriptNum is used here since it will support
  1122. // up to 2^39-1 which allows sequences beyond the current sequence
  1123. // limit.
  1124. //
  1125. // PeekByteArray is used here instead of PeekInt because we do not want
  1126. // to be limited to a 4-byte integer for reasons specified above.
  1127. so, err := vm.dstack.PeekByteArray(0)
  1128. if err != nil {
  1129. return err
  1130. }
  1131. stackSequence, err := scriptnum.MakeScriptNum(so, vm.dstack.verifyMinimalData, 5)
  1132. if err != nil {
  1133. return err
  1134. }
  1135. // In the rare event that the argument needs to be < 0 due to some
  1136. // arithmetic being done first, you can always use
  1137. // 0 OP_MAX OP_CHECKSEQUENCEVERIFY.
  1138. if stackSequence < 0 {
  1139. str := fmt.Sprintf("negative sequence: %d", stackSequence)
  1140. return txscripterr.ScriptError(txscripterr.ErrNegativeLockTime, str)
  1141. }
  1142. sequence := int64(stackSequence)
  1143. // To provide for future soft-fork extensibility, if the
  1144. // operand has the disabled lock-time flag set,
  1145. // CHECKSEQUENCEVERIFY behaves as a NOP.
  1146. if sequence&int64(constants.SequenceLockTimeDisabled) != 0 {
  1147. return nil
  1148. }
  1149. // Transaction version numbers not high enough to trigger CSV rules must
  1150. // fail.
  1151. if vm.tx.Version < 2 {
  1152. str := fmt.Sprintf("invalid transaction version: %d",
  1153. vm.tx.Version)
  1154. return txscripterr.ScriptError(txscripterr.ErrUnsatisfiedLockTime, str)
  1155. }
  1156. // Sequence numbers with their most significant bit set are not
  1157. // consensus constrained. Testing that the transaction's sequence
  1158. // number does not have this bit set prevents using this property
  1159. // to get around a CHECKSEQUENCEVERIFY check.
  1160. txSequence := int64(vm.tx.TxIn[vm.txIdx].Sequence)
  1161. if txSequence&int64(constants.SequenceLockTimeDisabled) != 0 {
  1162. str := fmt.Sprintf("transaction sequence has sequence "+
  1163. "locktime disabled bit set: 0x%x", txSequence)
  1164. return txscripterr.ScriptError(txscripterr.ErrUnsatisfiedLockTime, str)
  1165. }
  1166. // Mask off non-consensus bits before doing comparisons.
  1167. lockTimeMask := int64(constants.SequenceLockTimeIsSeconds |
  1168. constants.SequenceLockTimeMask)
  1169. return verifyLockTime(txSequence&lockTimeMask,
  1170. constants.SequenceLockTimeIsSeconds, sequence&lockTimeMask)
  1171. }
  1172. // opcodeToAltStack removes the top item from the main data stack and pushes it
  1173. // onto the alternate data stack.
  1174. //
  1175. // Main data stack transformation: [... x1 x2 x3] -> [... x1 x2]
  1176. // Alt data stack transformation: [... y1 y2 y3] -> [... y1 y2 y3 x3]
  1177. func opcodeToAltStack(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1178. so, err := vm.dstack.PopByteArray()
  1179. if err != nil {
  1180. return err
  1181. }
  1182. vm.astack.PushByteArray(so)
  1183. return nil
  1184. }
  1185. // opcodeFromAltStack removes the top item from the alternate data stack and
  1186. // pushes it onto the main data stack.
  1187. //
  1188. // Main data stack transformation: [... x1 x2 x3] -> [... x1 x2 x3 y3]
  1189. // Alt data stack transformation: [... y1 y2 y3] -> [... y1 y2]
  1190. func opcodeFromAltStack(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1191. so, err := vm.astack.PopByteArray()
  1192. if err != nil {
  1193. return err
  1194. }
  1195. vm.dstack.PushByteArray(so)
  1196. return nil
  1197. }
  1198. // opcode2Drop removes the top 2 items from the data stack.
  1199. //
  1200. // Stack transformation: [... x1 x2 x3] -> [... x1]
  1201. func opcode2Drop(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1202. return vm.dstack.DropN(2)
  1203. }
  1204. // opcode2Dup duplicates the top 2 items on the data stack.
  1205. //
  1206. // Stack transformation: [... x1 x2 x3] -> [... x1 x2 x3 x2 x3]
  1207. func opcode2Dup(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1208. return vm.dstack.DupN(2)
  1209. }
  1210. // opcode3Dup duplicates the top 3 items on the data stack.
  1211. //
  1212. // Stack transformation: [... x1 x2 x3] -> [... x1 x2 x3 x1 x2 x3]
  1213. func opcode3Dup(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1214. return vm.dstack.DupN(3)
  1215. }
  1216. // opcode2Over duplicates the 2 items before the top 2 items on the data stack.
  1217. //
  1218. // Stack transformation: [... x1 x2 x3 x4] -> [... x1 x2 x3 x4 x1 x2]
  1219. func opcode2Over(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1220. return vm.dstack.OverN(2)
  1221. }
  1222. // opcode2Rot rotates the top 6 items on the data stack to the left twice.
  1223. //
  1224. // Stack transformation: [... x1 x2 x3 x4 x5 x6] -> [... x3 x4 x5 x6 x1 x2]
  1225. func opcode2Rot(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1226. return vm.dstack.RotN(2)
  1227. }
  1228. // opcode2Swap swaps the top 2 items on the data stack with the 2 that come
  1229. // before them.
  1230. //
  1231. // Stack transformation: [... x1 x2 x3 x4] -> [... x3 x4 x1 x2]
  1232. func opcode2Swap(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1233. return vm.dstack.SwapN(2)
  1234. }
  1235. // opcodeIfDup duplicates the top item of the stack if it is not zero.
  1236. //
  1237. // Stack transformation (x1==0): [... x1] -> [... x1]
  1238. // Stack transformation (x1!=0): [... x1] -> [... x1 x1]
  1239. func opcodeIfDup(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1240. so, err := vm.dstack.PeekByteArray(0)
  1241. if err != nil {
  1242. return err
  1243. }
  1244. // Push copy of data iff it isn't zero
  1245. if asBool(so) {
  1246. vm.dstack.PushByteArray(so)
  1247. }
  1248. return nil
  1249. }
  1250. // opcodeDepth pushes the depth of the data stack prior to executing this
  1251. // opcode, encoded as a number, onto the data stack.
  1252. //
  1253. // Stack transformation: [...] -> [... <num of items on the stack>]
  1254. // Example with 2 items: [x1 x2] -> [x1 x2 2]
  1255. // Example with 3 items: [x1 x2 x3] -> [x1 x2 x3 3]
  1256. func opcodeDepth(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1257. vm.dstack.PushInt(scriptnum.ScriptNum(vm.dstack.Depth()))
  1258. return nil
  1259. }
  1260. // opcodeDrop removes the top item from the data stack.
  1261. //
  1262. // Stack transformation: [... x1 x2 x3] -> [... x1 x2]
  1263. func opcodeDrop(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1264. return vm.dstack.DropN(1)
  1265. }
  1266. // opcodeDup duplicates the top item on the data stack.
  1267. //
  1268. // Stack transformation: [... x1 x2 x3] -> [... x1 x2 x3 x3]
  1269. func opcodeDup(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1270. return vm.dstack.DupN(1)
  1271. }
  1272. // opcodeNip removes the item before the top item on the data stack.
  1273. //
  1274. // Stack transformation: [... x1 x2 x3] -> [... x1 x3]
  1275. func opcodeNip(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1276. return vm.dstack.NipN(1)
  1277. }
  1278. // opcodeOver duplicates the item before the top item on the data stack.
  1279. //
  1280. // Stack transformation: [... x1 x2 x3] -> [... x1 x2 x3 x2]
  1281. func opcodeOver(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1282. return vm.dstack.OverN(1)
  1283. }
  1284. // opcodePick treats the top item on the data stack as an integer and duplicates
  1285. // the item on the stack that number of items back to the top.
  1286. //
  1287. // Stack transformation: [xn ... x2 x1 x0 n] -> [xn ... x2 x1 x0 xn]
  1288. // Example with n=1: [x2 x1 x0 1] -> [x2 x1 x0 x1]
  1289. // Example with n=2: [x2 x1 x0 2] -> [x2 x1 x0 x2]
  1290. func opcodePick(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1291. val, err := vm.dstack.PopInt()
  1292. if err != nil {
  1293. return err
  1294. }
  1295. return vm.dstack.PickN(val.Int32())
  1296. }
  1297. // opcodeRoll treats the top item on the data stack as an integer and moves
  1298. // the item on the stack that number of items back to the top.
  1299. //
  1300. // Stack transformation: [xn ... x2 x1 x0 n] -> [... x2 x1 x0 xn]
  1301. // Example with n=1: [x2 x1 x0 1] -> [x2 x0 x1]
  1302. // Example with n=2: [x2 x1 x0 2] -> [x1 x0 x2]
  1303. func opcodeRoll(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1304. val, err := vm.dstack.PopInt()
  1305. if err != nil {
  1306. return err
  1307. }
  1308. return vm.dstack.RollN(val.Int32())
  1309. }
  1310. // opcodeRot rotates the top 3 items on the data stack to the left.
  1311. //
  1312. // Stack transformation: [... x1 x2 x3] -> [... x2 x3 x1]
  1313. func opcodeRot(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1314. return vm.dstack.RotN(1)
  1315. }
  1316. // opcodeSwap swaps the top two items on the stack.
  1317. //
  1318. // Stack transformation: [... x1 x2] -> [... x2 x1]
  1319. func opcodeSwap(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1320. return vm.dstack.SwapN(1)
  1321. }
  1322. // opcodeTuck inserts a duplicate of the top item of the data stack before the
  1323. // second-to-top item.
  1324. //
  1325. // Stack transformation: [... x1 x2] -> [... x2 x1 x2]
  1326. func opcodeTuck(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1327. return vm.dstack.Tuck()
  1328. }
  1329. // opcodeSize pushes the size of the top item of the data stack onto the data
  1330. // stack.
  1331. //
  1332. // Stack transformation: [... x1] -> [... x1 len(x1)]
  1333. func opcodeSize(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1334. so, err := vm.dstack.PeekByteArray(0)
  1335. if err != nil {
  1336. return err
  1337. }
  1338. vm.dstack.PushInt(scriptnum.ScriptNum(len(so)))
  1339. return nil
  1340. }
  1341. // opcodeEqual removes the top 2 items of the data stack, compares them as raw
  1342. // bytes, and pushes the result, encoded as a boolean, back to the stack.
  1343. //
  1344. // Stack transformation: [... x1 x2] -> [... bool]
  1345. func opcodeEqual(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1346. a, err := vm.dstack.PopByteArray()
  1347. if err != nil {
  1348. return err
  1349. }
  1350. b, err := vm.dstack.PopByteArray()
  1351. if err != nil {
  1352. return err
  1353. }
  1354. vm.dstack.PushBool(bytes.Equal(a, b))
  1355. return nil
  1356. }
  1357. // opcodeEqualVerify is a combination of opcodeEqual and opcodeVerify.
  1358. // Specifically, it removes the top 2 items of the data stack, compares them,
  1359. // and pushes the result, encoded as a boolean, back to the stack. Then, it
  1360. // examines the top item on the data stack as a boolean value and verifies it
  1361. // evaluates to true. An error is returned if it does not.
  1362. //
  1363. // Stack transformation: [... x1 x2] -> [... bool] -> [...]
  1364. func opcodeEqualVerify(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1365. err := opcodeEqual(op, vm)
  1366. if err == nil {
  1367. err = abstractVerify(op, vm, txscripterr.ErrEqualVerify)
  1368. }
  1369. return err
  1370. }
  1371. // opcode1Add treats the top item on the data stack as an integer and replaces
  1372. // it with its incremented value (plus 1).
  1373. //
  1374. // Stack transformation: [... x1 x2] -> [... x1 x2+1]
  1375. func opcode1Add(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1376. m, err := vm.dstack.PopInt()
  1377. if err != nil {
  1378. return err
  1379. }
  1380. vm.dstack.PushInt(m + 1)
  1381. return nil
  1382. }
  1383. // opcode1Sub treats the top item on the data stack as an integer and replaces
  1384. // it with its decremented value (minus 1).
  1385. //
  1386. // Stack transformation: [... x1 x2] -> [... x1 x2-1]
  1387. func opcode1Sub(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1388. m, err := vm.dstack.PopInt()
  1389. if err != nil {
  1390. return err
  1391. }
  1392. vm.dstack.PushInt(m - 1)
  1393. return nil
  1394. }
  1395. // opcodeNegate treats the top item on the data stack as an integer and replaces
  1396. // it with its negation.
  1397. //
  1398. // Stack transformation: [... x1 x2] -> [... x1 -x2]
  1399. func opcodeNegate(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1400. m, err := vm.dstack.PopInt()
  1401. if err != nil {
  1402. return err
  1403. }
  1404. vm.dstack.PushInt(-m)
  1405. return nil
  1406. }
  1407. // opcodeAbs treats the top item on the data stack as an integer and replaces it
  1408. // it with its absolute value.
  1409. //
  1410. // Stack transformation: [... x1 x2] -> [... x1 abs(x2)]
  1411. func opcodeAbs(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1412. m, err := vm.dstack.PopInt()
  1413. if err != nil {
  1414. return err
  1415. }
  1416. if m < 0 {
  1417. m = -m
  1418. }
  1419. vm.dstack.PushInt(m)
  1420. return nil
  1421. }
  1422. // opcodeNot treats the top item on the data stack as an integer and replaces
  1423. // it with its "inverted" value (0 becomes 1, non-zero becomes 0).
  1424. //
  1425. // NOTE: While it would probably make more sense to treat the top item as a
  1426. // boolean, and push the opposite, which is really what the intention of this
  1427. // opcode is, it is extremely important that is not done because integers are
  1428. // interpreted differently than booleans and the consensus rules for this opcode
  1429. // dictate the item is interpreted as an integer.
  1430. //
  1431. // Stack transformation (x2==0): [... x1 0] -> [... x1 1]
  1432. // Stack transformation (x2!=0): [... x1 1] -> [... x1 0]
  1433. // Stack transformation (x2!=0): [... x1 17] -> [... x1 0]
  1434. func opcodeNot(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1435. m, err := vm.dstack.PopInt()
  1436. if err != nil {
  1437. return err
  1438. }
  1439. if m == 0 {
  1440. vm.dstack.PushInt(scriptnum.ScriptNum(1))
  1441. } else {
  1442. vm.dstack.PushInt(scriptnum.ScriptNum(0))
  1443. }
  1444. return nil
  1445. }
  1446. // opcode0NotEqual treats the top item on the data stack as an integer and
  1447. // replaces it with either a 0 if it is zero, or a 1 if it is not zero.
  1448. //
  1449. // Stack transformation (x2==0): [... x1 0] -> [... x1 0]
  1450. // Stack transformation (x2!=0): [... x1 1] -> [... x1 1]
  1451. // Stack transformation (x2!=0): [... x1 17] -> [... x1 1]
  1452. func opcode0NotEqual(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1453. m, err := vm.dstack.PopInt()
  1454. if err != nil {
  1455. return err
  1456. }
  1457. if m != 0 {
  1458. m = 1
  1459. }
  1460. vm.dstack.PushInt(m)
  1461. return nil
  1462. }
  1463. // opcodeAdd treats the top two items on the data stack as integers and replaces
  1464. // them with their sum.
  1465. //
  1466. // Stack transformation: [... x1 x2] -> [... x1+x2]
  1467. func opcodeAdd(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1468. v0, err := vm.dstack.PopInt()
  1469. if err != nil {
  1470. return err
  1471. }
  1472. v1, err := vm.dstack.PopInt()
  1473. if err != nil {
  1474. return err
  1475. }
  1476. vm.dstack.PushInt(v0 + v1)
  1477. return nil
  1478. }
  1479. // opcodeSub treats the top two items on the data stack as integers and replaces
  1480. // them with the result of subtracting the top entry from the second-to-top
  1481. // entry.
  1482. //
  1483. // Stack transformation: [... x1 x2] -> [... x1-x2]
  1484. func opcodeSub(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1485. v0, err := vm.dstack.PopInt()
  1486. if err != nil {
  1487. return err
  1488. }
  1489. v1, err := vm.dstack.PopInt()
  1490. if err != nil {
  1491. return err
  1492. }
  1493. vm.dstack.PushInt(v1 - v0)
  1494. return nil
  1495. }
  1496. // opcodeBoolAnd treats the top two items on the data stack as integers. When
  1497. // both of them are not zero, they are replaced with a 1, otherwise a 0.
  1498. //
  1499. // Stack transformation (x1==0, x2==0): [... 0 0] -> [... 0]
  1500. // Stack transformation (x1!=0, x2==0): [... 5 0] -> [... 0]
  1501. // Stack transformation (x1==0, x2!=0): [... 0 7] -> [... 0]
  1502. // Stack transformation (x1!=0, x2!=0): [... 4 8] -> [... 1]
  1503. func opcodeBoolAnd(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1504. v0, err := vm.dstack.PopInt()
  1505. if err != nil {
  1506. return err
  1507. }
  1508. v1, err := vm.dstack.PopInt()
  1509. if err != nil {
  1510. return err
  1511. }
  1512. if v0 != 0 && v1 != 0 {
  1513. vm.dstack.PushInt(scriptnum.ScriptNum(1))
  1514. } else {
  1515. vm.dstack.PushInt(scriptnum.ScriptNum(0))
  1516. }
  1517. return nil
  1518. }
  1519. // opcodeBoolOr treats the top two items on the data stack as integers. When
  1520. // either of them are not zero, they are replaced with a 1, otherwise a 0.
  1521. //
  1522. // Stack transformation (x1==0, x2==0): [... 0 0] -> [... 0]
  1523. // Stack transformation (x1!=0, x2==0): [... 5 0] -> [... 1]
  1524. // Stack transformation (x1==0, x2!=0): [... 0 7] -> [... 1]
  1525. // Stack transformation (x1!=0, x2!=0): [... 4 8] -> [... 1]
  1526. func opcodeBoolOr(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1527. v0, err := vm.dstack.PopInt()
  1528. if err != nil {
  1529. return err
  1530. }
  1531. v1, err := vm.dstack.PopInt()
  1532. if err != nil {
  1533. return err
  1534. }
  1535. if v0 != 0 || v1 != 0 {
  1536. vm.dstack.PushInt(scriptnum.ScriptNum(1))
  1537. } else {
  1538. vm.dstack.PushInt(scriptnum.ScriptNum(0))
  1539. }
  1540. return nil
  1541. }
  1542. // opcodeNumEqual treats the top two items on the data stack as integers. When
  1543. // they are equal, they are replaced with a 1, otherwise a 0.
  1544. //
  1545. // Stack transformation (x1==x2): [... 5 5] -> [... 1]
  1546. // Stack transformation (x1!=x2): [... 5 7] -> [... 0]
  1547. func opcodeNumEqual(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1548. v0, err := vm.dstack.PopInt()
  1549. if err != nil {
  1550. return err
  1551. }
  1552. v1, err := vm.dstack.PopInt()
  1553. if err != nil {
  1554. return err
  1555. }
  1556. if v0 == v1 {
  1557. vm.dstack.PushInt(scriptnum.ScriptNum(1))
  1558. } else {
  1559. vm.dstack.PushInt(scriptnum.ScriptNum(0))
  1560. }
  1561. return nil
  1562. }
  1563. // opcodeNumEqualVerify is a combination of opcodeNumEqual and opcodeVerify.
  1564. //
  1565. // Specifically, treats the top two items on the data stack as integers. When
  1566. // they are equal, they are replaced with a 1, otherwise a 0. Then, it examines
  1567. // the top item on the data stack as a boolean value and verifies it evaluates
  1568. // to true. An error is returned if it does not.
  1569. //
  1570. // Stack transformation: [... x1 x2] -> [... bool] -> [...]
  1571. func opcodeNumEqualVerify(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1572. err := opcodeNumEqual(op, vm)
  1573. if err == nil {
  1574. err = abstractVerify(op, vm, txscripterr.ErrNumEqualVerify)
  1575. }
  1576. return err
  1577. }
  1578. // opcodeNumNotEqual treats the top two items on the data stack as integers.
  1579. // When they are NOT equal, they are replaced with a 1, otherwise a 0.
  1580. //
  1581. // Stack transformation (x1==x2): [... 5 5] -> [... 0]
  1582. // Stack transformation (x1!=x2): [... 5 7] -> [... 1]
  1583. func opcodeNumNotEqual(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1584. v0, err := vm.dstack.PopInt()
  1585. if err != nil {
  1586. return err
  1587. }
  1588. v1, err := vm.dstack.PopInt()
  1589. if err != nil {
  1590. return err
  1591. }
  1592. if v0 != v1 {
  1593. vm.dstack.PushInt(scriptnum.ScriptNum(1))
  1594. } else {
  1595. vm.dstack.PushInt(scriptnum.ScriptNum(0))
  1596. }
  1597. return nil
  1598. }
  1599. // opcodeLessThan treats the top two items on the data stack as integers. When
  1600. // the second-to-top item is less than the top item, they are replaced with a 1,
  1601. // otherwise a 0.
  1602. //
  1603. // Stack transformation: [... x1 x2] -> [... bool]
  1604. func opcodeLessThan(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1605. v0, err := vm.dstack.PopInt()
  1606. if err != nil {
  1607. return err
  1608. }
  1609. v1, err := vm.dstack.PopInt()
  1610. if err != nil {
  1611. return err
  1612. }
  1613. if v1 < v0 {
  1614. vm.dstack.PushInt(scriptnum.ScriptNum(1))
  1615. } else {
  1616. vm.dstack.PushInt(scriptnum.ScriptNum(0))
  1617. }
  1618. return nil
  1619. }
  1620. // opcodeGreaterThan treats the top two items on the data stack as integers.
  1621. // When the second-to-top item is greater than the top item, they are replaced
  1622. // with a 1, otherwise a 0.
  1623. //
  1624. // Stack transformation: [... x1 x2] -> [... bool]
  1625. func opcodeGreaterThan(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1626. v0, err := vm.dstack.PopInt()
  1627. if err != nil {
  1628. return err
  1629. }
  1630. v1, err := vm.dstack.PopInt()
  1631. if err != nil {
  1632. return err
  1633. }
  1634. if v1 > v0 {
  1635. vm.dstack.PushInt(scriptnum.ScriptNum(1))
  1636. } else {
  1637. vm.dstack.PushInt(scriptnum.ScriptNum(0))
  1638. }
  1639. return nil
  1640. }
  1641. // opcodeLessThanOrEqual treats the top two items on the data stack as integers.
  1642. // When the second-to-top item is less than or equal to the top item, they are
  1643. // replaced with a 1, otherwise a 0.
  1644. //
  1645. // Stack transformation: [... x1 x2] -> [... bool]
  1646. func opcodeLessThanOrEqual(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1647. v0, err := vm.dstack.PopInt()
  1648. if err != nil {
  1649. return err
  1650. }
  1651. v1, err := vm.dstack.PopInt()
  1652. if err != nil {
  1653. return err
  1654. }
  1655. if v1 <= v0 {
  1656. vm.dstack.PushInt(scriptnum.ScriptNum(1))
  1657. } else {
  1658. vm.dstack.PushInt(scriptnum.ScriptNum(0))
  1659. }
  1660. return nil
  1661. }
  1662. // opcodeGreaterThanOrEqual treats the top two items on the data stack as
  1663. // integers. When the second-to-top item is greater than or equal to the top
  1664. // item, they are replaced with a 1, otherwise a 0.
  1665. //
  1666. // Stack transformation: [... x1 x2] -> [... bool]
  1667. func opcodeGreaterThanOrEqual(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1668. v0, err := vm.dstack.PopInt()
  1669. if err != nil {
  1670. return err
  1671. }
  1672. v1, err := vm.dstack.PopInt()
  1673. if err != nil {
  1674. return err
  1675. }
  1676. if v1 >= v0 {
  1677. vm.dstack.PushInt(scriptnum.ScriptNum(1))
  1678. } else {
  1679. vm.dstack.PushInt(scriptnum.ScriptNum(0))
  1680. }
  1681. return nil
  1682. }
  1683. // opcodeMin treats the top two items on the data stack as integers and replaces
  1684. // them with the minimum of the two.
  1685. //
  1686. // Stack transformation: [... x1 x2] -> [... min(x1, x2)]
  1687. func opcodeMin(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1688. v0, err := vm.dstack.PopInt()
  1689. if err != nil {
  1690. return err
  1691. }
  1692. v1, err := vm.dstack.PopInt()
  1693. if err != nil {
  1694. return err
  1695. }
  1696. if v1 < v0 {
  1697. vm.dstack.PushInt(v1)
  1698. } else {
  1699. vm.dstack.PushInt(v0)
  1700. }
  1701. return nil
  1702. }
  1703. // opcodeMax treats the top two items on the data stack as integers and replaces
  1704. // them with the maximum of the two.
  1705. //
  1706. // Stack transformation: [... x1 x2] -> [... max(x1, x2)]
  1707. func opcodeMax(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1708. v0, err := vm.dstack.PopInt()
  1709. if err != nil {
  1710. return err
  1711. }
  1712. v1, err := vm.dstack.PopInt()
  1713. if err != nil {
  1714. return err
  1715. }
  1716. if v1 > v0 {
  1717. vm.dstack.PushInt(v1)
  1718. } else {
  1719. vm.dstack.PushInt(v0)
  1720. }
  1721. return nil
  1722. }
  1723. // opcodeWithin treats the top 3 items on the data stack as integers. When the
  1724. // value to test is within the specified range (left inclusive), they are
  1725. // replaced with a 1, otherwise a 0.
  1726. //
  1727. // The top item is the max value, the second-top-item is the minimum value, and
  1728. // the third-to-top item is the value to test.
  1729. //
  1730. // Stack transformation: [... x1 min max] -> [... bool]
  1731. func opcodeWithin(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1732. maxVal, err := vm.dstack.PopInt()
  1733. if err != nil {
  1734. return err
  1735. }
  1736. minVal, err := vm.dstack.PopInt()
  1737. if err != nil {
  1738. return err
  1739. }
  1740. x, err := vm.dstack.PopInt()
  1741. if err != nil {
  1742. return err
  1743. }
  1744. if x >= minVal && x < maxVal {
  1745. vm.dstack.PushInt(scriptnum.ScriptNum(1))
  1746. } else {
  1747. vm.dstack.PushInt(scriptnum.ScriptNum(0))
  1748. }
  1749. return nil
  1750. }
  1751. // opcodeRipemd160 treats the top item of the data stack as raw bytes and
  1752. // replaces it with ripemd160(data).
  1753. //
  1754. // Stack transformation: [... x1] -> [... ripemd160(x1)]
  1755. func opcodeRipemd160(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1756. buf, err := vm.dstack.PopByteArray()
  1757. if err != nil {
  1758. return err
  1759. }
  1760. vm.dstack.PushByteArray(btcutil.Ripemd160(buf))
  1761. return nil
  1762. }
  1763. // opcodeSha1 treats the top item of the data stack as raw bytes and replaces it
  1764. // with sha1(data).
  1765. //
  1766. // Stack transformation: [... x1] -> [... sha1(x1)]
  1767. func opcodeSha1(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1768. buf, err := vm.dstack.PopByteArray()
  1769. if err != nil {
  1770. return err
  1771. }
  1772. hash := sha1.Sum(buf)
  1773. vm.dstack.PushByteArray(hash[:])
  1774. return nil
  1775. }
  1776. // opcodeSha256 treats the top item of the data stack as raw bytes and replaces
  1777. // it with sha256(data).
  1778. //
  1779. // Stack transformation: [... x1] -> [... sha256(x1)]
  1780. func opcodeSha256(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1781. buf, err := vm.dstack.PopByteArray()
  1782. if err != nil {
  1783. return err
  1784. }
  1785. hash := sha256.Sum256(buf)
  1786. vm.dstack.PushByteArray(hash[:])
  1787. return nil
  1788. }
  1789. // opcodeHash160 treats the top item of the data stack as raw bytes and replaces
  1790. // it with ripemd160(sha256(data)).
  1791. //
  1792. // Stack transformation: [... x1] -> [... ripemd160(sha256(x1))]
  1793. func opcodeHash160(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1794. buf, err := vm.dstack.PopByteArray()
  1795. if err != nil {
  1796. return err
  1797. }
  1798. vm.dstack.PushByteArray(btcutil.Hash160(buf))
  1799. return nil
  1800. }
  1801. // opcodeHash256 treats the top item of the data stack as raw bytes and replaces
  1802. // it with sha256(sha256(data)).
  1803. //
  1804. // Stack transformation: [... x1] -> [... sha256(sha256(x1))]
  1805. func opcodeHash256(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1806. buf, err := vm.dstack.PopByteArray()
  1807. if err != nil {
  1808. return err
  1809. }
  1810. vm.dstack.PushByteArray(chainhash.DoubleHashB(buf))
  1811. return nil
  1812. }
  1813. // opcodeCodeSeparator stores the current script offset as the most recently
  1814. // seen OP_CODESEPARATOR which is used during signature checking.
  1815. //
  1816. // This opcode does not change the contents of the data stack.
  1817. func opcodeCodeSeparator(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1818. vm.lastCodeSep = vm.scriptOff
  1819. return nil
  1820. }
  1821. // opcodeCheckSig treats the top 2 items on the stack as a public key and a
  1822. // signature and replaces them with a bool which indicates if the signature was
  1823. // successfully verified.
  1824. //
  1825. // The process of verifying a signature requires calculating a signature hash in
  1826. // the same way the transaction signer did. It involves hashing portions of the
  1827. // transaction based on the hash type byte (which is the final byte of the
  1828. // signature) and the portion of the script starting from the most recent
  1829. // OP_CODESEPARATOR (or the beginning of the script if there are none) to the
  1830. // end of the script (with any other OP_CODESEPARATORs removed). Once this
  1831. // "script hash" is calculated, the signature is checked using standard
  1832. // cryptographic methods against the provided public key.
  1833. //
  1834. // Stack transformation: [... signature pubkey] -> [... bool]
  1835. func opcodeCheckSig(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1836. pkBytes, err := vm.dstack.PopByteArray()
  1837. if err != nil {
  1838. return err
  1839. }
  1840. fullSigBytes, err := vm.dstack.PopByteArray()
  1841. if err != nil {
  1842. return err
  1843. }
  1844. // The signature actually needs needs to be longer than this, but at
  1845. // least 1 byte is needed for the hash type below. The full length is
  1846. // checked depending on the script flags and upon parsing the signature.
  1847. if len(fullSigBytes) < 1 {
  1848. vm.dstack.PushBool(false)
  1849. return nil
  1850. }
  1851. // Trim off hashtype from the signature string and check if the
  1852. // signature and pubkey conform to the strict encoding requirements
  1853. // depending on the flags.
  1854. //
  1855. // NOTE: When the strict encoding flags are set, any errors in the
  1856. // signature or public encoding here result in an immediate script error
  1857. // (and thus no result bool is pushed to the data stack). This differs
  1858. // from the logic below where any errors in parsing the signature is
  1859. // treated as the signature failure resulting in false being pushed to
  1860. // the data stack. This is required because the more general script
  1861. // validation consensus rules do not have the new strict encoding
  1862. // requirements enabled by the flags.
  1863. hashType := params.SigHashType(fullSigBytes[len(fullSigBytes)-1])
  1864. sigBytes := fullSigBytes[:len(fullSigBytes)-1]
  1865. if err := vm.checkHashTypeEncoding(hashType); err != nil {
  1866. return err
  1867. }
  1868. if err := vm.checkSignatureEncoding(sigBytes); err != nil {
  1869. return err
  1870. }
  1871. if err := vm.checkPubKeyEncoding(pkBytes); err != nil {
  1872. return err
  1873. }
  1874. // Get script starting from the most recent OP_CODESEPARATOR.
  1875. subScript := vm.subScript()
  1876. // Generate the signature hash based on the signature hash type.
  1877. var hash []byte
  1878. if vm.isWitnessVersionActive(0) {
  1879. var sigHashes *TxSigHashes
  1880. if vm.hashCache != nil {
  1881. sigHashes = vm.hashCache
  1882. } else {
  1883. sigHashes = NewTxSigHashes(&vm.tx)
  1884. }
  1885. hash, err = calcWitnessSignatureHash(subScript, sigHashes, hashType,
  1886. &vm.tx, vm.txIdx, vm.inputAmount)
  1887. if err != nil {
  1888. return err
  1889. }
  1890. } else {
  1891. // Remove the signature since there is no way for a signature
  1892. // to sign itself.
  1893. subScript = removeOpcodeByData(subScript, fullSigBytes)
  1894. hash = calcSignatureHash(subScript, hashType, &vm.tx, vm.txIdx)
  1895. }
  1896. pubKey, err := btcec.ParsePubKey(pkBytes, btcec.S256())
  1897. if err != nil {
  1898. vm.dstack.PushBool(false)
  1899. return nil
  1900. }
  1901. var signature *btcec.Signature
  1902. if vm.hasFlag(ScriptVerifyStrictEncoding) ||
  1903. vm.hasFlag(ScriptVerifyDERSignatures) {
  1904. signature, err = btcec.ParseDERSignature(sigBytes, btcec.S256())
  1905. } else {
  1906. signature, err = btcec.ParseSignature(sigBytes, btcec.S256())
  1907. }
  1908. if err != nil {
  1909. vm.dstack.PushBool(false)
  1910. return nil
  1911. }
  1912. var valid bool
  1913. if vm.sigCache != nil {
  1914. var sigHash chainhash.Hash
  1915. copy(sigHash[:], hash)
  1916. valid = vm.sigCache.Exists(sigHash, signature, pubKey)
  1917. if !valid && signature.Verify(hash, pubKey) {
  1918. vm.sigCache.Add(sigHash, signature, pubKey)
  1919. valid = true
  1920. }
  1921. } else {
  1922. valid = signature.Verify(hash, pubKey)
  1923. }
  1924. if !valid && vm.hasFlag(ScriptVerifyNullFail) && len(sigBytes) > 0 {
  1925. str := "signature not empty on failed checksig"
  1926. return txscripterr.ScriptError(txscripterr.ErrNullFail, str)
  1927. }
  1928. vm.dstack.PushBool(valid)
  1929. return nil
  1930. }
  1931. // opcodeCheckSigVerify is a combination of opcodeCheckSig and opcodeVerify.
  1932. // The opcodeCheckSig function is invoked followed by opcodeVerify. See the
  1933. // documentation for each of those opcodes for more details.
  1934. //
  1935. // Stack transformation: signature pubkey] -> [... bool] -> [...]
  1936. func opcodeCheckSigVerify(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1937. err := opcodeCheckSig(op, vm)
  1938. if err == nil {
  1939. err = abstractVerify(op, vm, txscripterr.ErrCheckSigVerify)
  1940. }
  1941. return err
  1942. }
  1943. // parsedSigInfo houses a raw signature along with its parsed form and a flag
  1944. // for whether or not it has already been parsed. It is used to prevent parsing
  1945. // the same signature multiple times when verifying a multisig.
  1946. type parsedSigInfo struct {
  1947. signature []byte
  1948. parsedSignature *btcec.Signature
  1949. parsed bool
  1950. }
  1951. // opcodeCheckMultiSig treats the top item on the stack as an integer number of
  1952. // public keys, followed by that many entries as raw data representing the public
  1953. // keys, followed by the integer number of signatures, followed by that many
  1954. // entries as raw data representing the signatures.
  1955. //
  1956. // Due to a bug in the original Satoshi client implementation, an additional
  1957. // dummy argument is also required by the consensus rules, although it is not
  1958. // used. The dummy value SHOULD be an OP_0, although that is not required by
  1959. // the consensus rules. When the ScriptStrictMultiSig flag is set, it must be
  1960. // OP_0.
  1961. //
  1962. // All of the aforementioned stack items are replaced with a bool which
  1963. // indicates if the requisite number of signatures were successfully verified.
  1964. //
  1965. // See the opcodeCheckSigVerify documentation for more details about the process
  1966. // for verifying each signature.
  1967. //
  1968. // Stack transformation:
  1969. // [... dummy [sig ...] numsigs [pubkey ...] numpubkeys] -> [... bool]
  1970. func opcodeCheckMultiSig(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  1971. numKeys, err := vm.dstack.PopInt()
  1972. if err != nil {
  1973. return err
  1974. }
  1975. numPubKeys := int(numKeys.Int32())
  1976. if numPubKeys < 0 {
  1977. str := fmt.Sprintf("number of pubkeys %d is negative",
  1978. numPubKeys)
  1979. return txscripterr.ScriptError(txscripterr.ErrInvalidPubKeyCount, str)
  1980. }
  1981. if numPubKeys > params.MaxPubKeysPerMultiSig {
  1982. str := fmt.Sprintf("too many pubkeys: %d > %d",
  1983. numPubKeys, params.MaxPubKeysPerMultiSig)
  1984. return txscripterr.ScriptError(txscripterr.ErrInvalidPubKeyCount, str)
  1985. }
  1986. vm.numOps += numPubKeys
  1987. if vm.numOps > params.MaxOpsPerScript {
  1988. str := fmt.Sprintf("exceeded max operation limit of %d",
  1989. params.MaxOpsPerScript)
  1990. return txscripterr.ScriptError(txscripterr.ErrTooManyOperations, str)
  1991. }
  1992. pubKeys := make([][]byte, 0, numPubKeys)
  1993. for i := 0; i < numPubKeys; i++ {
  1994. pubKey, err := vm.dstack.PopByteArray()
  1995. if err != nil {
  1996. return err
  1997. }
  1998. pubKeys = append(pubKeys, pubKey)
  1999. }
  2000. numSigs, err := vm.dstack.PopInt()
  2001. if err != nil {
  2002. return err
  2003. }
  2004. numSignatures := int(numSigs.Int32())
  2005. if numSignatures < 0 {
  2006. str := fmt.Sprintf("number of signatures %d is negative",
  2007. numSignatures)
  2008. return txscripterr.ScriptError(txscripterr.ErrInvalidSignatureCount, str)
  2009. }
  2010. if numSignatures > numPubKeys {
  2011. str := fmt.Sprintf("more signatures than pubkeys: %d > %d",
  2012. numSignatures, numPubKeys)
  2013. return txscripterr.ScriptError(txscripterr.ErrInvalidSignatureCount, str)
  2014. }
  2015. signatures := make([]*parsedSigInfo, 0, numSignatures)
  2016. for i := 0; i < numSignatures; i++ {
  2017. signature, err := vm.dstack.PopByteArray()
  2018. if err != nil {
  2019. return err
  2020. }
  2021. sigInfo := &parsedSigInfo{signature: signature}
  2022. signatures = append(signatures, sigInfo)
  2023. }
  2024. // A bug in the original Satoshi client implementation means one more
  2025. // stack value than should be used must be popped. Unfortunately, this
  2026. // buggy behavior is now part of the consensus and a hard fork would be
  2027. // required to fix it.
  2028. dummy, err := vm.dstack.PopByteArray()
  2029. if err != nil {
  2030. return err
  2031. }
  2032. // Since the dummy argument is otherwise not checked, it could be any
  2033. // value which unfortunately provides a source of malleability. Thus,
  2034. // there is a script flag to force an error when the value is NOT 0.
  2035. if vm.hasFlag(ScriptStrictMultiSig) && len(dummy) != 0 {
  2036. str := fmt.Sprintf("multisig dummy argument has length %d "+
  2037. "instead of 0", len(dummy))
  2038. return txscripterr.ScriptError(txscripterr.ErrSigNullDummy, str)
  2039. }
  2040. // Get script starting from the most recent OP_CODESEPARATOR.
  2041. script := vm.subScript()
  2042. // Remove the signature in pre version 0 segwit scripts since there is
  2043. // no way for a signature to sign itself.
  2044. if !vm.isWitnessVersionActive(0) {
  2045. for _, sigInfo := range signatures {
  2046. script = removeOpcodeByData(script, sigInfo.signature)
  2047. }
  2048. }
  2049. success := true
  2050. numPubKeys++
  2051. pubKeyIdx := -1
  2052. signatureIdx := 0
  2053. for numSignatures > 0 {
  2054. // When there are more signatures than public keys remaining,
  2055. // there is no way to succeed since too many signatures are
  2056. // invalid, so exit early.
  2057. pubKeyIdx++
  2058. numPubKeys--
  2059. if numSignatures > numPubKeys {
  2060. success = false
  2061. break
  2062. }
  2063. sigInfo := signatures[signatureIdx]
  2064. pubKey := pubKeys[pubKeyIdx]
  2065. // The order of the signature and public key evaluation is
  2066. // important here since it can be distinguished by an
  2067. // OP_CHECKMULTISIG NOT when the strict encoding flag is set.
  2068. rawSig := sigInfo.signature
  2069. if len(rawSig) == 0 {
  2070. // Skip to the next pubkey if signature is empty.
  2071. continue
  2072. }
  2073. // Split the signature into hash type and signature components.
  2074. hashType := params.SigHashType(rawSig[len(rawSig)-1])
  2075. signature := rawSig[:len(rawSig)-1]
  2076. // Only parse and check the signature encoding once.
  2077. var parsedSig *btcec.Signature
  2078. if !sigInfo.parsed {
  2079. if err := vm.checkHashTypeEncoding(hashType); err != nil {
  2080. return err
  2081. }
  2082. if err := vm.checkSignatureEncoding(signature); err != nil {
  2083. return err
  2084. }
  2085. // Parse the signature.
  2086. var err er.R
  2087. if vm.hasFlag(ScriptVerifyStrictEncoding) ||
  2088. vm.hasFlag(ScriptVerifyDERSignatures) {
  2089. parsedSig, err = btcec.ParseDERSignature(signature,
  2090. btcec.S256())
  2091. } else {
  2092. parsedSig, err = btcec.ParseSignature(signature,
  2093. btcec.S256())
  2094. }
  2095. sigInfo.parsed = true
  2096. if err != nil {
  2097. continue
  2098. }
  2099. sigInfo.parsedSignature = parsedSig
  2100. } else {
  2101. // Skip to the next pubkey if the signature is invalid.
  2102. if sigInfo.parsedSignature == nil {
  2103. continue
  2104. }
  2105. // Use the already parsed signature.
  2106. parsedSig = sigInfo.parsedSignature
  2107. }
  2108. if err := vm.checkPubKeyEncoding(pubKey); err != nil {
  2109. return err
  2110. }
  2111. // Parse the pubkey.
  2112. parsedPubKey, err := btcec.ParsePubKey(pubKey, btcec.S256())
  2113. if err != nil {
  2114. continue
  2115. }
  2116. // Generate the signature hash based on the signature hash type.
  2117. var hash []byte
  2118. if vm.isWitnessVersionActive(0) {
  2119. var sigHashes *TxSigHashes
  2120. if vm.hashCache != nil {
  2121. sigHashes = vm.hashCache
  2122. } else {
  2123. sigHashes = NewTxSigHashes(&vm.tx)
  2124. }
  2125. hash, err = calcWitnessSignatureHash(script, sigHashes, hashType,
  2126. &vm.tx, vm.txIdx, vm.inputAmount)
  2127. if err != nil {
  2128. return err
  2129. }
  2130. } else {
  2131. hash = calcSignatureHash(script, hashType, &vm.tx, vm.txIdx)
  2132. }
  2133. var valid bool
  2134. if vm.sigCache != nil {
  2135. var sigHash chainhash.Hash
  2136. copy(sigHash[:], hash)
  2137. valid = vm.sigCache.Exists(sigHash, parsedSig, parsedPubKey)
  2138. if !valid && parsedSig.Verify(hash, parsedPubKey) {
  2139. vm.sigCache.Add(sigHash, parsedSig, parsedPubKey)
  2140. valid = true
  2141. }
  2142. } else {
  2143. valid = parsedSig.Verify(hash, parsedPubKey)
  2144. }
  2145. if valid {
  2146. // PubKey verified, move on to the next signature.
  2147. signatureIdx++
  2148. numSignatures--
  2149. }
  2150. }
  2151. if !success && vm.hasFlag(ScriptVerifyNullFail) {
  2152. for _, sig := range signatures {
  2153. if len(sig.signature) > 0 {
  2154. str := "not all signatures empty on failed checkmultisig"
  2155. return txscripterr.ScriptError(txscripterr.ErrNullFail, str)
  2156. }
  2157. }
  2158. }
  2159. vm.dstack.PushBool(success)
  2160. return nil
  2161. }
  2162. // opcodeCheckMultiSigVerify is a combination of opcodeCheckMultiSig and
  2163. // opcodeVerify. The opcodeCheckMultiSig is invoked followed by opcodeVerify.
  2164. // See the documentation for each of those opcodes for more details.
  2165. //
  2166. // Stack transformation:
  2167. // [... dummy [sig ...] numsigs [pubkey ...] numpubkeys] -> [... bool] -> [...]
  2168. func opcodeCheckMultiSigVerify(op *parsescript.ParsedOpcode, vm *Engine) er.R {
  2169. err := opcodeCheckMultiSig(op, vm)
  2170. if err == nil {
  2171. err = abstractVerify(op, vm, txscripterr.ErrCheckMultiSigVerify)
  2172. }
  2173. return err
  2174. }
  2175. // OpcodeByName is a map that can be used to lookup an opcode by its
  2176. // human-readable name (OP_CHECKMULTISIG, OP_CHECKSIG, etc).
  2177. var OpcodeByName = make(map[string]byte)
  2178. func init() {
  2179. // Initialize the opcode name to value map using the contents of the
  2180. // opcode array. Also add entries for "OP_FALSE", "OP_TRUE", and
  2181. // "OP_NOP2" since they are aliases for "OP_0", "OP_1",
  2182. // and "OP_CHECKLOCKTIMEVERIFY" respectively.
  2183. for i := 0; i < 256; i++ {
  2184. OpcodeByName[opcode.OpcodeName(byte(i))] = byte(i)
  2185. }
  2186. OpcodeByName["OP_FALSE"] = opcode.OP_FALSE
  2187. OpcodeByName["OP_TRUE"] = opcode.OP_TRUE
  2188. OpcodeByName["OP_NOP2"] = opcode.OP_CHECKLOCKTIMEVERIFY
  2189. OpcodeByName["OP_NOP3"] = opcode.OP_CHECKSEQUENCEVERIFY
  2190. }