You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

interpreter.cpp 62KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2017 The Starwels developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include <script/interpreter.h>
  6. #include <crypto/ripemd160.h>
  7. #include <crypto/sha1.h>
  8. #include <crypto/sha256.h>
  9. #include <pubkey.h>
  10. #include <script/script.h>
  11. #include <uint256.h>
  12. typedef std::vector<unsigned char> valtype;
  13. namespace {
  14. inline bool set_success(ScriptError* ret)
  15. {
  16. if (ret)
  17. *ret = SCRIPT_ERR_OK;
  18. return true;
  19. }
  20. inline bool set_error(ScriptError* ret, const ScriptError serror)
  21. {
  22. if (ret)
  23. *ret = serror;
  24. return false;
  25. }
  26. } // namespace
  27. bool CastToBool(const valtype& vch)
  28. {
  29. for (unsigned int i = 0; i < vch.size(); i++)
  30. {
  31. if (vch[i] != 0)
  32. {
  33. // Can be negative zero
  34. if (i == vch.size()-1 && vch[i] == 0x80)
  35. return false;
  36. return true;
  37. }
  38. }
  39. return false;
  40. }
  41. /**
  42. * Script is a stack machine (like Forth) that evaluates a predicate
  43. * returning a bool indicating valid or not. There are no loops.
  44. */
  45. #define stacktop(i) (stack.at(stack.size()+(i)))
  46. #define altstacktop(i) (altstack.at(altstack.size()+(i)))
  47. static inline void popstack(std::vector<valtype>& stack)
  48. {
  49. if (stack.empty())
  50. throw std::runtime_error("popstack(): stack empty");
  51. stack.pop_back();
  52. }
  53. bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
  54. if (vchPubKey.size() < 33) {
  55. // Non-canonical public key: too short
  56. return false;
  57. }
  58. if (vchPubKey[0] == 0x04) {
  59. if (vchPubKey.size() != 65) {
  60. // Non-canonical public key: invalid length for uncompressed key
  61. return false;
  62. }
  63. } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
  64. if (vchPubKey.size() != 33) {
  65. // Non-canonical public key: invalid length for compressed key
  66. return false;
  67. }
  68. } else {
  69. // Non-canonical public key: neither compressed nor uncompressed
  70. return false;
  71. }
  72. return true;
  73. }
  74. bool static IsCompressedPubKey(const valtype &vchPubKey) {
  75. if (vchPubKey.size() != 33) {
  76. // Non-canonical public key: invalid length for compressed key
  77. return false;
  78. }
  79. if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
  80. // Non-canonical public key: invalid prefix for compressed key
  81. return false;
  82. }
  83. return true;
  84. }
  85. /**
  86. * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
  87. * Where R and S are not negative (their first byte has its highest bit not set), and not
  88. * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
  89. * in which case a single 0 byte is necessary and even required).
  90. *
  91. * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
  92. *
  93. * This function is consensus-critical since BIP66.
  94. */
  95. bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
  96. // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
  97. // * total-length: 1-byte length descriptor of everything that follows,
  98. // excluding the sighash byte.
  99. // * R-length: 1-byte length descriptor of the R value that follows.
  100. // * R: arbitrary-length big-endian encoded R value. It must use the shortest
  101. // possible encoding for a positive integers (which means no null bytes at
  102. // the start, except a single one when the next byte has its highest bit set).
  103. // * S-length: 1-byte length descriptor of the S value that follows.
  104. // * S: arbitrary-length big-endian encoded S value. The same rules apply.
  105. // * sighash: 1-byte value indicating what data is hashed (not part of the DER
  106. // signature)
  107. // Minimum and maximum size constraints.
  108. if (sig.size() < 9) return false;
  109. if (sig.size() > 73) return false;
  110. // A signature is of type 0x30 (compound).
  111. if (sig[0] != 0x30) return false;
  112. // Make sure the length covers the entire signature.
  113. if (sig[1] != sig.size() - 3) return false;
  114. // Extract the length of the R element.
  115. unsigned int lenR = sig[3];
  116. // Make sure the length of the S element is still inside the signature.
  117. if (5 + lenR >= sig.size()) return false;
  118. // Extract the length of the S element.
  119. unsigned int lenS = sig[5 + lenR];
  120. // Verify that the length of the signature matches the sum of the length
  121. // of the elements.
  122. if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
  123. // Check whether the R element is an integer.
  124. if (sig[2] != 0x02) return false;
  125. // Zero-length integers are not allowed for R.
  126. if (lenR == 0) return false;
  127. // Negative numbers are not allowed for R.
  128. if (sig[4] & 0x80) return false;
  129. // Null bytes at the start of R are not allowed, unless R would
  130. // otherwise be interpreted as a negative number.
  131. if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
  132. // Check whether the S element is an integer.
  133. if (sig[lenR + 4] != 0x02) return false;
  134. // Zero-length integers are not allowed for S.
  135. if (lenS == 0) return false;
  136. // Negative numbers are not allowed for S.
  137. if (sig[lenR + 6] & 0x80) return false;
  138. // Null bytes at the start of S are not allowed, unless S would otherwise be
  139. // interpreted as a negative number.
  140. if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
  141. return true;
  142. }
  143. bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
  144. if (!IsValidSignatureEncoding(vchSig)) {
  145. return set_error(serror, SCRIPT_ERR_SIG_DER);
  146. }
  147. // https://bitcoin.stackexchange.com/a/12556:
  148. // Also note that inside transaction signatures, an extra hashtype byte
  149. // follows the actual signature data.
  150. std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
  151. // If the S value is above the order of the curve divided by two, its
  152. // complement modulo the order could have been used instead, which is
  153. // one byte shorter when encoded correctly.
  154. if (!CPubKey::CheckLowS(vchSigCopy)) {
  155. return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
  156. }
  157. return true;
  158. }
  159. bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
  160. if (vchSig.size() == 0) {
  161. return false;
  162. }
  163. unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
  164. if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
  165. return false;
  166. return true;
  167. }
  168. bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
  169. // Empty signature. Not strictly DER encoded, but allowed to provide a
  170. // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
  171. if (vchSig.size() == 0) {
  172. return true;
  173. }
  174. if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
  175. return set_error(serror, SCRIPT_ERR_SIG_DER);
  176. } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
  177. // serror is set
  178. return false;
  179. } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
  180. return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
  181. }
  182. return true;
  183. }
  184. bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
  185. if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
  186. return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
  187. }
  188. // Only compressed keys are accepted in segwit
  189. if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SIGVERSION_WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
  190. return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
  191. }
  192. return true;
  193. }
  194. bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
  195. if (data.size() == 0) {
  196. // Could have used OP_0.
  197. return opcode == OP_0;
  198. } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
  199. // Could have used OP_1 .. OP_16.
  200. return opcode == OP_1 + (data[0] - 1);
  201. } else if (data.size() == 1 && data[0] == 0x81) {
  202. // Could have used OP_1NEGATE.
  203. return opcode == OP_1NEGATE;
  204. } else if (data.size() <= 75) {
  205. // Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
  206. return opcode == data.size();
  207. } else if (data.size() <= 255) {
  208. // Could have used OP_PUSHDATA.
  209. return opcode == OP_PUSHDATA1;
  210. } else if (data.size() <= 65535) {
  211. // Could have used OP_PUSHDATA2.
  212. return opcode == OP_PUSHDATA2;
  213. }
  214. return true;
  215. }
  216. bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
  217. {
  218. static const CScriptNum bnZero(0);
  219. static const CScriptNum bnOne(1);
  220. // static const CScriptNum bnFalse(0);
  221. // static const CScriptNum bnTrue(1);
  222. static const valtype vchFalse(0);
  223. // static const valtype vchZero(0);
  224. static const valtype vchTrue(1, 1);
  225. CScript::const_iterator pc = script.begin();
  226. CScript::const_iterator pend = script.end();
  227. CScript::const_iterator pbegincodehash = script.begin();
  228. opcodetype opcode;
  229. valtype vchPushValue;
  230. std::vector<bool> vfExec;
  231. std::vector<valtype> altstack;
  232. set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
  233. if (script.size() > MAX_SCRIPT_SIZE)
  234. return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
  235. int nOpCount = 0;
  236. bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
  237. try
  238. {
  239. while (pc < pend)
  240. {
  241. bool fExec = !count(vfExec.begin(), vfExec.end(), false);
  242. //
  243. // Read instruction
  244. //
  245. if (!script.GetOp(pc, opcode, vchPushValue))
  246. return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
  247. if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
  248. return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
  249. // Note how OP_RESERVED does not count towards the opcode limit.
  250. if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
  251. return set_error(serror, SCRIPT_ERR_OP_COUNT);
  252. if (opcode == OP_CAT ||
  253. opcode == OP_SUBSTR ||
  254. opcode == OP_LEFT ||
  255. opcode == OP_RIGHT ||
  256. opcode == OP_INVERT ||
  257. opcode == OP_AND ||
  258. opcode == OP_OR ||
  259. opcode == OP_XOR ||
  260. opcode == OP_2MUL ||
  261. opcode == OP_2DIV ||
  262. opcode == OP_MUL ||
  263. opcode == OP_DIV ||
  264. opcode == OP_MOD ||
  265. opcode == OP_LSHIFT ||
  266. opcode == OP_RSHIFT)
  267. return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.
  268. // With SCRIPT_VERIFY_CONST_SCRIPTCODE, OP_CODESEPARATOR in non-segwit script is rejected even in an unexecuted branch
  269. if (opcode == OP_CODESEPARATOR && sigversion == SIGVERSION_BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
  270. return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
  271. if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
  272. if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
  273. return set_error(serror, SCRIPT_ERR_MINIMALDATA);
  274. }
  275. stack.push_back(vchPushValue);
  276. } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
  277. switch (opcode)
  278. {
  279. //
  280. // Push value
  281. //
  282. case OP_1NEGATE:
  283. case OP_1:
  284. case OP_2:
  285. case OP_3:
  286. case OP_4:
  287. case OP_5:
  288. case OP_6:
  289. case OP_7:
  290. case OP_8:
  291. case OP_9:
  292. case OP_10:
  293. case OP_11:
  294. case OP_12:
  295. case OP_13:
  296. case OP_14:
  297. case OP_15:
  298. case OP_16:
  299. {
  300. // ( -- value)
  301. CScriptNum bn((int)opcode - (int)(OP_1 - 1));
  302. stack.push_back(bn.getvch());
  303. // The result of these opcodes should always be the minimal way to push the data
  304. // they push, so no need for a CheckMinimalPush here.
  305. }
  306. break;
  307. //
  308. // Control
  309. //
  310. case OP_NOP:
  311. break;
  312. case OP_CHECKLOCKTIMEVERIFY:
  313. {
  314. if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
  315. // not enabled; treat as a NOP2
  316. break;
  317. }
  318. if (stack.size() < 1)
  319. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  320. // Note that elsewhere numeric opcodes are limited to
  321. // operands in the range -2**31+1 to 2**31-1, however it is
  322. // legal for opcodes to produce results exceeding that
  323. // range. This limitation is implemented by CScriptNum's
  324. // default 4-byte limit.
  325. //
  326. // If we kept to that limit we'd have a year 2038 problem,
  327. // even though the nLockTime field in transactions
  328. // themselves is uint32 which only becomes meaningless
  329. // after the year 2106.
  330. //
  331. // Thus as a special case we tell CScriptNum to accept up
  332. // to 5-byte bignums, which are good until 2**39-1, well
  333. // beyond the 2**32-1 limit of the nLockTime field itself.
  334. const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
  335. // In the rare event that the argument may be < 0 due to
  336. // some arithmetic being done first, you can always use
  337. // 0 MAX CHECKLOCKTIMEVERIFY.
  338. if (nLockTime < 0)
  339. return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
  340. // Actually compare the specified lock time with the transaction.
  341. if (!checker.CheckLockTime(nLockTime))
  342. return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
  343. break;
  344. }
  345. case OP_CHECKSEQUENCEVERIFY:
  346. {
  347. if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
  348. // not enabled; treat as a NOP3
  349. break;
  350. }
  351. if (stack.size() < 1)
  352. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  353. // nSequence, like nLockTime, is a 32-bit unsigned integer
  354. // field. See the comment in CHECKLOCKTIMEVERIFY regarding
  355. // 5-byte numeric operands.
  356. const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
  357. // In the rare event that the argument may be < 0 due to
  358. // some arithmetic being done first, you can always use
  359. // 0 MAX CHECKSEQUENCEVERIFY.
  360. if (nSequence < 0)
  361. return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
  362. // To provide for future soft-fork extensibility, if the
  363. // operand has the disabled lock-time flag set,
  364. // CHECKSEQUENCEVERIFY behaves as a NOP.
  365. if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
  366. break;
  367. // Compare the specified sequence number with the input.
  368. if (!checker.CheckSequence(nSequence))
  369. return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
  370. break;
  371. }
  372. case OP_NOP1: case OP_NOP4: case OP_NOP5:
  373. case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
  374. {
  375. if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
  376. return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
  377. }
  378. break;
  379. case OP_IF:
  380. case OP_NOTIF:
  381. {
  382. // <expression> if [statements] [else [statements]] endif
  383. bool fValue = false;
  384. if (fExec)
  385. {
  386. if (stack.size() < 1)
  387. return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
  388. valtype& vch = stacktop(-1);
  389. if (sigversion == SIGVERSION_WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
  390. if (vch.size() > 1)
  391. return set_error(serror, SCRIPT_ERR_MINIMALIF);
  392. if (vch.size() == 1 && vch[0] != 1)
  393. return set_error(serror, SCRIPT_ERR_MINIMALIF);
  394. }
  395. fValue = CastToBool(vch);
  396. if (opcode == OP_NOTIF)
  397. fValue = !fValue;
  398. popstack(stack);
  399. }
  400. vfExec.push_back(fValue);
  401. }
  402. break;
  403. case OP_ELSE:
  404. {
  405. if (vfExec.empty())
  406. return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
  407. vfExec.back() = !vfExec.back();
  408. }
  409. break;
  410. case OP_ENDIF:
  411. {
  412. if (vfExec.empty())
  413. return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
  414. vfExec.pop_back();
  415. }
  416. break;
  417. case OP_VERIFY:
  418. {
  419. // (true -- ) or
  420. // (false -- false) and return
  421. if (stack.size() < 1)
  422. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  423. bool fValue = CastToBool(stacktop(-1));
  424. if (fValue)
  425. popstack(stack);
  426. else
  427. return set_error(serror, SCRIPT_ERR_VERIFY);
  428. }
  429. break;
  430. case OP_RETURN:
  431. {
  432. return set_error(serror, SCRIPT_ERR_OP_RETURN);
  433. }
  434. break;
  435. //
  436. // Stack ops
  437. //
  438. case OP_TOALTSTACK:
  439. {
  440. if (stack.size() < 1)
  441. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  442. altstack.push_back(stacktop(-1));
  443. popstack(stack);
  444. }
  445. break;
  446. case OP_FROMALTSTACK:
  447. {
  448. if (altstack.size() < 1)
  449. return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
  450. stack.push_back(altstacktop(-1));
  451. popstack(altstack);
  452. }
  453. break;
  454. case OP_2DROP:
  455. {
  456. // (x1 x2 -- )
  457. if (stack.size() < 2)
  458. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  459. popstack(stack);
  460. popstack(stack);
  461. }
  462. break;
  463. case OP_2DUP:
  464. {
  465. // (x1 x2 -- x1 x2 x1 x2)
  466. if (stack.size() < 2)
  467. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  468. valtype vch1 = stacktop(-2);
  469. valtype vch2 = stacktop(-1);
  470. stack.push_back(vch1);
  471. stack.push_back(vch2);
  472. }
  473. break;
  474. case OP_3DUP:
  475. {
  476. // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
  477. if (stack.size() < 3)
  478. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  479. valtype vch1 = stacktop(-3);
  480. valtype vch2 = stacktop(-2);
  481. valtype vch3 = stacktop(-1);
  482. stack.push_back(vch1);
  483. stack.push_back(vch2);
  484. stack.push_back(vch3);
  485. }
  486. break;
  487. case OP_2OVER:
  488. {
  489. // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
  490. if (stack.size() < 4)
  491. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  492. valtype vch1 = stacktop(-4);
  493. valtype vch2 = stacktop(-3);
  494. stack.push_back(vch1);
  495. stack.push_back(vch2);
  496. }
  497. break;
  498. case OP_2ROT:
  499. {
  500. // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
  501. if (stack.size() < 6)
  502. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  503. valtype vch1 = stacktop(-6);
  504. valtype vch2 = stacktop(-5);
  505. stack.erase(stack.end()-6, stack.end()-4);
  506. stack.push_back(vch1);
  507. stack.push_back(vch2);
  508. }
  509. break;
  510. case OP_2SWAP:
  511. {
  512. // (x1 x2 x3 x4 -- x3 x4 x1 x2)
  513. if (stack.size() < 4)
  514. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  515. swap(stacktop(-4), stacktop(-2));
  516. swap(stacktop(-3), stacktop(-1));
  517. }
  518. break;
  519. case OP_IFDUP:
  520. {
  521. // (x - 0 | x x)
  522. if (stack.size() < 1)
  523. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  524. valtype vch = stacktop(-1);
  525. if (CastToBool(vch))
  526. stack.push_back(vch);
  527. }
  528. break;
  529. case OP_DEPTH:
  530. {
  531. // -- stacksize
  532. CScriptNum bn(stack.size());
  533. stack.push_back(bn.getvch());
  534. }
  535. break;
  536. case OP_DROP:
  537. {
  538. // (x -- )
  539. if (stack.size() < 1)
  540. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  541. popstack(stack);
  542. }
  543. break;
  544. case OP_DUP:
  545. {
  546. // (x -- x x)
  547. if (stack.size() < 1)
  548. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  549. valtype vch = stacktop(-1);
  550. stack.push_back(vch);
  551. }
  552. break;
  553. case OP_NIP:
  554. {
  555. // (x1 x2 -- x2)
  556. if (stack.size() < 2)
  557. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  558. stack.erase(stack.end() - 2);
  559. }
  560. break;
  561. case OP_OVER:
  562. {
  563. // (x1 x2 -- x1 x2 x1)
  564. if (stack.size() < 2)
  565. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  566. valtype vch = stacktop(-2);
  567. stack.push_back(vch);
  568. }
  569. break;
  570. case OP_PICK:
  571. case OP_ROLL:
  572. {
  573. // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
  574. // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
  575. if (stack.size() < 2)
  576. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  577. int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
  578. popstack(stack);
  579. if (n < 0 || n >= (int)stack.size())
  580. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  581. valtype vch = stacktop(-n-1);
  582. if (opcode == OP_ROLL)
  583. stack.erase(stack.end()-n-1);
  584. stack.push_back(vch);
  585. }
  586. break;
  587. case OP_ROT:
  588. {
  589. // (x1 x2 x3 -- x2 x3 x1)
  590. // x2 x1 x3 after first swap
  591. // x2 x3 x1 after second swap
  592. if (stack.size() < 3)
  593. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  594. swap(stacktop(-3), stacktop(-2));
  595. swap(stacktop(-2), stacktop(-1));
  596. }
  597. break;
  598. case OP_SWAP:
  599. {
  600. // (x1 x2 -- x2 x1)
  601. if (stack.size() < 2)
  602. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  603. swap(stacktop(-2), stacktop(-1));
  604. }
  605. break;
  606. case OP_TUCK:
  607. {
  608. // (x1 x2 -- x2 x1 x2)
  609. if (stack.size() < 2)
  610. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  611. valtype vch = stacktop(-1);
  612. stack.insert(stack.end()-2, vch);
  613. }
  614. break;
  615. case OP_SIZE:
  616. {
  617. // (in -- in size)
  618. if (stack.size() < 1)
  619. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  620. CScriptNum bn(stacktop(-1).size());
  621. stack.push_back(bn.getvch());
  622. }
  623. break;
  624. //
  625. // Bitwise logic
  626. //
  627. case OP_EQUAL:
  628. case OP_EQUALVERIFY:
  629. //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
  630. {
  631. // (x1 x2 - bool)
  632. if (stack.size() < 2)
  633. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  634. valtype& vch1 = stacktop(-2);
  635. valtype& vch2 = stacktop(-1);
  636. bool fEqual = (vch1 == vch2);
  637. // OP_NOTEQUAL is disabled because it would be too easy to say
  638. // something like n != 1 and have some wiseguy pass in 1 with extra
  639. // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
  640. //if (opcode == OP_NOTEQUAL)
  641. // fEqual = !fEqual;
  642. popstack(stack);
  643. popstack(stack);
  644. stack.push_back(fEqual ? vchTrue : vchFalse);
  645. if (opcode == OP_EQUALVERIFY)
  646. {
  647. if (fEqual)
  648. popstack(stack);
  649. else
  650. return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
  651. }
  652. }
  653. break;
  654. //
  655. // Numeric
  656. //
  657. case OP_1ADD:
  658. case OP_1SUB:
  659. case OP_NEGATE:
  660. case OP_ABS:
  661. case OP_NOT:
  662. case OP_0NOTEQUAL:
  663. {
  664. // (in -- out)
  665. if (stack.size() < 1)
  666. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  667. CScriptNum bn(stacktop(-1), fRequireMinimal);
  668. switch (opcode)
  669. {
  670. case OP_1ADD: bn += bnOne; break;
  671. case OP_1SUB: bn -= bnOne; break;
  672. case OP_NEGATE: bn = -bn; break;
  673. case OP_ABS: if (bn < bnZero) bn = -bn; break;
  674. case OP_NOT: bn = (bn == bnZero); break;
  675. case OP_0NOTEQUAL: bn = (bn != bnZero); break;
  676. default: assert(!"invalid opcode"); break;
  677. }
  678. popstack(stack);
  679. stack.push_back(bn.getvch());
  680. }
  681. break;
  682. case OP_ADD:
  683. case OP_SUB:
  684. case OP_BOOLAND:
  685. case OP_BOOLOR:
  686. case OP_NUMEQUAL:
  687. case OP_NUMEQUALVERIFY:
  688. case OP_NUMNOTEQUAL:
  689. case OP_LESSTHAN:
  690. case OP_GREATERTHAN:
  691. case OP_LESSTHANOREQUAL:
  692. case OP_GREATERTHANOREQUAL:
  693. case OP_MIN:
  694. case OP_MAX:
  695. {
  696. // (x1 x2 -- out)
  697. if (stack.size() < 2)
  698. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  699. CScriptNum bn1(stacktop(-2), fRequireMinimal);
  700. CScriptNum bn2(stacktop(-1), fRequireMinimal);
  701. CScriptNum bn(0);
  702. switch (opcode)
  703. {
  704. case OP_ADD:
  705. bn = bn1 + bn2;
  706. break;
  707. case OP_SUB:
  708. bn = bn1 - bn2;
  709. break;
  710. case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
  711. case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
  712. case OP_NUMEQUAL: bn = (bn1 == bn2); break;
  713. case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
  714. case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
  715. case OP_LESSTHAN: bn = (bn1 < bn2); break;
  716. case OP_GREATERTHAN: bn = (bn1 > bn2); break;
  717. case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
  718. case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
  719. case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
  720. case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
  721. default: assert(!"invalid opcode"); break;
  722. }
  723. popstack(stack);
  724. popstack(stack);
  725. stack.push_back(bn.getvch());
  726. if (opcode == OP_NUMEQUALVERIFY)
  727. {
  728. if (CastToBool(stacktop(-1)))
  729. popstack(stack);
  730. else
  731. return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
  732. }
  733. }
  734. break;
  735. case OP_WITHIN:
  736. {
  737. // (x min max -- out)
  738. if (stack.size() < 3)
  739. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  740. CScriptNum bn1(stacktop(-3), fRequireMinimal);
  741. CScriptNum bn2(stacktop(-2), fRequireMinimal);
  742. CScriptNum bn3(stacktop(-1), fRequireMinimal);
  743. bool fValue = (bn2 <= bn1 && bn1 < bn3);
  744. popstack(stack);
  745. popstack(stack);
  746. popstack(stack);
  747. stack.push_back(fValue ? vchTrue : vchFalse);
  748. }
  749. break;
  750. //
  751. // Crypto
  752. //
  753. case OP_RIPEMD160:
  754. case OP_SHA1:
  755. case OP_SHA256:
  756. case OP_HASH160:
  757. case OP_HASH256:
  758. {
  759. // (in -- hash)
  760. if (stack.size() < 1)
  761. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  762. valtype& vch = stacktop(-1);
  763. valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
  764. if (opcode == OP_RIPEMD160)
  765. CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
  766. else if (opcode == OP_SHA1)
  767. CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
  768. else if (opcode == OP_SHA256)
  769. CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
  770. else if (opcode == OP_HASH160)
  771. CHash160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
  772. else if (opcode == OP_HASH256)
  773. CHash256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
  774. popstack(stack);
  775. stack.push_back(vchHash);
  776. }
  777. break;
  778. case OP_CODESEPARATOR:
  779. {
  780. // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected in pre-segwit
  781. // script, even in an unexecuted branch (this is checked above the opcode case statement).
  782. // Hash starts after the code separator
  783. pbegincodehash = pc;
  784. }
  785. break;
  786. case OP_CHECKSIG:
  787. case OP_CHECKSIGVERIFY:
  788. {
  789. // (sig pubkey -- bool)
  790. if (stack.size() < 2)
  791. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  792. valtype& vchSig = stacktop(-2);
  793. valtype& vchPubKey = stacktop(-1);
  794. // Subset of script starting at the most recent codeseparator
  795. CScript scriptCode(pbegincodehash, pend);
  796. // Drop the signature in pre-segwit scripts but not segwit scripts
  797. if (sigversion == SIGVERSION_BASE) {
  798. int found = scriptCode.FindAndDelete(CScript(vchSig));
  799. if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
  800. return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
  801. }
  802. if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
  803. //serror is set
  804. return false;
  805. }
  806. bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
  807. if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
  808. return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
  809. popstack(stack);
  810. popstack(stack);
  811. stack.push_back(fSuccess ? vchTrue : vchFalse);
  812. if (opcode == OP_CHECKSIGVERIFY)
  813. {
  814. if (fSuccess)
  815. popstack(stack);
  816. else
  817. return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
  818. }
  819. }
  820. break;
  821. case OP_CHECKMULTISIG:
  822. case OP_CHECKMULTISIGVERIFY:
  823. {
  824. // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
  825. int i = 1;
  826. if ((int)stack.size() < i)
  827. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  828. int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
  829. if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
  830. return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
  831. nOpCount += nKeysCount;
  832. if (nOpCount > MAX_OPS_PER_SCRIPT)
  833. return set_error(serror, SCRIPT_ERR_OP_COUNT);
  834. int ikey = ++i;
  835. // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
  836. // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
  837. int ikey2 = nKeysCount + 2;
  838. i += nKeysCount;
  839. if ((int)stack.size() < i)
  840. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  841. int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
  842. if (nSigsCount < 0 || nSigsCount > nKeysCount)
  843. return set_error(serror, SCRIPT_ERR_SIG_COUNT);
  844. int isig = ++i;
  845. i += nSigsCount;
  846. if ((int)stack.size() < i)
  847. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  848. // Subset of script starting at the most recent codeseparator
  849. CScript scriptCode(pbegincodehash, pend);
  850. // Drop the signature in pre-segwit scripts but not segwit scripts
  851. for (int k = 0; k < nSigsCount; k++)
  852. {
  853. valtype& vchSig = stacktop(-isig-k);
  854. if (sigversion == SIGVERSION_BASE) {
  855. int found = scriptCode.FindAndDelete(CScript(vchSig));
  856. if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
  857. return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
  858. }
  859. }
  860. bool fSuccess = true;
  861. while (fSuccess && nSigsCount > 0)
  862. {
  863. valtype& vchSig = stacktop(-isig);
  864. valtype& vchPubKey = stacktop(-ikey);
  865. // Note how this makes the exact order of pubkey/signature evaluation
  866. // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
  867. // See the script_(in)valid tests for details.
  868. if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
  869. // serror is set
  870. return false;
  871. }
  872. // Check signature
  873. bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
  874. if (fOk) {
  875. isig++;
  876. nSigsCount--;
  877. }
  878. ikey++;
  879. nKeysCount--;
  880. // If there are more signatures left than keys left,
  881. // then too many signatures have failed. Exit early,
  882. // without checking any further signatures.
  883. if (nSigsCount > nKeysCount)
  884. fSuccess = false;
  885. }
  886. // Clean up stack of actual arguments
  887. while (i-- > 1) {
  888. // If the operation failed, we require that all signatures must be empty vector
  889. if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
  890. return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
  891. if (ikey2 > 0)
  892. ikey2--;
  893. popstack(stack);
  894. }
  895. // A bug causes CHECKMULTISIG to consume one extra argument
  896. // whose contents were not checked in any way.
  897. //
  898. // Unfortunately this is a potential source of mutability,
  899. // so optionally verify it is exactly equal to zero prior
  900. // to removing it from the stack.
  901. if (stack.size() < 1)
  902. return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  903. if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
  904. return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
  905. popstack(stack);
  906. stack.push_back(fSuccess ? vchTrue : vchFalse);
  907. if (opcode == OP_CHECKMULTISIGVERIFY)
  908. {
  909. if (fSuccess)
  910. popstack(stack);
  911. else
  912. return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
  913. }
  914. }
  915. break;
  916. default:
  917. return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
  918. }
  919. // Size limits
  920. if (stack.size() + altstack.size() > MAX_STACK_SIZE)
  921. return set_error(serror, SCRIPT_ERR_STACK_SIZE);
  922. }
  923. }
  924. catch (...)
  925. {
  926. return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
  927. }
  928. if (!vfExec.empty())
  929. return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
  930. return set_success(serror);
  931. }
  932. namespace {
  933. /**
  934. * Wrapper that serializes like CTransaction, but with the modifications
  935. * required for the signature hash done in-place
  936. */
  937. class CTransactionSignatureSerializer {
  938. private:
  939. const CTransaction& txTo; //!< reference to the spending transaction (the one being serialized)
  940. const CScript& scriptCode; //!< output script being consumed
  941. const unsigned int nIn; //!< input index of txTo being signed
  942. const bool fAnyoneCanPay; //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
  943. const bool fHashSingle; //!< whether the hashtype is SIGHASH_SINGLE
  944. const bool fHashNone; //!< whether the hashtype is SIGHASH_NONE
  945. public:
  946. CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
  947. txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
  948. fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
  949. fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
  950. fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
  951. /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
  952. template<typename S>
  953. void SerializeScriptCode(S &s) const {
  954. CScript::const_iterator it = scriptCode.begin();
  955. CScript::const_iterator itBegin = it;
  956. opcodetype opcode;
  957. unsigned int nCodeSeparators = 0;
  958. while (scriptCode.GetOp(it, opcode)) {
  959. if (opcode == OP_CODESEPARATOR)
  960. nCodeSeparators++;
  961. }
  962. ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
  963. it = itBegin;
  964. while (scriptCode.GetOp(it, opcode)) {
  965. if (opcode == OP_CODESEPARATOR) {
  966. s.write((char*)&itBegin[0], it-itBegin-1);
  967. itBegin = it;
  968. }
  969. }
  970. if (itBegin != scriptCode.end())
  971. s.write((char*)&itBegin[0], it-itBegin);
  972. }
  973. /** Serialize an input of txTo */
  974. template<typename S>
  975. void SerializeInput(S &s, unsigned int nInput) const {
  976. // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
  977. if (fAnyoneCanPay)
  978. nInput = nIn;
  979. // Serialize the prevout
  980. ::Serialize(s, txTo.vin[nInput].prevout);
  981. // Serialize the script
  982. if (nInput != nIn)
  983. // Blank out other inputs' signatures
  984. ::Serialize(s, CScript());
  985. else
  986. SerializeScriptCode(s);
  987. // Serialize the nSequence
  988. if (nInput != nIn && (fHashSingle || fHashNone))
  989. // let the others update at will
  990. ::Serialize(s, (int)0);
  991. else
  992. ::Serialize(s, txTo.vin[nInput].nSequence);
  993. }
  994. /** Serialize an output of txTo */
  995. template<typename S>
  996. void SerializeOutput(S &s, unsigned int nOutput) const {
  997. if (fHashSingle && nOutput != nIn)
  998. // Do not lock-in the txout payee at other indices as txin
  999. ::Serialize(s, CTxOut());
  1000. else
  1001. ::Serialize(s, txTo.vout[nOutput]);
  1002. }
  1003. /** Serialize txTo */
  1004. template<typename S>
  1005. void Serialize(S &s) const {
  1006. // Serialize nVersion
  1007. ::Serialize(s, txTo.nVersion);
  1008. // Serialize vin
  1009. unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
  1010. ::WriteCompactSize(s, nInputs);
  1011. for (unsigned int nInput = 0; nInput < nInputs; nInput++)
  1012. SerializeInput(s, nInput);
  1013. // Serialize vout
  1014. unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
  1015. ::WriteCompactSize(s, nOutputs);
  1016. for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
  1017. SerializeOutput(s, nOutput);
  1018. // Serialize nLockTime
  1019. ::Serialize(s, txTo.nLockTime);
  1020. }
  1021. };
  1022. uint256 GetPrevoutHash(const CTransaction& txTo) {
  1023. CHashWriter ss(SER_GETHASH, 0);
  1024. for (const auto& txin : txTo.vin) {
  1025. ss << txin.prevout;
  1026. }
  1027. return ss.GetHash();
  1028. }
  1029. uint256 GetSequenceHash(const CTransaction& txTo) {
  1030. CHashWriter ss(SER_GETHASH, 0);
  1031. for (const auto& txin : txTo.vin) {
  1032. ss << txin.nSequence;
  1033. }
  1034. return ss.GetHash();
  1035. }
  1036. uint256 GetOutputsHash(const CTransaction& txTo) {
  1037. CHashWriter ss(SER_GETHASH, 0);
  1038. for (const auto& txout : txTo.vout) {
  1039. ss << txout;
  1040. }
  1041. return ss.GetHash();
  1042. }
  1043. } // namespace
  1044. PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo)
  1045. {
  1046. // Cache is calculated only for transactions with witness
  1047. if (txTo.HasWitness()) {
  1048. hashPrevouts = GetPrevoutHash(txTo);
  1049. hashSequence = GetSequenceHash(txTo);
  1050. hashOutputs = GetOutputsHash(txTo);
  1051. ready = true;
  1052. }
  1053. }
  1054. uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
  1055. {
  1056. assert(nIn < txTo.vin.size());
  1057. if (sigversion == SIGVERSION_WITNESS_V0) {
  1058. uint256 hashPrevouts;
  1059. uint256 hashSequence;
  1060. uint256 hashOutputs;
  1061. const bool cacheready = cache && cache->ready;
  1062. if (!(nHashType & SIGHASH_ANYONECANPAY)) {
  1063. hashPrevouts = cacheready ? cache->hashPrevouts : GetPrevoutHash(txTo);
  1064. }
  1065. if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
  1066. hashSequence = cacheready ? cache->hashSequence : GetSequenceHash(txTo);
  1067. }
  1068. if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
  1069. hashOutputs = cacheready ? cache->hashOutputs : GetOutputsHash(txTo);
  1070. } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
  1071. CHashWriter ss(SER_GETHASH, 0);
  1072. ss << txTo.vout[nIn];
  1073. hashOutputs = ss.GetHash();
  1074. }
  1075. CHashWriter ss(SER_GETHASH, 0);
  1076. // Version
  1077. ss << txTo.nVersion;
  1078. // Input prevouts/nSequence (none/all, depending on flags)
  1079. ss << hashPrevouts;
  1080. ss << hashSequence;
  1081. // The input being signed (replacing the scriptSig with scriptCode + amount)
  1082. // The prevout may already be contained in hashPrevout, and the nSequence
  1083. // may already be contain in hashSequence.
  1084. ss << txTo.vin[nIn].prevout;
  1085. ss << scriptCode;
  1086. ss << amount;
  1087. ss << txTo.vin[nIn].nSequence;
  1088. // Outputs (none/one/all, depending on flags)
  1089. ss << hashOutputs;
  1090. // Locktime
  1091. ss << txTo.nLockTime;
  1092. // Sighash type
  1093. ss << nHashType;
  1094. return ss.GetHash();
  1095. }
  1096. static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
  1097. // Check for invalid use of SIGHASH_SINGLE
  1098. if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
  1099. if (nIn >= txTo.vout.size()) {
  1100. // nOut out of range
  1101. return one;
  1102. }
  1103. }
  1104. // Wrapper to serialize only the necessary parts of the transaction being signed
  1105. CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
  1106. // Serialize and hash
  1107. CHashWriter ss(SER_GETHASH, 0);
  1108. ss << txTmp << nHashType;
  1109. return ss.GetHash();
  1110. }
  1111. bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
  1112. {
  1113. return pubkey.Verify(sighash, vchSig);
  1114. }
  1115. bool TransactionSignatureChecker::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
  1116. {
  1117. CPubKey pubkey(vchPubKey);
  1118. if (!pubkey.IsValid())
  1119. return false;
  1120. // Hash type is one byte tacked on to the end of the signature
  1121. std::vector<unsigned char> vchSig(vchSigIn);
  1122. if (vchSig.empty())
  1123. return false;
  1124. int nHashType = vchSig.back();
  1125. vchSig.pop_back();
  1126. uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
  1127. if (!VerifySignature(vchSig, pubkey, sighash))
  1128. return false;
  1129. return true;
  1130. }
  1131. bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const
  1132. {
  1133. // There are two kinds of nLockTime: lock-by-blockheight
  1134. // and lock-by-blocktime, distinguished by whether
  1135. // nLockTime < LOCKTIME_THRESHOLD.
  1136. //
  1137. // We want to compare apples to apples, so fail the script
  1138. // unless the type of nLockTime being tested is the same as
  1139. // the nLockTime in the transaction.
  1140. if (!(
  1141. (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
  1142. (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
  1143. ))
  1144. return false;
  1145. // Now that we know we're comparing apples-to-apples, the
  1146. // comparison is a simple numeric one.
  1147. if (nLockTime > (int64_t)txTo->nLockTime)
  1148. return false;
  1149. // Finally the nLockTime feature can be disabled and thus
  1150. // CHECKLOCKTIMEVERIFY bypassed if every txin has been
  1151. // finalized by setting nSequence to maxint. The
  1152. // transaction would be allowed into the blockchain, making
  1153. // the opcode ineffective.
  1154. //
  1155. // Testing if this vin is not final is sufficient to
  1156. // prevent this condition. Alternatively we could test all
  1157. // inputs, but testing just this input minimizes the data
  1158. // required to prove correct CHECKLOCKTIMEVERIFY execution.
  1159. if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
  1160. return false;
  1161. return true;
  1162. }
  1163. bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
  1164. {
  1165. // Relative lock times are supported by comparing the passed
  1166. // in operand to the sequence number of the input.
  1167. const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
  1168. // Fail if the transaction's version number is not set high
  1169. // enough to trigger BIP 68 rules.
  1170. if (static_cast<uint32_t>(txTo->nVersion) < 2)
  1171. return false;
  1172. // Sequence numbers with their most significant bit set are not
  1173. // consensus constrained. Testing that the transaction's sequence
  1174. // number do not have this bit set prevents using this property
  1175. // to get around a CHECKSEQUENCEVERIFY check.
  1176. if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
  1177. return false;
  1178. // Mask off any bits that do not have consensus-enforced meaning
  1179. // before doing the integer comparisons
  1180. const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
  1181. const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
  1182. const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
  1183. // There are two kinds of nSequence: lock-by-blockheight
  1184. // and lock-by-blocktime, distinguished by whether
  1185. // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
  1186. //
  1187. // We want to compare apples to apples, so fail the script
  1188. // unless the type of nSequenceMasked being tested is the same as
  1189. // the nSequenceMasked in the transaction.
  1190. if (!(
  1191. (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
  1192. (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
  1193. )) {
  1194. return false;
  1195. }
  1196. // Now that we know we're comparing apples-to-apples, the
  1197. // comparison is a simple numeric one.
  1198. if (nSequenceMasked > txToSequenceMasked)
  1199. return false;
  1200. return true;
  1201. }
  1202. static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
  1203. {
  1204. std::vector<std::vector<unsigned char> > stack;
  1205. CScript scriptPubKey;
  1206. if (witversion == 0) {
  1207. if (program.size() == 32) {
  1208. // Version 0 segregated witness program: SHA256(CScript) inside the program, CScript + inputs in witness
  1209. if (witness.stack.size() == 0) {
  1210. return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
  1211. }
  1212. scriptPubKey = CScript(witness.stack.back().begin(), witness.stack.back().end());
  1213. stack = std::vector<std::vector<unsigned char> >(witness.stack.begin(), witness.stack.end() - 1);
  1214. uint256 hashScriptPubKey;
  1215. CSHA256().Write(&scriptPubKey[0], scriptPubKey.size()).Finalize(hashScriptPubKey.begin());
  1216. if (memcmp(hashScriptPubKey.begin(), program.data(), 32)) {
  1217. return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
  1218. }
  1219. } else if (program.size() == 20) {
  1220. // Special case for pay-to-pubkeyhash; signature + pubkey in witness
  1221. if (witness.stack.size() != 2) {
  1222. return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
  1223. }
  1224. scriptPubKey << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
  1225. stack = witness.stack;
  1226. } else {
  1227. return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
  1228. }
  1229. } else if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
  1230. return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
  1231. } else {
  1232. // Higher version witness scripts return true for future softfork compatibility
  1233. return set_success(serror);
  1234. }
  1235. // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
  1236. for (unsigned int i = 0; i < stack.size(); i++) {
  1237. if (stack.at(i).size() > MAX_SCRIPT_ELEMENT_SIZE)
  1238. return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
  1239. }
  1240. if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_WITNESS_V0, serror)) {
  1241. return false;
  1242. }
  1243. // Scripts inside witness implicitly require cleanstack behaviour
  1244. if (stack.size() != 1)
  1245. return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
  1246. if (!CastToBool(stack.back()))
  1247. return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
  1248. return true;
  1249. }
  1250. bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
  1251. {
  1252. static const CScriptWitness emptyWitness;
  1253. if (witness == nullptr) {
  1254. witness = &emptyWitness;
  1255. }
  1256. bool hadWitness = false;
  1257. set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
  1258. if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
  1259. return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
  1260. }
  1261. std::vector<std::vector<unsigned char> > stack, stackCopy;
  1262. if (!EvalScript(stack, scriptSig, flags, checker, SIGVERSION_BASE, serror))
  1263. // serror is set
  1264. return false;
  1265. if (flags & SCRIPT_VERIFY_P2SH)
  1266. stackCopy = stack;
  1267. if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_BASE, serror))
  1268. // serror is set
  1269. return false;
  1270. if (stack.empty())
  1271. return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
  1272. if (CastToBool(stack.back()) == false)
  1273. return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
  1274. // Bare witness programs
  1275. int witnessversion;
  1276. std::vector<unsigned char> witnessprogram;
  1277. if (flags & SCRIPT_VERIFY_WITNESS) {
  1278. if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
  1279. hadWitness = true;
  1280. if (scriptSig.size() != 0) {
  1281. // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
  1282. return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
  1283. }
  1284. if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
  1285. return false;
  1286. }
  1287. // Bypass the cleanstack check at the end. The actual stack is obviously not clean
  1288. // for witness programs.
  1289. stack.resize(1);
  1290. }
  1291. }
  1292. // Additional validation for spend-to-script-hash transactions:
  1293. if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
  1294. {
  1295. // scriptSig must be literals-only or validation fails
  1296. if (!scriptSig.IsPushOnly())
  1297. return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
  1298. // Restore stack.
  1299. swap(stack, stackCopy);
  1300. // stack cannot be empty here, because if it was the
  1301. // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
  1302. // an empty stack and the EvalScript above would return false.
  1303. assert(!stack.empty());
  1304. const valtype& pubKeySerialized = stack.back();
  1305. CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
  1306. popstack(stack);
  1307. if (!EvalScript(stack, pubKey2, flags, checker, SIGVERSION_BASE, serror))
  1308. // serror is set
  1309. return false;
  1310. if (stack.empty())
  1311. return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
  1312. if (!CastToBool(stack.back()))
  1313. return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
  1314. // P2SH witness program
  1315. if (flags & SCRIPT_VERIFY_WITNESS) {
  1316. if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
  1317. hadWitness = true;
  1318. if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
  1319. // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
  1320. // reintroduce malleability.
  1321. return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
  1322. }
  1323. if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
  1324. return false;
  1325. }
  1326. // Bypass the cleanstack check at the end. The actual stack is obviously not clean
  1327. // for witness programs.
  1328. stack.resize(1);
  1329. }
  1330. }
  1331. }
  1332. // The CLEANSTACK check is only performed after potential P2SH evaluation,
  1333. // as the non-P2SH evaluation of a P2SH script will obviously not result in
  1334. // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
  1335. if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
  1336. // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
  1337. // would be possible, which is not a softfork (and P2SH should be one).
  1338. assert((flags & SCRIPT_VERIFY_P2SH) != 0);
  1339. assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
  1340. if (stack.size() != 1) {
  1341. return set_error(serror, SCRIPT_ERR_CLEANSTACK);
  1342. }
  1343. }
  1344. if (flags & SCRIPT_VERIFY_WITNESS) {
  1345. // We can't check for correct unexpected witness data if P2SH was off, so require
  1346. // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
  1347. // possible, which is not a softfork.
  1348. // assert((flags & SCRIPT_VERIFY_P2SH) != 0);
  1349. if (!hadWitness && !witness->IsNull()) {
  1350. return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
  1351. }
  1352. }
  1353. return set_success(serror);
  1354. }
  1355. size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness, int flags)
  1356. {
  1357. if (witversion == 0) {
  1358. if (witprogram.size() == 20)
  1359. return 1;
  1360. if (witprogram.size() == 32 && witness.stack.size() > 0) {
  1361. CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
  1362. return subscript.GetSigOpCount(true);
  1363. }
  1364. }
  1365. // Future flags may be implemented here.
  1366. return 0;
  1367. }
  1368. size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
  1369. {
  1370. static const CScriptWitness witnessEmpty;
  1371. if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
  1372. return 0;
  1373. }
  1374. // assert((flags & SCRIPT_VERIFY_P2SH) != 0);
  1375. int witnessversion;
  1376. std::vector<unsigned char> witnessprogram;
  1377. if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
  1378. return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty, flags);
  1379. }
  1380. if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
  1381. CScript::const_iterator pc = scriptSig.begin();
  1382. std::vector<unsigned char> data;
  1383. while (pc < scriptSig.end()) {
  1384. opcodetype opcode;
  1385. scriptSig.GetOp(pc, opcode, data);
  1386. }
  1387. CScript subscript(data.begin(), data.end());
  1388. if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
  1389. return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty, flags);
  1390. }
  1391. }
  1392. return 0;
  1393. }