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.

script.cpp 70KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2013 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "script.h"
  6. #include "core.h"
  7. #include "hash.h"
  8. #include "key.h"
  9. #include "keystore.h"
  10. #include "crypto/sha1.h"
  11. #include "crypto/sha2.h"
  12. #include "crypto/ripemd160.h"
  13. #include "sync.h"
  14. #include "uint256.h"
  15. #include "util.h"
  16. #include <boost/foreach.hpp>
  17. #include <boost/tuple/tuple.hpp>
  18. #include <boost/tuple/tuple_comparison.hpp>
  19. using namespace std;
  20. using namespace boost;
  21. typedef vector<unsigned char> valtype;
  22. static const valtype vchFalse(0);
  23. static const valtype vchZero(0);
  24. static const valtype vchTrue(1, 1);
  25. static const CScriptNum bnZero(0);
  26. static const CScriptNum bnOne(1);
  27. static const CScriptNum bnFalse(0);
  28. static const CScriptNum bnTrue(1);
  29. bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
  30. bool CastToBool(const valtype& vch)
  31. {
  32. for (unsigned int i = 0; i < vch.size(); i++)
  33. {
  34. if (vch[i] != 0)
  35. {
  36. // Can be negative zero
  37. if (i == vch.size()-1 && vch[i] == 0x80)
  38. return false;
  39. return true;
  40. }
  41. }
  42. return false;
  43. }
  44. //
  45. // Script is a stack machine (like Forth) that evaluates a predicate
  46. // returning a bool indicating valid or not. There are no loops.
  47. //
  48. #define stacktop(i) (stack.at(stack.size()+(i)))
  49. #define altstacktop(i) (altstack.at(altstack.size()+(i)))
  50. static inline void popstack(vector<valtype>& stack)
  51. {
  52. if (stack.empty())
  53. throw runtime_error("popstack() : stack empty");
  54. stack.pop_back();
  55. }
  56. const char* GetTxnOutputType(txnouttype t)
  57. {
  58. switch (t)
  59. {
  60. case TX_NONSTANDARD: return "nonstandard";
  61. case TX_PUBKEY: return "pubkey";
  62. case TX_PUBKEYHASH: return "pubkeyhash";
  63. case TX_SCRIPTHASH: return "scripthash";
  64. case TX_MULTISIG: return "multisig";
  65. case TX_NULL_DATA: return "nulldata";
  66. }
  67. return NULL;
  68. }
  69. const char* GetOpName(opcodetype opcode)
  70. {
  71. switch (opcode)
  72. {
  73. // push value
  74. case OP_0 : return "0";
  75. case OP_PUSHDATA1 : return "OP_PUSHDATA1";
  76. case OP_PUSHDATA2 : return "OP_PUSHDATA2";
  77. case OP_PUSHDATA4 : return "OP_PUSHDATA4";
  78. case OP_1NEGATE : return "-1";
  79. case OP_RESERVED : return "OP_RESERVED";
  80. case OP_1 : return "1";
  81. case OP_2 : return "2";
  82. case OP_3 : return "3";
  83. case OP_4 : return "4";
  84. case OP_5 : return "5";
  85. case OP_6 : return "6";
  86. case OP_7 : return "7";
  87. case OP_8 : return "8";
  88. case OP_9 : return "9";
  89. case OP_10 : return "10";
  90. case OP_11 : return "11";
  91. case OP_12 : return "12";
  92. case OP_13 : return "13";
  93. case OP_14 : return "14";
  94. case OP_15 : return "15";
  95. case OP_16 : return "16";
  96. // control
  97. case OP_NOP : return "OP_NOP";
  98. case OP_VER : return "OP_VER";
  99. case OP_IF : return "OP_IF";
  100. case OP_NOTIF : return "OP_NOTIF";
  101. case OP_VERIF : return "OP_VERIF";
  102. case OP_VERNOTIF : return "OP_VERNOTIF";
  103. case OP_ELSE : return "OP_ELSE";
  104. case OP_ENDIF : return "OP_ENDIF";
  105. case OP_VERIFY : return "OP_VERIFY";
  106. case OP_RETURN : return "OP_RETURN";
  107. // stack ops
  108. case OP_TOALTSTACK : return "OP_TOALTSTACK";
  109. case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
  110. case OP_2DROP : return "OP_2DROP";
  111. case OP_2DUP : return "OP_2DUP";
  112. case OP_3DUP : return "OP_3DUP";
  113. case OP_2OVER : return "OP_2OVER";
  114. case OP_2ROT : return "OP_2ROT";
  115. case OP_2SWAP : return "OP_2SWAP";
  116. case OP_IFDUP : return "OP_IFDUP";
  117. case OP_DEPTH : return "OP_DEPTH";
  118. case OP_DROP : return "OP_DROP";
  119. case OP_DUP : return "OP_DUP";
  120. case OP_NIP : return "OP_NIP";
  121. case OP_OVER : return "OP_OVER";
  122. case OP_PICK : return "OP_PICK";
  123. case OP_ROLL : return "OP_ROLL";
  124. case OP_ROT : return "OP_ROT";
  125. case OP_SWAP : return "OP_SWAP";
  126. case OP_TUCK : return "OP_TUCK";
  127. // splice ops
  128. case OP_CAT : return "OP_CAT";
  129. case OP_SUBSTR : return "OP_SUBSTR";
  130. case OP_LEFT : return "OP_LEFT";
  131. case OP_RIGHT : return "OP_RIGHT";
  132. case OP_SIZE : return "OP_SIZE";
  133. // bit logic
  134. case OP_INVERT : return "OP_INVERT";
  135. case OP_AND : return "OP_AND";
  136. case OP_OR : return "OP_OR";
  137. case OP_XOR : return "OP_XOR";
  138. case OP_EQUAL : return "OP_EQUAL";
  139. case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
  140. case OP_RESERVED1 : return "OP_RESERVED1";
  141. case OP_RESERVED2 : return "OP_RESERVED2";
  142. // numeric
  143. case OP_1ADD : return "OP_1ADD";
  144. case OP_1SUB : return "OP_1SUB";
  145. case OP_2MUL : return "OP_2MUL";
  146. case OP_2DIV : return "OP_2DIV";
  147. case OP_NEGATE : return "OP_NEGATE";
  148. case OP_ABS : return "OP_ABS";
  149. case OP_NOT : return "OP_NOT";
  150. case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
  151. case OP_ADD : return "OP_ADD";
  152. case OP_SUB : return "OP_SUB";
  153. case OP_MUL : return "OP_MUL";
  154. case OP_DIV : return "OP_DIV";
  155. case OP_MOD : return "OP_MOD";
  156. case OP_LSHIFT : return "OP_LSHIFT";
  157. case OP_RSHIFT : return "OP_RSHIFT";
  158. case OP_BOOLAND : return "OP_BOOLAND";
  159. case OP_BOOLOR : return "OP_BOOLOR";
  160. case OP_NUMEQUAL : return "OP_NUMEQUAL";
  161. case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
  162. case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
  163. case OP_LESSTHAN : return "OP_LESSTHAN";
  164. case OP_GREATERTHAN : return "OP_GREATERTHAN";
  165. case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
  166. case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
  167. case OP_MIN : return "OP_MIN";
  168. case OP_MAX : return "OP_MAX";
  169. case OP_WITHIN : return "OP_WITHIN";
  170. // crypto
  171. case OP_RIPEMD160 : return "OP_RIPEMD160";
  172. case OP_SHA1 : return "OP_SHA1";
  173. case OP_SHA256 : return "OP_SHA256";
  174. case OP_HASH160 : return "OP_HASH160";
  175. case OP_HASH256 : return "OP_HASH256";
  176. case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
  177. case OP_CHECKSIG : return "OP_CHECKSIG";
  178. case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
  179. case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
  180. case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
  181. // expanson
  182. case OP_NOP1 : return "OP_NOP1";
  183. case OP_NOP2 : return "OP_NOP2";
  184. case OP_NOP3 : return "OP_NOP3";
  185. case OP_NOP4 : return "OP_NOP4";
  186. case OP_NOP5 : return "OP_NOP5";
  187. case OP_NOP6 : return "OP_NOP6";
  188. case OP_NOP7 : return "OP_NOP7";
  189. case OP_NOP8 : return "OP_NOP8";
  190. case OP_NOP9 : return "OP_NOP9";
  191. case OP_NOP10 : return "OP_NOP10";
  192. case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
  193. // Note:
  194. // The template matching params OP_SMALLDATA/etc are defined in opcodetype enum
  195. // as kind of implementation hack, they are *NOT* real opcodes. If found in real
  196. // Script, just let the default: case deal with them.
  197. default:
  198. return "OP_UNKNOWN";
  199. }
  200. }
  201. bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
  202. if (!(flags & SCRIPT_VERIFY_STRICTENC))
  203. return true;
  204. if (vchPubKey.size() < 33)
  205. return error("Non-canonical public key: too short");
  206. if (vchPubKey[0] == 0x04) {
  207. if (vchPubKey.size() != 65)
  208. return error("Non-canonical public key: invalid length for uncompressed key");
  209. } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
  210. if (vchPubKey.size() != 33)
  211. return error("Non-canonical public key: invalid length for compressed key");
  212. } else {
  213. return error("Non-canonical public key: compressed nor uncompressed");
  214. }
  215. return true;
  216. }
  217. bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
  218. if (!(flags & SCRIPT_VERIFY_STRICTENC))
  219. return true;
  220. // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
  221. // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
  222. // Where R and S are not negative (their first byte has its highest bit not set), and not
  223. // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
  224. // in which case a single 0 byte is necessary and even required).
  225. if (vchSig.size() < 9)
  226. return error("Non-canonical signature: too short");
  227. if (vchSig.size() > 73)
  228. return error("Non-canonical signature: too long");
  229. unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
  230. if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
  231. return error("Non-canonical signature: unknown hashtype byte");
  232. if (vchSig[0] != 0x30)
  233. return error("Non-canonical signature: wrong type");
  234. if (vchSig[1] != vchSig.size()-3)
  235. return error("Non-canonical signature: wrong length marker");
  236. unsigned int nLenR = vchSig[3];
  237. if (5 + nLenR >= vchSig.size())
  238. return error("Non-canonical signature: S length misplaced");
  239. unsigned int nLenS = vchSig[5+nLenR];
  240. if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
  241. return error("Non-canonical signature: R+S length mismatch");
  242. const unsigned char *R = &vchSig[4];
  243. if (R[-2] != 0x02)
  244. return error("Non-canonical signature: R value type mismatch");
  245. if (nLenR == 0)
  246. return error("Non-canonical signature: R length is zero");
  247. if (R[0] & 0x80)
  248. return error("Non-canonical signature: R value negative");
  249. if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
  250. return error("Non-canonical signature: R value excessively padded");
  251. const unsigned char *S = &vchSig[6+nLenR];
  252. if (S[-2] != 0x02)
  253. return error("Non-canonical signature: S value type mismatch");
  254. if (nLenS == 0)
  255. return error("Non-canonical signature: S length is zero");
  256. if (S[0] & 0x80)
  257. return error("Non-canonical signature: S value negative");
  258. if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
  259. return error("Non-canonical signature: S value excessively padded");
  260. if (flags & SCRIPT_VERIFY_LOW_S) {
  261. // If the S value is above the order of the curve divided by two, its
  262. // complement modulo the order could have been used instead, which is
  263. // one byte shorter when encoded correctly.
  264. if (!CKey::CheckSignatureElement(S, nLenS, true))
  265. return error("Non-canonical signature: S value is unnecessarily high");
  266. }
  267. return true;
  268. }
  269. bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
  270. {
  271. CScript::const_iterator pc = script.begin();
  272. CScript::const_iterator pend = script.end();
  273. CScript::const_iterator pbegincodehash = script.begin();
  274. opcodetype opcode;
  275. valtype vchPushValue;
  276. vector<bool> vfExec;
  277. vector<valtype> altstack;
  278. if (script.size() > 10000)
  279. return false;
  280. int nOpCount = 0;
  281. try
  282. {
  283. while (pc < pend)
  284. {
  285. bool fExec = !count(vfExec.begin(), vfExec.end(), false);
  286. //
  287. // Read instruction
  288. //
  289. if (!script.GetOp(pc, opcode, vchPushValue))
  290. return false;
  291. if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
  292. return false;
  293. // Note how OP_RESERVED does not count towards the opcode limit.
  294. if (opcode > OP_16 && ++nOpCount > 201)
  295. return false;
  296. if (opcode == OP_CAT ||
  297. opcode == OP_SUBSTR ||
  298. opcode == OP_LEFT ||
  299. opcode == OP_RIGHT ||
  300. opcode == OP_INVERT ||
  301. opcode == OP_AND ||
  302. opcode == OP_OR ||
  303. opcode == OP_XOR ||
  304. opcode == OP_2MUL ||
  305. opcode == OP_2DIV ||
  306. opcode == OP_MUL ||
  307. opcode == OP_DIV ||
  308. opcode == OP_MOD ||
  309. opcode == OP_LSHIFT ||
  310. opcode == OP_RSHIFT)
  311. return false; // Disabled opcodes.
  312. if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
  313. stack.push_back(vchPushValue);
  314. else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
  315. switch (opcode)
  316. {
  317. //
  318. // Push value
  319. //
  320. case OP_1NEGATE:
  321. case OP_1:
  322. case OP_2:
  323. case OP_3:
  324. case OP_4:
  325. case OP_5:
  326. case OP_6:
  327. case OP_7:
  328. case OP_8:
  329. case OP_9:
  330. case OP_10:
  331. case OP_11:
  332. case OP_12:
  333. case OP_13:
  334. case OP_14:
  335. case OP_15:
  336. case OP_16:
  337. {
  338. // ( -- value)
  339. CScriptNum bn((int)opcode - (int)(OP_1 - 1));
  340. stack.push_back(bn.getvch());
  341. }
  342. break;
  343. //
  344. // Control
  345. //
  346. case OP_NOP:
  347. case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
  348. case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
  349. break;
  350. case OP_IF:
  351. case OP_NOTIF:
  352. {
  353. // <expression> if [statements] [else [statements]] endif
  354. bool fValue = false;
  355. if (fExec)
  356. {
  357. if (stack.size() < 1)
  358. return false;
  359. valtype& vch = stacktop(-1);
  360. fValue = CastToBool(vch);
  361. if (opcode == OP_NOTIF)
  362. fValue = !fValue;
  363. popstack(stack);
  364. }
  365. vfExec.push_back(fValue);
  366. }
  367. break;
  368. case OP_ELSE:
  369. {
  370. if (vfExec.empty())
  371. return false;
  372. vfExec.back() = !vfExec.back();
  373. }
  374. break;
  375. case OP_ENDIF:
  376. {
  377. if (vfExec.empty())
  378. return false;
  379. vfExec.pop_back();
  380. }
  381. break;
  382. case OP_VERIFY:
  383. {
  384. // (true -- ) or
  385. // (false -- false) and return
  386. if (stack.size() < 1)
  387. return false;
  388. bool fValue = CastToBool(stacktop(-1));
  389. if (fValue)
  390. popstack(stack);
  391. else
  392. return false;
  393. }
  394. break;
  395. case OP_RETURN:
  396. {
  397. return false;
  398. }
  399. break;
  400. //
  401. // Stack ops
  402. //
  403. case OP_TOALTSTACK:
  404. {
  405. if (stack.size() < 1)
  406. return false;
  407. altstack.push_back(stacktop(-1));
  408. popstack(stack);
  409. }
  410. break;
  411. case OP_FROMALTSTACK:
  412. {
  413. if (altstack.size() < 1)
  414. return false;
  415. stack.push_back(altstacktop(-1));
  416. popstack(altstack);
  417. }
  418. break;
  419. case OP_2DROP:
  420. {
  421. // (x1 x2 -- )
  422. if (stack.size() < 2)
  423. return false;
  424. popstack(stack);
  425. popstack(stack);
  426. }
  427. break;
  428. case OP_2DUP:
  429. {
  430. // (x1 x2 -- x1 x2 x1 x2)
  431. if (stack.size() < 2)
  432. return false;
  433. valtype vch1 = stacktop(-2);
  434. valtype vch2 = stacktop(-1);
  435. stack.push_back(vch1);
  436. stack.push_back(vch2);
  437. }
  438. break;
  439. case OP_3DUP:
  440. {
  441. // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
  442. if (stack.size() < 3)
  443. return false;
  444. valtype vch1 = stacktop(-3);
  445. valtype vch2 = stacktop(-2);
  446. valtype vch3 = stacktop(-1);
  447. stack.push_back(vch1);
  448. stack.push_back(vch2);
  449. stack.push_back(vch3);
  450. }
  451. break;
  452. case OP_2OVER:
  453. {
  454. // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
  455. if (stack.size() < 4)
  456. return false;
  457. valtype vch1 = stacktop(-4);
  458. valtype vch2 = stacktop(-3);
  459. stack.push_back(vch1);
  460. stack.push_back(vch2);
  461. }
  462. break;
  463. case OP_2ROT:
  464. {
  465. // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
  466. if (stack.size() < 6)
  467. return false;
  468. valtype vch1 = stacktop(-6);
  469. valtype vch2 = stacktop(-5);
  470. stack.erase(stack.end()-6, stack.end()-4);
  471. stack.push_back(vch1);
  472. stack.push_back(vch2);
  473. }
  474. break;
  475. case OP_2SWAP:
  476. {
  477. // (x1 x2 x3 x4 -- x3 x4 x1 x2)
  478. if (stack.size() < 4)
  479. return false;
  480. swap(stacktop(-4), stacktop(-2));
  481. swap(stacktop(-3), stacktop(-1));
  482. }
  483. break;
  484. case OP_IFDUP:
  485. {
  486. // (x - 0 | x x)
  487. if (stack.size() < 1)
  488. return false;
  489. valtype vch = stacktop(-1);
  490. if (CastToBool(vch))
  491. stack.push_back(vch);
  492. }
  493. break;
  494. case OP_DEPTH:
  495. {
  496. // -- stacksize
  497. CScriptNum bn(stack.size());
  498. stack.push_back(bn.getvch());
  499. }
  500. break;
  501. case OP_DROP:
  502. {
  503. // (x -- )
  504. if (stack.size() < 1)
  505. return false;
  506. popstack(stack);
  507. }
  508. break;
  509. case OP_DUP:
  510. {
  511. // (x -- x x)
  512. if (stack.size() < 1)
  513. return false;
  514. valtype vch = stacktop(-1);
  515. stack.push_back(vch);
  516. }
  517. break;
  518. case OP_NIP:
  519. {
  520. // (x1 x2 -- x2)
  521. if (stack.size() < 2)
  522. return false;
  523. stack.erase(stack.end() - 2);
  524. }
  525. break;
  526. case OP_OVER:
  527. {
  528. // (x1 x2 -- x1 x2 x1)
  529. if (stack.size() < 2)
  530. return false;
  531. valtype vch = stacktop(-2);
  532. stack.push_back(vch);
  533. }
  534. break;
  535. case OP_PICK:
  536. case OP_ROLL:
  537. {
  538. // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
  539. // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
  540. if (stack.size() < 2)
  541. return false;
  542. int n = CScriptNum(stacktop(-1)).getint();
  543. popstack(stack);
  544. if (n < 0 || n >= (int)stack.size())
  545. return false;
  546. valtype vch = stacktop(-n-1);
  547. if (opcode == OP_ROLL)
  548. stack.erase(stack.end()-n-1);
  549. stack.push_back(vch);
  550. }
  551. break;
  552. case OP_ROT:
  553. {
  554. // (x1 x2 x3 -- x2 x3 x1)
  555. // x2 x1 x3 after first swap
  556. // x2 x3 x1 after second swap
  557. if (stack.size() < 3)
  558. return false;
  559. swap(stacktop(-3), stacktop(-2));
  560. swap(stacktop(-2), stacktop(-1));
  561. }
  562. break;
  563. case OP_SWAP:
  564. {
  565. // (x1 x2 -- x2 x1)
  566. if (stack.size() < 2)
  567. return false;
  568. swap(stacktop(-2), stacktop(-1));
  569. }
  570. break;
  571. case OP_TUCK:
  572. {
  573. // (x1 x2 -- x2 x1 x2)
  574. if (stack.size() < 2)
  575. return false;
  576. valtype vch = stacktop(-1);
  577. stack.insert(stack.end()-2, vch);
  578. }
  579. break;
  580. case OP_SIZE:
  581. {
  582. // (in -- in size)
  583. if (stack.size() < 1)
  584. return false;
  585. CScriptNum bn(stacktop(-1).size());
  586. stack.push_back(bn.getvch());
  587. }
  588. break;
  589. //
  590. // Bitwise logic
  591. //
  592. case OP_EQUAL:
  593. case OP_EQUALVERIFY:
  594. //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
  595. {
  596. // (x1 x2 - bool)
  597. if (stack.size() < 2)
  598. return false;
  599. valtype& vch1 = stacktop(-2);
  600. valtype& vch2 = stacktop(-1);
  601. bool fEqual = (vch1 == vch2);
  602. // OP_NOTEQUAL is disabled because it would be too easy to say
  603. // something like n != 1 and have some wiseguy pass in 1 with extra
  604. // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
  605. //if (opcode == OP_NOTEQUAL)
  606. // fEqual = !fEqual;
  607. popstack(stack);
  608. popstack(stack);
  609. stack.push_back(fEqual ? vchTrue : vchFalse);
  610. if (opcode == OP_EQUALVERIFY)
  611. {
  612. if (fEqual)
  613. popstack(stack);
  614. else
  615. return false;
  616. }
  617. }
  618. break;
  619. //
  620. // Numeric
  621. //
  622. case OP_1ADD:
  623. case OP_1SUB:
  624. case OP_NEGATE:
  625. case OP_ABS:
  626. case OP_NOT:
  627. case OP_0NOTEQUAL:
  628. {
  629. // (in -- out)
  630. if (stack.size() < 1)
  631. return false;
  632. CScriptNum bn(stacktop(-1));
  633. switch (opcode)
  634. {
  635. case OP_1ADD: bn += bnOne; break;
  636. case OP_1SUB: bn -= bnOne; break;
  637. case OP_NEGATE: bn = -bn; break;
  638. case OP_ABS: if (bn < bnZero) bn = -bn; break;
  639. case OP_NOT: bn = (bn == bnZero); break;
  640. case OP_0NOTEQUAL: bn = (bn != bnZero); break;
  641. default: assert(!"invalid opcode"); break;
  642. }
  643. popstack(stack);
  644. stack.push_back(bn.getvch());
  645. }
  646. break;
  647. case OP_ADD:
  648. case OP_SUB:
  649. case OP_BOOLAND:
  650. case OP_BOOLOR:
  651. case OP_NUMEQUAL:
  652. case OP_NUMEQUALVERIFY:
  653. case OP_NUMNOTEQUAL:
  654. case OP_LESSTHAN:
  655. case OP_GREATERTHAN:
  656. case OP_LESSTHANOREQUAL:
  657. case OP_GREATERTHANOREQUAL:
  658. case OP_MIN:
  659. case OP_MAX:
  660. {
  661. // (x1 x2 -- out)
  662. if (stack.size() < 2)
  663. return false;
  664. CScriptNum bn1(stacktop(-2));
  665. CScriptNum bn2(stacktop(-1));
  666. CScriptNum bn(0);
  667. switch (opcode)
  668. {
  669. case OP_ADD:
  670. bn = bn1 + bn2;
  671. break;
  672. case OP_SUB:
  673. bn = bn1 - bn2;
  674. break;
  675. case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
  676. case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
  677. case OP_NUMEQUAL: bn = (bn1 == bn2); break;
  678. case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
  679. case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
  680. case OP_LESSTHAN: bn = (bn1 < bn2); break;
  681. case OP_GREATERTHAN: bn = (bn1 > bn2); break;
  682. case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
  683. case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
  684. case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
  685. case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
  686. default: assert(!"invalid opcode"); break;
  687. }
  688. popstack(stack);
  689. popstack(stack);
  690. stack.push_back(bn.getvch());
  691. if (opcode == OP_NUMEQUALVERIFY)
  692. {
  693. if (CastToBool(stacktop(-1)))
  694. popstack(stack);
  695. else
  696. return false;
  697. }
  698. }
  699. break;
  700. case OP_WITHIN:
  701. {
  702. // (x min max -- out)
  703. if (stack.size() < 3)
  704. return false;
  705. CScriptNum bn1(stacktop(-3));
  706. CScriptNum bn2(stacktop(-2));
  707. CScriptNum bn3(stacktop(-1));
  708. bool fValue = (bn2 <= bn1 && bn1 < bn3);
  709. popstack(stack);
  710. popstack(stack);
  711. popstack(stack);
  712. stack.push_back(fValue ? vchTrue : vchFalse);
  713. }
  714. break;
  715. //
  716. // Crypto
  717. //
  718. case OP_RIPEMD160:
  719. case OP_SHA1:
  720. case OP_SHA256:
  721. case OP_HASH160:
  722. case OP_HASH256:
  723. {
  724. // (in -- hash)
  725. if (stack.size() < 1)
  726. return false;
  727. valtype& vch = stacktop(-1);
  728. valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
  729. if (opcode == OP_RIPEMD160)
  730. CRIPEMD160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
  731. else if (opcode == OP_SHA1)
  732. CSHA1().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
  733. else if (opcode == OP_SHA256)
  734. CSHA256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
  735. else if (opcode == OP_HASH160)
  736. CHash160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
  737. else if (opcode == OP_HASH256)
  738. CHash256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
  739. popstack(stack);
  740. stack.push_back(vchHash);
  741. }
  742. break;
  743. case OP_CODESEPARATOR:
  744. {
  745. // Hash starts after the code separator
  746. pbegincodehash = pc;
  747. }
  748. break;
  749. case OP_CHECKSIG:
  750. case OP_CHECKSIGVERIFY:
  751. {
  752. // (sig pubkey -- bool)
  753. if (stack.size() < 2)
  754. return false;
  755. valtype& vchSig = stacktop(-2);
  756. valtype& vchPubKey = stacktop(-1);
  757. // Subset of script starting at the most recent codeseparator
  758. CScript scriptCode(pbegincodehash, pend);
  759. // Drop the signature, since there's no way for a signature to sign itself
  760. scriptCode.FindAndDelete(CScript(vchSig));
  761. bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
  762. CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
  763. popstack(stack);
  764. popstack(stack);
  765. stack.push_back(fSuccess ? vchTrue : vchFalse);
  766. if (opcode == OP_CHECKSIGVERIFY)
  767. {
  768. if (fSuccess)
  769. popstack(stack);
  770. else
  771. return false;
  772. }
  773. }
  774. break;
  775. case OP_CHECKMULTISIG:
  776. case OP_CHECKMULTISIGVERIFY:
  777. {
  778. // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
  779. int i = 1;
  780. if ((int)stack.size() < i)
  781. return false;
  782. int nKeysCount = CScriptNum(stacktop(-i)).getint();
  783. if (nKeysCount < 0 || nKeysCount > 20)
  784. return false;
  785. nOpCount += nKeysCount;
  786. if (nOpCount > 201)
  787. return false;
  788. int ikey = ++i;
  789. i += nKeysCount;
  790. if ((int)stack.size() < i)
  791. return false;
  792. int nSigsCount = CScriptNum(stacktop(-i)).getint();
  793. if (nSigsCount < 0 || nSigsCount > nKeysCount)
  794. return false;
  795. int isig = ++i;
  796. i += nSigsCount;
  797. if ((int)stack.size() < i)
  798. return false;
  799. // Subset of script starting at the most recent codeseparator
  800. CScript scriptCode(pbegincodehash, pend);
  801. // Drop the signatures, since there's no way for a signature to sign itself
  802. for (int k = 0; k < nSigsCount; k++)
  803. {
  804. valtype& vchSig = stacktop(-isig-k);
  805. scriptCode.FindAndDelete(CScript(vchSig));
  806. }
  807. bool fSuccess = true;
  808. while (fSuccess && nSigsCount > 0)
  809. {
  810. valtype& vchSig = stacktop(-isig);
  811. valtype& vchPubKey = stacktop(-ikey);
  812. // Check signature
  813. bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
  814. CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
  815. if (fOk) {
  816. isig++;
  817. nSigsCount--;
  818. }
  819. ikey++;
  820. nKeysCount--;
  821. // If there are more signatures left than keys left,
  822. // then too many signatures have failed
  823. if (nSigsCount > nKeysCount)
  824. fSuccess = false;
  825. }
  826. // Clean up stack of actual arguments
  827. while (i-- > 1)
  828. popstack(stack);
  829. // A bug causes CHECKMULTISIG to consume one extra argument
  830. // whose contents were not checked in any way.
  831. //
  832. // Unfortunately this is a potential source of mutability,
  833. // so optionally verify it is exactly equal to zero prior
  834. // to removing it from the stack.
  835. if (stack.size() < 1)
  836. return false;
  837. if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
  838. return error("CHECKMULTISIG dummy argument not null");
  839. popstack(stack);
  840. stack.push_back(fSuccess ? vchTrue : vchFalse);
  841. if (opcode == OP_CHECKMULTISIGVERIFY)
  842. {
  843. if (fSuccess)
  844. popstack(stack);
  845. else
  846. return false;
  847. }
  848. }
  849. break;
  850. default:
  851. return false;
  852. }
  853. // Size limits
  854. if (stack.size() + altstack.size() > 1000)
  855. return false;
  856. }
  857. }
  858. catch (...)
  859. {
  860. return false;
  861. }
  862. if (!vfExec.empty())
  863. return false;
  864. return true;
  865. }
  866. namespace {
  867. /** Wrapper that serializes like CTransaction, but with the modifications
  868. * required for the signature hash done in-place
  869. */
  870. class CTransactionSignatureSerializer {
  871. private:
  872. const CTransaction &txTo; // reference to the spending transaction (the one being serialized)
  873. const CScript &scriptCode; // output script being consumed
  874. const unsigned int nIn; // input index of txTo being signed
  875. const bool fAnyoneCanPay; // whether the hashtype has the SIGHASH_ANYONECANPAY flag set
  876. const bool fHashSingle; // whether the hashtype is SIGHASH_SINGLE
  877. const bool fHashNone; // whether the hashtype is SIGHASH_NONE
  878. public:
  879. CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
  880. txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
  881. fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
  882. fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
  883. fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
  884. /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
  885. template<typename S>
  886. void SerializeScriptCode(S &s, int nType, int nVersion) const {
  887. CScript::const_iterator it = scriptCode.begin();
  888. CScript::const_iterator itBegin = it;
  889. opcodetype opcode;
  890. unsigned int nCodeSeparators = 0;
  891. while (scriptCode.GetOp(it, opcode)) {
  892. if (opcode == OP_CODESEPARATOR)
  893. nCodeSeparators++;
  894. }
  895. ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
  896. it = itBegin;
  897. while (scriptCode.GetOp(it, opcode)) {
  898. if (opcode == OP_CODESEPARATOR) {
  899. s.write((char*)&itBegin[0], it-itBegin-1);
  900. itBegin = it;
  901. }
  902. }
  903. s.write((char*)&itBegin[0], it-itBegin);
  904. }
  905. /** Serialize an input of txTo */
  906. template<typename S>
  907. void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const {
  908. // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
  909. if (fAnyoneCanPay)
  910. nInput = nIn;
  911. // Serialize the prevout
  912. ::Serialize(s, txTo.vin[nInput].prevout, nType, nVersion);
  913. // Serialize the script
  914. if (nInput != nIn)
  915. // Blank out other inputs' signatures
  916. ::Serialize(s, CScript(), nType, nVersion);
  917. else
  918. SerializeScriptCode(s, nType, nVersion);
  919. // Serialize the nSequence
  920. if (nInput != nIn && (fHashSingle || fHashNone))
  921. // let the others update at will
  922. ::Serialize(s, (int)0, nType, nVersion);
  923. else
  924. ::Serialize(s, txTo.vin[nInput].nSequence, nType, nVersion);
  925. }
  926. /** Serialize an output of txTo */
  927. template<typename S>
  928. void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const {
  929. if (fHashSingle && nOutput != nIn)
  930. // Do not lock-in the txout payee at other indices as txin
  931. ::Serialize(s, CTxOut(), nType, nVersion);
  932. else
  933. ::Serialize(s, txTo.vout[nOutput], nType, nVersion);
  934. }
  935. /** Serialize txTo */
  936. template<typename S>
  937. void Serialize(S &s, int nType, int nVersion) const {
  938. // Serialize nVersion
  939. ::Serialize(s, txTo.nVersion, nType, nVersion);
  940. // Serialize vin
  941. unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
  942. ::WriteCompactSize(s, nInputs);
  943. for (unsigned int nInput = 0; nInput < nInputs; nInput++)
  944. SerializeInput(s, nInput, nType, nVersion);
  945. // Serialize vout
  946. unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
  947. ::WriteCompactSize(s, nOutputs);
  948. for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
  949. SerializeOutput(s, nOutput, nType, nVersion);
  950. // Serialie nLockTime
  951. ::Serialize(s, txTo.nLockTime, nType, nVersion);
  952. }
  953. };
  954. } // anon namespace
  955. uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
  956. {
  957. if (nIn >= txTo.vin.size()) {
  958. LogPrintf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
  959. return 1;
  960. }
  961. // Check for invalid use of SIGHASH_SINGLE
  962. if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
  963. if (nIn >= txTo.vout.size()) {
  964. LogPrintf("ERROR: SignatureHash() : nOut=%d out of range\n", nIn);
  965. return 1;
  966. }
  967. }
  968. // Wrapper to serialize only the necessary parts of the transaction being signed
  969. CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
  970. // Serialize and hash
  971. CHashWriter ss(SER_GETHASH, 0);
  972. ss << txTmp << nHashType;
  973. return ss.GetHash();
  974. }
  975. // Valid signature cache, to avoid doing expensive ECDSA signature checking
  976. // twice for every transaction (once when accepted into memory pool, and
  977. // again when accepted into the block chain)
  978. class CSignatureCache
  979. {
  980. private:
  981. // sigdata_type is (signature hash, signature, public key):
  982. typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey> sigdata_type;
  983. std::set< sigdata_type> setValid;
  984. boost::shared_mutex cs_sigcache;
  985. public:
  986. bool
  987. Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
  988. {
  989. boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
  990. sigdata_type k(hash, vchSig, pubKey);
  991. std::set<sigdata_type>::iterator mi = setValid.find(k);
  992. if (mi != setValid.end())
  993. return true;
  994. return false;
  995. }
  996. void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
  997. {
  998. // DoS prevention: limit cache size to less than 10MB
  999. // (~200 bytes per cache entry times 50,000 entries)
  1000. // Since there are a maximum of 20,000 signature operations per block
  1001. // 50,000 is a reasonable default.
  1002. int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
  1003. if (nMaxCacheSize <= 0) return;
  1004. boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
  1005. while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
  1006. {
  1007. // Evict a random entry. Random because that helps
  1008. // foil would-be DoS attackers who might try to pre-generate
  1009. // and re-use a set of valid signatures just-slightly-greater
  1010. // than our cache size.
  1011. uint256 randomHash = GetRandHash();
  1012. std::vector<unsigned char> unused;
  1013. std::set<sigdata_type>::iterator it =
  1014. setValid.lower_bound(sigdata_type(randomHash, unused, unused));
  1015. if (it == setValid.end())
  1016. it = setValid.begin();
  1017. setValid.erase(*it);
  1018. }
  1019. sigdata_type k(hash, vchSig, pubKey);
  1020. setValid.insert(k);
  1021. }
  1022. };
  1023. bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
  1024. const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
  1025. {
  1026. static CSignatureCache signatureCache;
  1027. CPubKey pubkey(vchPubKey);
  1028. if (!pubkey.IsValid())
  1029. return false;
  1030. // Hash type is one byte tacked on to the end of the signature
  1031. if (vchSig.empty())
  1032. return false;
  1033. if (nHashType == 0)
  1034. nHashType = vchSig.back();
  1035. else if (nHashType != vchSig.back())
  1036. return false;
  1037. vchSig.pop_back();
  1038. uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
  1039. if (signatureCache.Get(sighash, vchSig, pubkey))
  1040. return true;
  1041. if (!pubkey.Verify(sighash, vchSig))
  1042. return false;
  1043. if (!(flags & SCRIPT_VERIFY_NOCACHE))
  1044. signatureCache.Set(sighash, vchSig, pubkey);
  1045. return true;
  1046. }
  1047. //
  1048. // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
  1049. //
  1050. bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
  1051. {
  1052. // Templates
  1053. static multimap<txnouttype, CScript> mTemplates;
  1054. if (mTemplates.empty())
  1055. {
  1056. // Standard tx, sender provides pubkey, receiver adds signature
  1057. mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
  1058. // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
  1059. mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
  1060. // Sender provides N pubkeys, receivers provides M signatures
  1061. mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
  1062. // Empty, provably prunable, data-carrying output
  1063. if (GetBoolArg("-datacarrier", true))
  1064. mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
  1065. mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN));
  1066. }
  1067. // Shortcut for pay-to-script-hash, which are more constrained than the other types:
  1068. // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
  1069. if (scriptPubKey.IsPayToScriptHash())
  1070. {
  1071. typeRet = TX_SCRIPTHASH;
  1072. vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
  1073. vSolutionsRet.push_back(hashBytes);
  1074. return true;
  1075. }
  1076. // Scan templates
  1077. const CScript& script1 = scriptPubKey;
  1078. BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
  1079. {
  1080. const CScript& script2 = tplate.second;
  1081. vSolutionsRet.clear();
  1082. opcodetype opcode1, opcode2;
  1083. vector<unsigned char> vch1, vch2;
  1084. // Compare
  1085. CScript::const_iterator pc1 = script1.begin();
  1086. CScript::const_iterator pc2 = script2.begin();
  1087. while (true)
  1088. {
  1089. if (pc1 == script1.end() && pc2 == script2.end())
  1090. {
  1091. // Found a match
  1092. typeRet = tplate.first;
  1093. if (typeRet == TX_MULTISIG)
  1094. {
  1095. // Additional checks for TX_MULTISIG:
  1096. unsigned char m = vSolutionsRet.front()[0];
  1097. unsigned char n = vSolutionsRet.back()[0];
  1098. if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
  1099. return false;
  1100. }
  1101. return true;
  1102. }
  1103. if (!script1.GetOp(pc1, opcode1, vch1))
  1104. break;
  1105. if (!script2.GetOp(pc2, opcode2, vch2))
  1106. break;
  1107. // Template matching opcodes:
  1108. if (opcode2 == OP_PUBKEYS)
  1109. {
  1110. while (vch1.size() >= 33 && vch1.size() <= 65)
  1111. {
  1112. vSolutionsRet.push_back(vch1);
  1113. if (!script1.GetOp(pc1, opcode1, vch1))
  1114. break;
  1115. }
  1116. if (!script2.GetOp(pc2, opcode2, vch2))
  1117. break;
  1118. // Normal situation is to fall through
  1119. // to other if/else statements
  1120. }
  1121. if (opcode2 == OP_PUBKEY)
  1122. {
  1123. if (vch1.size() < 33 || vch1.size() > 65)
  1124. break;
  1125. vSolutionsRet.push_back(vch1);
  1126. }
  1127. else if (opcode2 == OP_PUBKEYHASH)
  1128. {
  1129. if (vch1.size() != sizeof(uint160))
  1130. break;
  1131. vSolutionsRet.push_back(vch1);
  1132. }
  1133. else if (opcode2 == OP_SMALLINTEGER)
  1134. { // Single-byte small integer pushed onto vSolutions
  1135. if (opcode1 == OP_0 ||
  1136. (opcode1 >= OP_1 && opcode1 <= OP_16))
  1137. {
  1138. char n = (char)CScript::DecodeOP_N(opcode1);
  1139. vSolutionsRet.push_back(valtype(1, n));
  1140. }
  1141. else
  1142. break;
  1143. }
  1144. else if (opcode2 == OP_SMALLDATA)
  1145. {
  1146. // small pushdata, <= MAX_OP_RETURN_RELAY bytes
  1147. if (vch1.size() > MAX_OP_RETURN_RELAY)
  1148. break;
  1149. }
  1150. else if (opcode1 != opcode2 || vch1 != vch2)
  1151. {
  1152. // Others must match exactly
  1153. break;
  1154. }
  1155. }
  1156. }
  1157. vSolutionsRet.clear();
  1158. typeRet = TX_NONSTANDARD;
  1159. return false;
  1160. }
  1161. bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
  1162. {
  1163. CKey key;
  1164. if (!keystore.GetKey(address, key))
  1165. return false;
  1166. vector<unsigned char> vchSig;
  1167. if (!key.Sign(hash, vchSig))
  1168. return false;
  1169. vchSig.push_back((unsigned char)nHashType);
  1170. scriptSigRet << vchSig;
  1171. return true;
  1172. }
  1173. bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
  1174. {
  1175. int nSigned = 0;
  1176. int nRequired = multisigdata.front()[0];
  1177. for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
  1178. {
  1179. const valtype& pubkey = multisigdata[i];
  1180. CKeyID keyID = CPubKey(pubkey).GetID();
  1181. if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
  1182. ++nSigned;
  1183. }
  1184. return nSigned==nRequired;
  1185. }
  1186. //
  1187. // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
  1188. // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
  1189. // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
  1190. // Returns false if scriptPubKey could not be completely satisfied.
  1191. //
  1192. bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
  1193. CScript& scriptSigRet, txnouttype& whichTypeRet)
  1194. {
  1195. scriptSigRet.clear();
  1196. vector<valtype> vSolutions;
  1197. if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
  1198. return false;
  1199. CKeyID keyID;
  1200. switch (whichTypeRet)
  1201. {
  1202. case TX_NONSTANDARD:
  1203. case TX_NULL_DATA:
  1204. return false;
  1205. case TX_PUBKEY:
  1206. keyID = CPubKey(vSolutions[0]).GetID();
  1207. return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
  1208. case TX_PUBKEYHASH:
  1209. keyID = CKeyID(uint160(vSolutions[0]));
  1210. if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
  1211. return false;
  1212. else
  1213. {
  1214. CPubKey vch;
  1215. keystore.GetPubKey(keyID, vch);
  1216. scriptSigRet << vch;
  1217. }
  1218. return true;
  1219. case TX_SCRIPTHASH:
  1220. return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
  1221. case TX_MULTISIG:
  1222. scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
  1223. return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
  1224. }
  1225. return false;
  1226. }
  1227. int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
  1228. {
  1229. switch (t)
  1230. {
  1231. case TX_NONSTANDARD:
  1232. case TX_NULL_DATA:
  1233. return -1;
  1234. case TX_PUBKEY:
  1235. return 1;
  1236. case TX_PUBKEYHASH:
  1237. return 2;
  1238. case TX_MULTISIG:
  1239. if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
  1240. return -1;
  1241. return vSolutions[0][0] + 1;
  1242. case TX_SCRIPTHASH:
  1243. return 1; // doesn't include args needed by the script
  1244. }
  1245. return -1;
  1246. }
  1247. bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
  1248. {
  1249. vector<valtype> vSolutions;
  1250. if (!Solver(scriptPubKey, whichType, vSolutions))
  1251. return false;
  1252. if (whichType == TX_MULTISIG)
  1253. {
  1254. unsigned char m = vSolutions.front()[0];
  1255. unsigned char n = vSolutions.back()[0];
  1256. // Support up to x-of-3 multisig txns as standard
  1257. if (n < 1 || n > 3)
  1258. return false;
  1259. if (m < 1 || m > n)
  1260. return false;
  1261. }
  1262. return whichType != TX_NONSTANDARD;
  1263. }
  1264. unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
  1265. {
  1266. unsigned int nResult = 0;
  1267. BOOST_FOREACH(const valtype& pubkey, pubkeys)
  1268. {
  1269. CKeyID keyID = CPubKey(pubkey).GetID();
  1270. if (keystore.HaveKey(keyID))
  1271. ++nResult;
  1272. }
  1273. return nResult;
  1274. }
  1275. class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
  1276. {
  1277. private:
  1278. const CKeyStore *keystore;
  1279. public:
  1280. CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
  1281. bool operator()(const CNoDestination &dest) const { return false; }
  1282. bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
  1283. bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
  1284. };
  1285. bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
  1286. {
  1287. return boost::apply_visitor(CKeyStoreIsMineVisitor(&keystore), dest);
  1288. }
  1289. bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
  1290. {
  1291. vector<valtype> vSolutions;
  1292. txnouttype whichType;
  1293. if (!Solver(scriptPubKey, whichType, vSolutions))
  1294. return false;
  1295. CKeyID keyID;
  1296. switch (whichType)
  1297. {
  1298. case TX_NONSTANDARD:
  1299. case TX_NULL_DATA:
  1300. return false;
  1301. case TX_PUBKEY:
  1302. keyID = CPubKey(vSolutions[0]).GetID();
  1303. return keystore.HaveKey(keyID);
  1304. case TX_PUBKEYHASH:
  1305. keyID = CKeyID(uint160(vSolutions[0]));
  1306. return keystore.HaveKey(keyID);
  1307. case TX_SCRIPTHASH:
  1308. {
  1309. CScript subscript;
  1310. if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
  1311. return false;
  1312. return IsMine(keystore, subscript);
  1313. }
  1314. case TX_MULTISIG:
  1315. {
  1316. // Only consider transactions "mine" if we own ALL the
  1317. // keys involved. multi-signature transactions that are
  1318. // partially owned (somebody else has a key that can spend
  1319. // them) enable spend-out-from-under-you attacks, especially
  1320. // in shared-wallet situations.
  1321. vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
  1322. return HaveKeys(keys, keystore) == keys.size();
  1323. }
  1324. }
  1325. return false;
  1326. }
  1327. bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
  1328. {
  1329. vector<valtype> vSolutions;
  1330. txnouttype whichType;
  1331. if (!Solver(scriptPubKey, whichType, vSolutions))
  1332. return false;
  1333. if (whichType == TX_PUBKEY)
  1334. {
  1335. addressRet = CPubKey(vSolutions[0]).GetID();
  1336. return true;
  1337. }
  1338. else if (whichType == TX_PUBKEYHASH)
  1339. {
  1340. addressRet = CKeyID(uint160(vSolutions[0]));
  1341. return true;
  1342. }
  1343. else if (whichType == TX_SCRIPTHASH)
  1344. {
  1345. addressRet = CScriptID(uint160(vSolutions[0]));
  1346. return true;
  1347. }
  1348. // Multisig txns have more than one address...
  1349. return false;
  1350. }
  1351. bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
  1352. {
  1353. addressRet.clear();
  1354. typeRet = TX_NONSTANDARD;
  1355. vector<valtype> vSolutions;
  1356. if (!Solver(scriptPubKey, typeRet, vSolutions))
  1357. return false;
  1358. if (typeRet == TX_NULL_DATA){
  1359. // This is data, not addresses
  1360. return false;
  1361. }
  1362. if (typeRet == TX_MULTISIG)
  1363. {
  1364. nRequiredRet = vSolutions.front()[0];
  1365. for (unsigned int i = 1; i < vSolutions.size()-1; i++)
  1366. {
  1367. CTxDestination address = CPubKey(vSolutions[i]).GetID();
  1368. addressRet.push_back(address);
  1369. }
  1370. }
  1371. else
  1372. {
  1373. nRequiredRet = 1;
  1374. CTxDestination address;
  1375. if (!ExtractDestination(scriptPubKey, address))
  1376. return false;
  1377. addressRet.push_back(address);
  1378. }
  1379. return true;
  1380. }
  1381. class CAffectedKeysVisitor : public boost::static_visitor<void> {
  1382. private:
  1383. const CKeyStore &keystore;
  1384. std::vector<CKeyID> &vKeys;
  1385. public:
  1386. CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
  1387. void Process(const CScript &script) {
  1388. txnouttype type;
  1389. std::vector<CTxDestination> vDest;
  1390. int nRequired;
  1391. if (ExtractDestinations(script, type, vDest, nRequired)) {
  1392. BOOST_FOREACH(const CTxDestination &dest, vDest)
  1393. boost::apply_visitor(*this, dest);
  1394. }
  1395. }
  1396. void operator()(const CKeyID &keyId) {
  1397. if (keystore.HaveKey(keyId))
  1398. vKeys.push_back(keyId);
  1399. }
  1400. void operator()(const CScriptID &scriptId) {
  1401. CScript script;
  1402. if (keystore.GetCScript(scriptId, script))
  1403. Process(script);
  1404. }
  1405. void operator()(const CNoDestination &none) {}
  1406. };
  1407. void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
  1408. CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
  1409. }
  1410. bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
  1411. unsigned int flags, int nHashType)
  1412. {
  1413. vector<vector<unsigned char> > stack, stackCopy;
  1414. if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
  1415. return false;
  1416. if (flags & SCRIPT_VERIFY_P2SH)
  1417. stackCopy = stack;
  1418. if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
  1419. return false;
  1420. if (stack.empty())
  1421. return false;
  1422. if (CastToBool(stack.back()) == false)
  1423. return false;
  1424. // Additional validation for spend-to-script-hash transactions:
  1425. if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
  1426. {
  1427. if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
  1428. return false; // or validation fails
  1429. // stackCopy cannot be empty here, because if it was the
  1430. // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
  1431. // an empty stack and the EvalScript above would return false.
  1432. assert(!stackCopy.empty());
  1433. const valtype& pubKeySerialized = stackCopy.back();
  1434. CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
  1435. popstack(stackCopy);
  1436. if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
  1437. return false;
  1438. if (stackCopy.empty())
  1439. return false;
  1440. return CastToBool(stackCopy.back());
  1441. }
  1442. return true;
  1443. }
  1444. bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
  1445. {
  1446. assert(nIn < txTo.vin.size());
  1447. CTxIn& txin = txTo.vin[nIn];
  1448. // Leave out the signature from the hash, since a signature can't sign itself.
  1449. // The checksig op will also drop the signatures from its hash.
  1450. uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
  1451. txnouttype whichType;
  1452. if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
  1453. return false;
  1454. if (whichType == TX_SCRIPTHASH)
  1455. {
  1456. // Solver returns the subscript that need to be evaluated;
  1457. // the final scriptSig is the signatures from that
  1458. // and then the serialized subscript:
  1459. CScript subscript = txin.scriptSig;
  1460. // Recompute txn hash using subscript in place of scriptPubKey:
  1461. uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
  1462. txnouttype subType;
  1463. bool fSolved =
  1464. Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
  1465. // Append serialized subscript whether or not it is completely signed:
  1466. txin.scriptSig << static_cast<valtype>(subscript);
  1467. if (!fSolved) return false;
  1468. }
  1469. // Test solution
  1470. return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STANDARD_SCRIPT_VERIFY_FLAGS, 0);
  1471. }
  1472. bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
  1473. {
  1474. assert(nIn < txTo.vin.size());
  1475. CTxIn& txin = txTo.vin[nIn];
  1476. assert(txin.prevout.n < txFrom.vout.size());
  1477. const CTxOut& txout = txFrom.vout[txin.prevout.n];
  1478. return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
  1479. }
  1480. static CScript PushAll(const vector<valtype>& values)
  1481. {
  1482. CScript result;
  1483. BOOST_FOREACH(const valtype& v, values)
  1484. result << v;
  1485. return result;
  1486. }
  1487. static CScript CombineMultisig(CScript scriptPubKey, const CMutableTransaction& txTo, unsigned int nIn,
  1488. const vector<valtype>& vSolutions,
  1489. vector<valtype>& sigs1, vector<valtype>& sigs2)
  1490. {
  1491. // Combine all the signatures we've got:
  1492. set<valtype> allsigs;
  1493. BOOST_FOREACH(const valtype& v, sigs1)
  1494. {
  1495. if (!v.empty())
  1496. allsigs.insert(v);
  1497. }
  1498. BOOST_FOREACH(const valtype& v, sigs2)
  1499. {
  1500. if (!v.empty())
  1501. allsigs.insert(v);
  1502. }
  1503. // Build a map of pubkey -> signature by matching sigs to pubkeys:
  1504. assert(vSolutions.size() > 1);
  1505. unsigned int nSigsRequired = vSolutions.front()[0];
  1506. unsigned int nPubKeys = vSolutions.size()-2;
  1507. map<valtype, valtype> sigs;
  1508. BOOST_FOREACH(const valtype& sig, allsigs)
  1509. {
  1510. for (unsigned int i = 0; i < nPubKeys; i++)
  1511. {
  1512. const valtype& pubkey = vSolutions[i+1];
  1513. if (sigs.count(pubkey))
  1514. continue; // Already got a sig for this pubkey
  1515. if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
  1516. {
  1517. sigs[pubkey] = sig;
  1518. break;
  1519. }
  1520. }
  1521. }
  1522. // Now build a merged CScript:
  1523. unsigned int nSigsHave = 0;
  1524. CScript result; result << OP_0; // pop-one-too-many workaround
  1525. for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
  1526. {
  1527. if (sigs.count(vSolutions[i+1]))
  1528. {
  1529. result << sigs[vSolutions[i+1]];
  1530. ++nSigsHave;
  1531. }
  1532. }
  1533. // Fill any missing with OP_0:
  1534. for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
  1535. result << OP_0;
  1536. return result;
  1537. }
  1538. static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
  1539. const txnouttype txType, const vector<valtype>& vSolutions,
  1540. vector<valtype>& sigs1, vector<valtype>& sigs2)
  1541. {
  1542. switch (txType)
  1543. {
  1544. case TX_NONSTANDARD:
  1545. case TX_NULL_DATA:
  1546. // Don't know anything about this, assume bigger one is correct:
  1547. if (sigs1.size() >= sigs2.size())
  1548. return PushAll(sigs1);
  1549. return PushAll(sigs2);
  1550. case TX_PUBKEY:
  1551. case TX_PUBKEYHASH:
  1552. // Signatures are bigger than placeholders or empty scripts:
  1553. if (sigs1.empty() || sigs1[0].empty())
  1554. return PushAll(sigs2);
  1555. return PushAll(sigs1);
  1556. case TX_SCRIPTHASH:
  1557. if (sigs1.empty() || sigs1.back().empty())
  1558. return PushAll(sigs2);
  1559. else if (sigs2.empty() || sigs2.back().empty())
  1560. return PushAll(sigs1);
  1561. else
  1562. {
  1563. // Recur to combine:
  1564. valtype spk = sigs1.back();
  1565. CScript pubKey2(spk.begin(), spk.end());
  1566. txnouttype txType2;
  1567. vector<vector<unsigned char> > vSolutions2;
  1568. Solver(pubKey2, txType2, vSolutions2);
  1569. sigs1.pop_back();
  1570. sigs2.pop_back();
  1571. CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
  1572. result << spk;
  1573. return result;
  1574. }
  1575. case TX_MULTISIG:
  1576. return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
  1577. }
  1578. return CScript();
  1579. }
  1580. CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
  1581. const CScript& scriptSig1, const CScript& scriptSig2)
  1582. {
  1583. txnouttype txType;
  1584. vector<vector<unsigned char> > vSolutions;
  1585. Solver(scriptPubKey, txType, vSolutions);
  1586. vector<valtype> stack1;
  1587. EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
  1588. vector<valtype> stack2;
  1589. EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
  1590. return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
  1591. }
  1592. unsigned int CScript::GetSigOpCount(bool fAccurate) const
  1593. {
  1594. unsigned int n = 0;
  1595. const_iterator pc = begin();
  1596. opcodetype lastOpcode = OP_INVALIDOPCODE;
  1597. while (pc < end())
  1598. {
  1599. opcodetype opcode;
  1600. if (!GetOp(pc, opcode))
  1601. break;
  1602. if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
  1603. n++;
  1604. else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
  1605. {
  1606. if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
  1607. n += DecodeOP_N(lastOpcode);
  1608. else
  1609. n += 20;
  1610. }
  1611. lastOpcode = opcode;
  1612. }
  1613. return n;
  1614. }
  1615. unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
  1616. {
  1617. if (!IsPayToScriptHash())
  1618. return GetSigOpCount(true);
  1619. // This is a pay-to-script-hash scriptPubKey;
  1620. // get the last item that the scriptSig
  1621. // pushes onto the stack:
  1622. const_iterator pc = scriptSig.begin();
  1623. vector<unsigned char> data;
  1624. while (pc < scriptSig.end())
  1625. {
  1626. opcodetype opcode;
  1627. if (!scriptSig.GetOp(pc, opcode, data))
  1628. return 0;
  1629. if (opcode > OP_16)
  1630. return 0;
  1631. }
  1632. /// ... and return its opcount:
  1633. CScript subscript(data.begin(), data.end());
  1634. return subscript.GetSigOpCount(true);
  1635. }
  1636. bool CScript::IsPayToScriptHash() const
  1637. {
  1638. // Extra-fast test for pay-to-script-hash CScripts:
  1639. return (this->size() == 23 &&
  1640. this->at(0) == OP_HASH160 &&
  1641. this->at(1) == 0x14 &&
  1642. this->at(22) == OP_EQUAL);
  1643. }
  1644. bool CScript::IsPushOnly() const
  1645. {
  1646. const_iterator pc = begin();
  1647. while (pc < end())
  1648. {
  1649. opcodetype opcode;
  1650. if (!GetOp(pc, opcode))
  1651. return false;
  1652. // Note that IsPushOnly() *does* consider OP_RESERVED to be a
  1653. // push-type opcode, however execution of OP_RESERVED fails, so
  1654. // it's not relevant to P2SH as the scriptSig would fail prior to
  1655. // the P2SH special validation code being executed.
  1656. if (opcode > OP_16)
  1657. return false;
  1658. }
  1659. return true;
  1660. }
  1661. bool CScript::HasCanonicalPushes() const
  1662. {
  1663. const_iterator pc = begin();
  1664. while (pc < end())
  1665. {
  1666. opcodetype opcode;
  1667. std::vector<unsigned char> data;
  1668. if (!GetOp(pc, opcode, data))
  1669. return false;
  1670. if (opcode > OP_16)
  1671. continue;
  1672. if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
  1673. // Could have used an OP_n code, rather than a 1-byte push.
  1674. return false;
  1675. if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
  1676. // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
  1677. return false;
  1678. if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
  1679. // Could have used an OP_PUSHDATA1.
  1680. return false;
  1681. if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
  1682. // Could have used an OP_PUSHDATA2.
  1683. return false;
  1684. }
  1685. return true;
  1686. }
  1687. class CScriptVisitor : public boost::static_visitor<bool>
  1688. {
  1689. private:
  1690. CScript *script;
  1691. public:
  1692. CScriptVisitor(CScript *scriptin) { script = scriptin; }
  1693. bool operator()(const CNoDestination &dest) const {
  1694. script->clear();
  1695. return false;
  1696. }
  1697. bool operator()(const CKeyID &keyID) const {
  1698. script->clear();
  1699. *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
  1700. return true;
  1701. }
  1702. bool operator()(const CScriptID &scriptID) const {
  1703. script->clear();
  1704. *script << OP_HASH160 << scriptID << OP_EQUAL;
  1705. return true;
  1706. }
  1707. };
  1708. void CScript::SetDestination(const CTxDestination& dest)
  1709. {
  1710. boost::apply_visitor(CScriptVisitor(this), dest);
  1711. }
  1712. void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
  1713. {
  1714. this->clear();
  1715. *this << EncodeOP_N(nRequired);
  1716. BOOST_FOREACH(const CPubKey& key, keys)
  1717. *this << key;
  1718. *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
  1719. }
  1720. bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
  1721. {
  1722. if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160
  1723. && script[2] == 20 && script[23] == OP_EQUALVERIFY
  1724. && script[24] == OP_CHECKSIG) {
  1725. memcpy(&hash, &script[3], 20);
  1726. return true;
  1727. }
  1728. return false;
  1729. }
  1730. bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
  1731. {
  1732. if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
  1733. && script[22] == OP_EQUAL) {
  1734. memcpy(&hash, &script[2], 20);
  1735. return true;
  1736. }
  1737. return false;
  1738. }
  1739. bool CScriptCompressor::IsToPubKey(CPubKey &pubkey) const
  1740. {
  1741. if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
  1742. && (script[1] == 0x02 || script[1] == 0x03)) {
  1743. pubkey.Set(&script[1], &script[34]);
  1744. return true;
  1745. }
  1746. if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG
  1747. && script[1] == 0x04) {
  1748. pubkey.Set(&script[1], &script[66]);
  1749. return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible
  1750. }
  1751. return false;
  1752. }
  1753. bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
  1754. {
  1755. CKeyID keyID;
  1756. if (IsToKeyID(keyID)) {
  1757. out.resize(21);
  1758. out[0] = 0x00;
  1759. memcpy(&out[1], &keyID, 20);
  1760. return true;
  1761. }
  1762. CScriptID scriptID;
  1763. if (IsToScriptID(scriptID)) {
  1764. out.resize(21);
  1765. out[0] = 0x01;
  1766. memcpy(&out[1], &scriptID, 20);
  1767. return true;
  1768. }
  1769. CPubKey pubkey;
  1770. if (IsToPubKey(pubkey)) {
  1771. out.resize(33);
  1772. memcpy(&out[1], &pubkey[1], 32);
  1773. if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
  1774. out[0] = pubkey[0];
  1775. return true;
  1776. } else if (pubkey[0] == 0x04) {
  1777. out[0] = 0x04 | (pubkey[64] & 0x01);
  1778. return true;
  1779. }
  1780. }
  1781. return false;
  1782. }
  1783. unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
  1784. {
  1785. if (nSize == 0 || nSize == 1)
  1786. return 20;
  1787. if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
  1788. return 32;
  1789. return 0;
  1790. }
  1791. bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
  1792. {
  1793. switch(nSize) {
  1794. case 0x00:
  1795. script.resize(25);
  1796. script[0] = OP_DUP;
  1797. script[1] = OP_HASH160;
  1798. script[2] = 20;
  1799. memcpy(&script[3], &in[0], 20);
  1800. script[23] = OP_EQUALVERIFY;
  1801. script[24] = OP_CHECKSIG;
  1802. return true;
  1803. case 0x01:
  1804. script.resize(23);
  1805. script[0] = OP_HASH160;
  1806. script[1] = 20;
  1807. memcpy(&script[2], &in[0], 20);
  1808. script[22] = OP_EQUAL;
  1809. return true;
  1810. case 0x02:
  1811. case 0x03:
  1812. script.resize(35);
  1813. script[0] = 33;
  1814. script[1] = nSize;
  1815. memcpy(&script[2], &in[0], 32);
  1816. script[34] = OP_CHECKSIG;
  1817. return true;
  1818. case 0x04:
  1819. case 0x05:
  1820. unsigned char vch[33] = {};
  1821. vch[0] = nSize - 2;
  1822. memcpy(&vch[1], &in[0], 32);
  1823. CPubKey pubkey(&vch[0], &vch[33]);
  1824. if (!pubkey.Decompress())
  1825. return false;
  1826. assert(pubkey.size() == 65);
  1827. script.resize(67);
  1828. script[0] = 65;
  1829. memcpy(&script[1], pubkey.begin(), 65);
  1830. script[66] = OP_CHECKSIG;
  1831. return true;
  1832. }
  1833. return false;
  1834. }