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

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