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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin 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 "core.h"
  7. #include "crypto/ripemd160.h"
  8. #include "crypto/sha1.h"
  9. #include "crypto/sha2.h"
  10. #include "key.h"
  11. #include "script/script.h"
  12. #include "uint256.h"
  13. #include "util.h"
  14. using namespace std;
  15. typedef vector<unsigned char> valtype;
  16. static const valtype vchFalse(0);
  17. static const valtype vchZero(0);
  18. static const valtype vchTrue(1, 1);
  19. static const CScriptNum bnZero(0);
  20. static const CScriptNum bnOne(1);
  21. static const CScriptNum bnFalse(0);
  22. static const CScriptNum bnTrue(1);
  23. bool CastToBool(const valtype& vch)
  24. {
  25. for (unsigned int i = 0; i < vch.size(); i++)
  26. {
  27. if (vch[i] != 0)
  28. {
  29. // Can be negative zero
  30. if (i == vch.size()-1 && vch[i] == 0x80)
  31. return false;
  32. return true;
  33. }
  34. }
  35. return false;
  36. }
  37. //
  38. // Script is a stack machine (like Forth) that evaluates a predicate
  39. // returning a bool indicating valid or not. There are no loops.
  40. //
  41. #define stacktop(i) (stack.at(stack.size()+(i)))
  42. #define altstacktop(i) (altstack.at(altstack.size()+(i)))
  43. static inline void popstack(vector<valtype>& stack)
  44. {
  45. if (stack.empty())
  46. throw runtime_error("popstack() : stack empty");
  47. stack.pop_back();
  48. }
  49. bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
  50. if (vchPubKey.size() < 33)
  51. return error("Non-canonical public key: too short");
  52. if (vchPubKey[0] == 0x04) {
  53. if (vchPubKey.size() != 65)
  54. return error("Non-canonical public key: invalid length for uncompressed key");
  55. } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
  56. if (vchPubKey.size() != 33)
  57. return error("Non-canonical public key: invalid length for compressed key");
  58. } else {
  59. return error("Non-canonical public key: neither compressed nor uncompressed");
  60. }
  61. return true;
  62. }
  63. bool static IsDERSignature(const valtype &vchSig) {
  64. // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
  65. // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
  66. // Where R and S are not negative (their first byte has its highest bit not set), and not
  67. // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
  68. // in which case a single 0 byte is necessary and even required).
  69. if (vchSig.size() < 9)
  70. return error("Non-canonical signature: too short");
  71. if (vchSig.size() > 73)
  72. return error("Non-canonical signature: too long");
  73. if (vchSig[0] != 0x30)
  74. return error("Non-canonical signature: wrong type");
  75. if (vchSig[1] != vchSig.size()-3)
  76. return error("Non-canonical signature: wrong length marker");
  77. unsigned int nLenR = vchSig[3];
  78. if (5 + nLenR >= vchSig.size())
  79. return error("Non-canonical signature: S length misplaced");
  80. unsigned int nLenS = vchSig[5+nLenR];
  81. if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
  82. return error("Non-canonical signature: R+S length mismatch");
  83. const unsigned char *R = &vchSig[4];
  84. if (R[-2] != 0x02)
  85. return error("Non-canonical signature: R value type mismatch");
  86. if (nLenR == 0)
  87. return error("Non-canonical signature: R length is zero");
  88. if (R[0] & 0x80)
  89. return error("Non-canonical signature: R value negative");
  90. if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
  91. return error("Non-canonical signature: R value excessively padded");
  92. const unsigned char *S = &vchSig[6+nLenR];
  93. if (S[-2] != 0x02)
  94. return error("Non-canonical signature: S value type mismatch");
  95. if (nLenS == 0)
  96. return error("Non-canonical signature: S length is zero");
  97. if (S[0] & 0x80)
  98. return error("Non-canonical signature: S value negative");
  99. if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
  100. return error("Non-canonical signature: S value excessively padded");
  101. return true;
  102. }
  103. bool static IsLowDERSignature(const valtype &vchSig) {
  104. if (!IsDERSignature(vchSig)) {
  105. return false;
  106. }
  107. unsigned int nLenR = vchSig[3];
  108. unsigned int nLenS = vchSig[5+nLenR];
  109. const unsigned char *S = &vchSig[6+nLenR];
  110. // If the S value is above the order of the curve divided by two, its
  111. // complement modulo the order could have been used instead, which is
  112. // one byte shorter when encoded correctly.
  113. if (!CKey::CheckSignatureElement(S, nLenS, true))
  114. return error("Non-canonical signature: S value is unnecessarily high");
  115. return true;
  116. }
  117. bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
  118. if (vchSig.size() == 0) {
  119. return false;
  120. }
  121. unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
  122. if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
  123. return error("Non-canonical signature: unknown hashtype byte");
  124. return true;
  125. }
  126. bool static CheckSignatureEncoding(const valtype &vchSig, unsigned int flags) {
  127. if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsDERSignature(vchSig)) {
  128. return false;
  129. } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig)) {
  130. return false;
  131. } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
  132. return false;
  133. }
  134. return true;
  135. }
  136. bool static CheckPubKeyEncoding(const valtype &vchSig, unsigned int flags) {
  137. if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchSig)) {
  138. return false;
  139. }
  140. return true;
  141. }
  142. bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker)
  143. {
  144. CScript::const_iterator pc = script.begin();
  145. CScript::const_iterator pend = script.end();
  146. CScript::const_iterator pbegincodehash = script.begin();
  147. opcodetype opcode;
  148. valtype vchPushValue;
  149. vector<bool> vfExec;
  150. vector<valtype> altstack;
  151. if (script.size() > 10000)
  152. return false;
  153. int nOpCount = 0;
  154. try
  155. {
  156. while (pc < pend)
  157. {
  158. bool fExec = !count(vfExec.begin(), vfExec.end(), false);
  159. //
  160. // Read instruction
  161. //
  162. if (!script.GetOp(pc, opcode, vchPushValue))
  163. return false;
  164. if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
  165. return false;
  166. // Note how OP_RESERVED does not count towards the opcode limit.
  167. if (opcode > OP_16 && ++nOpCount > 201)
  168. return false;
  169. if (opcode == OP_CAT ||
  170. opcode == OP_SUBSTR ||
  171. opcode == OP_LEFT ||
  172. opcode == OP_RIGHT ||
  173. opcode == OP_INVERT ||
  174. opcode == OP_AND ||
  175. opcode == OP_OR ||
  176. opcode == OP_XOR ||
  177. opcode == OP_2MUL ||
  178. opcode == OP_2DIV ||
  179. opcode == OP_MUL ||
  180. opcode == OP_DIV ||
  181. opcode == OP_MOD ||
  182. opcode == OP_LSHIFT ||
  183. opcode == OP_RSHIFT)
  184. return false; // Disabled opcodes.
  185. if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
  186. stack.push_back(vchPushValue);
  187. else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
  188. switch (opcode)
  189. {
  190. //
  191. // Push value
  192. //
  193. case OP_1NEGATE:
  194. case OP_1:
  195. case OP_2:
  196. case OP_3:
  197. case OP_4:
  198. case OP_5:
  199. case OP_6:
  200. case OP_7:
  201. case OP_8:
  202. case OP_9:
  203. case OP_10:
  204. case OP_11:
  205. case OP_12:
  206. case OP_13:
  207. case OP_14:
  208. case OP_15:
  209. case OP_16:
  210. {
  211. // ( -- value)
  212. CScriptNum bn((int)opcode - (int)(OP_1 - 1));
  213. stack.push_back(bn.getvch());
  214. }
  215. break;
  216. //
  217. // Control
  218. //
  219. case OP_NOP:
  220. case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
  221. case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
  222. break;
  223. case OP_IF:
  224. case OP_NOTIF:
  225. {
  226. // <expression> if [statements] [else [statements]] endif
  227. bool fValue = false;
  228. if (fExec)
  229. {
  230. if (stack.size() < 1)
  231. return false;
  232. valtype& vch = stacktop(-1);
  233. fValue = CastToBool(vch);
  234. if (opcode == OP_NOTIF)
  235. fValue = !fValue;
  236. popstack(stack);
  237. }
  238. vfExec.push_back(fValue);
  239. }
  240. break;
  241. case OP_ELSE:
  242. {
  243. if (vfExec.empty())
  244. return false;
  245. vfExec.back() = !vfExec.back();
  246. }
  247. break;
  248. case OP_ENDIF:
  249. {
  250. if (vfExec.empty())
  251. return false;
  252. vfExec.pop_back();
  253. }
  254. break;
  255. case OP_VERIFY:
  256. {
  257. // (true -- ) or
  258. // (false -- false) and return
  259. if (stack.size() < 1)
  260. return false;
  261. bool fValue = CastToBool(stacktop(-1));
  262. if (fValue)
  263. popstack(stack);
  264. else
  265. return false;
  266. }
  267. break;
  268. case OP_RETURN:
  269. {
  270. return false;
  271. }
  272. break;
  273. //
  274. // Stack ops
  275. //
  276. case OP_TOALTSTACK:
  277. {
  278. if (stack.size() < 1)
  279. return false;
  280. altstack.push_back(stacktop(-1));
  281. popstack(stack);
  282. }
  283. break;
  284. case OP_FROMALTSTACK:
  285. {
  286. if (altstack.size() < 1)
  287. return false;
  288. stack.push_back(altstacktop(-1));
  289. popstack(altstack);
  290. }
  291. break;
  292. case OP_2DROP:
  293. {
  294. // (x1 x2 -- )
  295. if (stack.size() < 2)
  296. return false;
  297. popstack(stack);
  298. popstack(stack);
  299. }
  300. break;
  301. case OP_2DUP:
  302. {
  303. // (x1 x2 -- x1 x2 x1 x2)
  304. if (stack.size() < 2)
  305. return false;
  306. valtype vch1 = stacktop(-2);
  307. valtype vch2 = stacktop(-1);
  308. stack.push_back(vch1);
  309. stack.push_back(vch2);
  310. }
  311. break;
  312. case OP_3DUP:
  313. {
  314. // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
  315. if (stack.size() < 3)
  316. return false;
  317. valtype vch1 = stacktop(-3);
  318. valtype vch2 = stacktop(-2);
  319. valtype vch3 = stacktop(-1);
  320. stack.push_back(vch1);
  321. stack.push_back(vch2);
  322. stack.push_back(vch3);
  323. }
  324. break;
  325. case OP_2OVER:
  326. {
  327. // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
  328. if (stack.size() < 4)
  329. return false;
  330. valtype vch1 = stacktop(-4);
  331. valtype vch2 = stacktop(-3);
  332. stack.push_back(vch1);
  333. stack.push_back(vch2);
  334. }
  335. break;
  336. case OP_2ROT:
  337. {
  338. // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
  339. if (stack.size() < 6)
  340. return false;
  341. valtype vch1 = stacktop(-6);
  342. valtype vch2 = stacktop(-5);
  343. stack.erase(stack.end()-6, stack.end()-4);
  344. stack.push_back(vch1);
  345. stack.push_back(vch2);
  346. }
  347. break;
  348. case OP_2SWAP:
  349. {
  350. // (x1 x2 x3 x4 -- x3 x4 x1 x2)
  351. if (stack.size() < 4)
  352. return false;
  353. swap(stacktop(-4), stacktop(-2));
  354. swap(stacktop(-3), stacktop(-1));
  355. }
  356. break;
  357. case OP_IFDUP:
  358. {
  359. // (x - 0 | x x)
  360. if (stack.size() < 1)
  361. return false;
  362. valtype vch = stacktop(-1);
  363. if (CastToBool(vch))
  364. stack.push_back(vch);
  365. }
  366. break;
  367. case OP_DEPTH:
  368. {
  369. // -- stacksize
  370. CScriptNum bn(stack.size());
  371. stack.push_back(bn.getvch());
  372. }
  373. break;
  374. case OP_DROP:
  375. {
  376. // (x -- )
  377. if (stack.size() < 1)
  378. return false;
  379. popstack(stack);
  380. }
  381. break;
  382. case OP_DUP:
  383. {
  384. // (x -- x x)
  385. if (stack.size() < 1)
  386. return false;
  387. valtype vch = stacktop(-1);
  388. stack.push_back(vch);
  389. }
  390. break;
  391. case OP_NIP:
  392. {
  393. // (x1 x2 -- x2)
  394. if (stack.size() < 2)
  395. return false;
  396. stack.erase(stack.end() - 2);
  397. }
  398. break;
  399. case OP_OVER:
  400. {
  401. // (x1 x2 -- x1 x2 x1)
  402. if (stack.size() < 2)
  403. return false;
  404. valtype vch = stacktop(-2);
  405. stack.push_back(vch);
  406. }
  407. break;
  408. case OP_PICK:
  409. case OP_ROLL:
  410. {
  411. // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
  412. // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
  413. if (stack.size() < 2)
  414. return false;
  415. int n = CScriptNum(stacktop(-1)).getint();
  416. popstack(stack);
  417. if (n < 0 || n >= (int)stack.size())
  418. return false;
  419. valtype vch = stacktop(-n-1);
  420. if (opcode == OP_ROLL)
  421. stack.erase(stack.end()-n-1);
  422. stack.push_back(vch);
  423. }
  424. break;
  425. case OP_ROT:
  426. {
  427. // (x1 x2 x3 -- x2 x3 x1)
  428. // x2 x1 x3 after first swap
  429. // x2 x3 x1 after second swap
  430. if (stack.size() < 3)
  431. return false;
  432. swap(stacktop(-3), stacktop(-2));
  433. swap(stacktop(-2), stacktop(-1));
  434. }
  435. break;
  436. case OP_SWAP:
  437. {
  438. // (x1 x2 -- x2 x1)
  439. if (stack.size() < 2)
  440. return false;
  441. swap(stacktop(-2), stacktop(-1));
  442. }
  443. break;
  444. case OP_TUCK:
  445. {
  446. // (x1 x2 -- x2 x1 x2)
  447. if (stack.size() < 2)
  448. return false;
  449. valtype vch = stacktop(-1);
  450. stack.insert(stack.end()-2, vch);
  451. }
  452. break;
  453. case OP_SIZE:
  454. {
  455. // (in -- in size)
  456. if (stack.size() < 1)
  457. return false;
  458. CScriptNum bn(stacktop(-1).size());
  459. stack.push_back(bn.getvch());
  460. }
  461. break;
  462. //
  463. // Bitwise logic
  464. //
  465. case OP_EQUAL:
  466. case OP_EQUALVERIFY:
  467. //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
  468. {
  469. // (x1 x2 - bool)
  470. if (stack.size() < 2)
  471. return false;
  472. valtype& vch1 = stacktop(-2);
  473. valtype& vch2 = stacktop(-1);
  474. bool fEqual = (vch1 == vch2);
  475. // OP_NOTEQUAL is disabled because it would be too easy to say
  476. // something like n != 1 and have some wiseguy pass in 1 with extra
  477. // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
  478. //if (opcode == OP_NOTEQUAL)
  479. // fEqual = !fEqual;
  480. popstack(stack);
  481. popstack(stack);
  482. stack.push_back(fEqual ? vchTrue : vchFalse);
  483. if (opcode == OP_EQUALVERIFY)
  484. {
  485. if (fEqual)
  486. popstack(stack);
  487. else
  488. return false;
  489. }
  490. }
  491. break;
  492. //
  493. // Numeric
  494. //
  495. case OP_1ADD:
  496. case OP_1SUB:
  497. case OP_NEGATE:
  498. case OP_ABS:
  499. case OP_NOT:
  500. case OP_0NOTEQUAL:
  501. {
  502. // (in -- out)
  503. if (stack.size() < 1)
  504. return false;
  505. CScriptNum bn(stacktop(-1));
  506. switch (opcode)
  507. {
  508. case OP_1ADD: bn += bnOne; break;
  509. case OP_1SUB: bn -= bnOne; break;
  510. case OP_NEGATE: bn = -bn; break;
  511. case OP_ABS: if (bn < bnZero) bn = -bn; break;
  512. case OP_NOT: bn = (bn == bnZero); break;
  513. case OP_0NOTEQUAL: bn = (bn != bnZero); break;
  514. default: assert(!"invalid opcode"); break;
  515. }
  516. popstack(stack);
  517. stack.push_back(bn.getvch());
  518. }
  519. break;
  520. case OP_ADD:
  521. case OP_SUB:
  522. case OP_BOOLAND:
  523. case OP_BOOLOR:
  524. case OP_NUMEQUAL:
  525. case OP_NUMEQUALVERIFY:
  526. case OP_NUMNOTEQUAL:
  527. case OP_LESSTHAN:
  528. case OP_GREATERTHAN:
  529. case OP_LESSTHANOREQUAL:
  530. case OP_GREATERTHANOREQUAL:
  531. case OP_MIN:
  532. case OP_MAX:
  533. {
  534. // (x1 x2 -- out)
  535. if (stack.size() < 2)
  536. return false;
  537. CScriptNum bn1(stacktop(-2));
  538. CScriptNum bn2(stacktop(-1));
  539. CScriptNum bn(0);
  540. switch (opcode)
  541. {
  542. case OP_ADD:
  543. bn = bn1 + bn2;
  544. break;
  545. case OP_SUB:
  546. bn = bn1 - bn2;
  547. break;
  548. case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
  549. case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
  550. case OP_NUMEQUAL: bn = (bn1 == bn2); break;
  551. case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
  552. case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
  553. case OP_LESSTHAN: bn = (bn1 < bn2); break;
  554. case OP_GREATERTHAN: bn = (bn1 > bn2); break;
  555. case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
  556. case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
  557. case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
  558. case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
  559. default: assert(!"invalid opcode"); break;
  560. }
  561. popstack(stack);
  562. popstack(stack);
  563. stack.push_back(bn.getvch());
  564. if (opcode == OP_NUMEQUALVERIFY)
  565. {
  566. if (CastToBool(stacktop(-1)))
  567. popstack(stack);
  568. else
  569. return false;
  570. }
  571. }
  572. break;
  573. case OP_WITHIN:
  574. {
  575. // (x min max -- out)
  576. if (stack.size() < 3)
  577. return false;
  578. CScriptNum bn1(stacktop(-3));
  579. CScriptNum bn2(stacktop(-2));
  580. CScriptNum bn3(stacktop(-1));
  581. bool fValue = (bn2 <= bn1 && bn1 < bn3);
  582. popstack(stack);
  583. popstack(stack);
  584. popstack(stack);
  585. stack.push_back(fValue ? vchTrue : vchFalse);
  586. }
  587. break;
  588. //
  589. // Crypto
  590. //
  591. case OP_RIPEMD160:
  592. case OP_SHA1:
  593. case OP_SHA256:
  594. case OP_HASH160:
  595. case OP_HASH256:
  596. {
  597. // (in -- hash)
  598. if (stack.size() < 1)
  599. return false;
  600. valtype& vch = stacktop(-1);
  601. valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
  602. if (opcode == OP_RIPEMD160)
  603. CRIPEMD160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
  604. else if (opcode == OP_SHA1)
  605. CSHA1().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
  606. else if (opcode == OP_SHA256)
  607. CSHA256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
  608. else if (opcode == OP_HASH160)
  609. CHash160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
  610. else if (opcode == OP_HASH256)
  611. CHash256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
  612. popstack(stack);
  613. stack.push_back(vchHash);
  614. }
  615. break;
  616. case OP_CODESEPARATOR:
  617. {
  618. // Hash starts after the code separator
  619. pbegincodehash = pc;
  620. }
  621. break;
  622. case OP_CHECKSIG:
  623. case OP_CHECKSIGVERIFY:
  624. {
  625. // (sig pubkey -- bool)
  626. if (stack.size() < 2)
  627. return false;
  628. valtype& vchSig = stacktop(-2);
  629. valtype& vchPubKey = stacktop(-1);
  630. // Subset of script starting at the most recent codeseparator
  631. CScript scriptCode(pbegincodehash, pend);
  632. // Drop the signature, since there's no way for a signature to sign itself
  633. scriptCode.FindAndDelete(CScript(vchSig));
  634. if (!CheckSignatureEncoding(vchSig, flags)) {
  635. return false;
  636. }
  637. bool fSuccess = CheckPubKeyEncoding(vchPubKey, flags) && checker.CheckSig(vchSig, vchPubKey, scriptCode);
  638. popstack(stack);
  639. popstack(stack);
  640. stack.push_back(fSuccess ? vchTrue : vchFalse);
  641. if (opcode == OP_CHECKSIGVERIFY)
  642. {
  643. if (fSuccess)
  644. popstack(stack);
  645. else
  646. return false;
  647. }
  648. }
  649. break;
  650. case OP_CHECKMULTISIG:
  651. case OP_CHECKMULTISIGVERIFY:
  652. {
  653. // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
  654. int i = 1;
  655. if ((int)stack.size() < i)
  656. return false;
  657. int nKeysCount = CScriptNum(stacktop(-i)).getint();
  658. if (nKeysCount < 0 || nKeysCount > 20)
  659. return false;
  660. nOpCount += nKeysCount;
  661. if (nOpCount > 201)
  662. return false;
  663. int ikey = ++i;
  664. i += nKeysCount;
  665. if ((int)stack.size() < i)
  666. return false;
  667. int nSigsCount = CScriptNum(stacktop(-i)).getint();
  668. if (nSigsCount < 0 || nSigsCount > nKeysCount)
  669. return false;
  670. int isig = ++i;
  671. i += nSigsCount;
  672. if ((int)stack.size() < i)
  673. return false;
  674. // Subset of script starting at the most recent codeseparator
  675. CScript scriptCode(pbegincodehash, pend);
  676. // Drop the signatures, since there's no way for a signature to sign itself
  677. for (int k = 0; k < nSigsCount; k++)
  678. {
  679. valtype& vchSig = stacktop(-isig-k);
  680. scriptCode.FindAndDelete(CScript(vchSig));
  681. }
  682. bool fSuccess = true;
  683. while (fSuccess && nSigsCount > 0)
  684. {
  685. valtype& vchSig = stacktop(-isig);
  686. valtype& vchPubKey = stacktop(-ikey);
  687. if (!CheckSignatureEncoding(vchSig, flags)) {
  688. return false;
  689. }
  690. // Check signature
  691. bool fOk = CheckPubKeyEncoding(vchPubKey, flags) && checker.CheckSig(vchSig, vchPubKey, scriptCode);
  692. if (fOk) {
  693. isig++;
  694. nSigsCount--;
  695. }
  696. ikey++;
  697. nKeysCount--;
  698. // If there are more signatures left than keys left,
  699. // then too many signatures have failed
  700. if (nSigsCount > nKeysCount)
  701. fSuccess = false;
  702. }
  703. // Clean up stack of actual arguments
  704. while (i-- > 1)
  705. popstack(stack);
  706. // A bug causes CHECKMULTISIG to consume one extra argument
  707. // whose contents were not checked in any way.
  708. //
  709. // Unfortunately this is a potential source of mutability,
  710. // so optionally verify it is exactly equal to zero prior
  711. // to removing it from the stack.
  712. if (stack.size() < 1)
  713. return false;
  714. if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
  715. return error("CHECKMULTISIG dummy argument not null");
  716. popstack(stack);
  717. stack.push_back(fSuccess ? vchTrue : vchFalse);
  718. if (opcode == OP_CHECKMULTISIGVERIFY)
  719. {
  720. if (fSuccess)
  721. popstack(stack);
  722. else
  723. return false;
  724. }
  725. }
  726. break;
  727. default:
  728. return false;
  729. }
  730. // Size limits
  731. if (stack.size() + altstack.size() > 1000)
  732. return false;
  733. }
  734. }
  735. catch (...)
  736. {
  737. return false;
  738. }
  739. if (!vfExec.empty())
  740. return false;
  741. return true;
  742. }
  743. namespace {
  744. /** Wrapper that serializes like CTransaction, but with the modifications
  745. * required for the signature hash done in-place
  746. */
  747. class CTransactionSignatureSerializer {
  748. private:
  749. const CTransaction &txTo; // reference to the spending transaction (the one being serialized)
  750. const CScript &scriptCode; // output script being consumed
  751. const unsigned int nIn; // input index of txTo being signed
  752. const bool fAnyoneCanPay; // whether the hashtype has the SIGHASH_ANYONECANPAY flag set
  753. const bool fHashSingle; // whether the hashtype is SIGHASH_SINGLE
  754. const bool fHashNone; // whether the hashtype is SIGHASH_NONE
  755. public:
  756. CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
  757. txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
  758. fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
  759. fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
  760. fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
  761. /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
  762. template<typename S>
  763. void SerializeScriptCode(S &s, int nType, int nVersion) const {
  764. CScript::const_iterator it = scriptCode.begin();
  765. CScript::const_iterator itBegin = it;
  766. opcodetype opcode;
  767. unsigned int nCodeSeparators = 0;
  768. while (scriptCode.GetOp(it, opcode)) {
  769. if (opcode == OP_CODESEPARATOR)
  770. nCodeSeparators++;
  771. }
  772. ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
  773. it = itBegin;
  774. while (scriptCode.GetOp(it, opcode)) {
  775. if (opcode == OP_CODESEPARATOR) {
  776. s.write((char*)&itBegin[0], it-itBegin-1);
  777. itBegin = it;
  778. }
  779. }
  780. if (itBegin != scriptCode.end())
  781. s.write((char*)&itBegin[0], it-itBegin);
  782. }
  783. /** Serialize an input of txTo */
  784. template<typename S>
  785. void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const {
  786. // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
  787. if (fAnyoneCanPay)
  788. nInput = nIn;
  789. // Serialize the prevout
  790. ::Serialize(s, txTo.vin[nInput].prevout, nType, nVersion);
  791. // Serialize the script
  792. if (nInput != nIn)
  793. // Blank out other inputs' signatures
  794. ::Serialize(s, CScript(), nType, nVersion);
  795. else
  796. SerializeScriptCode(s, nType, nVersion);
  797. // Serialize the nSequence
  798. if (nInput != nIn && (fHashSingle || fHashNone))
  799. // let the others update at will
  800. ::Serialize(s, (int)0, nType, nVersion);
  801. else
  802. ::Serialize(s, txTo.vin[nInput].nSequence, nType, nVersion);
  803. }
  804. /** Serialize an output of txTo */
  805. template<typename S>
  806. void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const {
  807. if (fHashSingle && nOutput != nIn)
  808. // Do not lock-in the txout payee at other indices as txin
  809. ::Serialize(s, CTxOut(), nType, nVersion);
  810. else
  811. ::Serialize(s, txTo.vout[nOutput], nType, nVersion);
  812. }
  813. /** Serialize txTo */
  814. template<typename S>
  815. void Serialize(S &s, int nType, int nVersion) const {
  816. // Serialize nVersion
  817. ::Serialize(s, txTo.nVersion, nType, nVersion);
  818. // Serialize vin
  819. unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
  820. ::WriteCompactSize(s, nInputs);
  821. for (unsigned int nInput = 0; nInput < nInputs; nInput++)
  822. SerializeInput(s, nInput, nType, nVersion);
  823. // Serialize vout
  824. unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
  825. ::WriteCompactSize(s, nOutputs);
  826. for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
  827. SerializeOutput(s, nOutput, nType, nVersion);
  828. // Serialie nLockTime
  829. ::Serialize(s, txTo.nLockTime, nType, nVersion);
  830. }
  831. };
  832. } // anon namespace
  833. uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
  834. {
  835. if (nIn >= txTo.vin.size()) {
  836. LogPrintf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
  837. return 1;
  838. }
  839. // Check for invalid use of SIGHASH_SINGLE
  840. if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
  841. if (nIn >= txTo.vout.size()) {
  842. LogPrintf("ERROR: SignatureHash() : nOut=%d out of range\n", nIn);
  843. return 1;
  844. }
  845. }
  846. // Wrapper to serialize only the necessary parts of the transaction being signed
  847. CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
  848. // Serialize and hash
  849. CHashWriter ss(SER_GETHASH, 0);
  850. ss << txTmp << nHashType;
  851. return ss.GetHash();
  852. }
  853. bool SignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
  854. {
  855. return pubkey.Verify(sighash, vchSig);
  856. }
  857. bool SignatureChecker::CheckSig(const vector<unsigned char>& vchSigIn, const vector<unsigned char>& vchPubKey, const CScript& scriptCode) const
  858. {
  859. CPubKey pubkey(vchPubKey);
  860. if (!pubkey.IsValid())
  861. return false;
  862. // Hash type is one byte tacked on to the end of the signature
  863. vector<unsigned char> vchSig(vchSigIn);
  864. if (vchSig.empty())
  865. return false;
  866. int nHashType = vchSig.back();
  867. vchSig.pop_back();
  868. uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
  869. if (!VerifySignature(vchSig, pubkey, sighash))
  870. return false;
  871. return true;
  872. }
  873. bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker)
  874. {
  875. vector<vector<unsigned char> > stack, stackCopy;
  876. if (!EvalScript(stack, scriptSig, flags, checker))
  877. return false;
  878. if (flags & SCRIPT_VERIFY_P2SH)
  879. stackCopy = stack;
  880. if (!EvalScript(stack, scriptPubKey, flags, checker))
  881. return false;
  882. if (stack.empty())
  883. return false;
  884. if (CastToBool(stack.back()) == false)
  885. return false;
  886. // Additional validation for spend-to-script-hash transactions:
  887. if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
  888. {
  889. if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
  890. return false; // or validation fails
  891. // stackCopy cannot be empty here, because if it was the
  892. // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
  893. // an empty stack and the EvalScript above would return false.
  894. assert(!stackCopy.empty());
  895. const valtype& pubKeySerialized = stackCopy.back();
  896. CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
  897. popstack(stackCopy);
  898. if (!EvalScript(stackCopy, pubKey2, flags, checker))
  899. return false;
  900. if (stackCopy.empty())
  901. return false;
  902. return CastToBool(stackCopy.back());
  903. }
  904. return true;
  905. }