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 50KB

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