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.h 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. #ifndef H_BITCOIN_SCRIPT
  6. #define H_BITCOIN_SCRIPT
  7. #include "key.h"
  8. #include "tinyformat.h"
  9. #include "utilstrencodings.h"
  10. #include <stdexcept>
  11. #include <boost/variant.hpp>
  12. static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
  13. /** Script opcodes */
  14. enum opcodetype
  15. {
  16. // push value
  17. OP_0 = 0x00,
  18. OP_FALSE = OP_0,
  19. OP_PUSHDATA1 = 0x4c,
  20. OP_PUSHDATA2 = 0x4d,
  21. OP_PUSHDATA4 = 0x4e,
  22. OP_1NEGATE = 0x4f,
  23. OP_RESERVED = 0x50,
  24. OP_1 = 0x51,
  25. OP_TRUE=OP_1,
  26. OP_2 = 0x52,
  27. OP_3 = 0x53,
  28. OP_4 = 0x54,
  29. OP_5 = 0x55,
  30. OP_6 = 0x56,
  31. OP_7 = 0x57,
  32. OP_8 = 0x58,
  33. OP_9 = 0x59,
  34. OP_10 = 0x5a,
  35. OP_11 = 0x5b,
  36. OP_12 = 0x5c,
  37. OP_13 = 0x5d,
  38. OP_14 = 0x5e,
  39. OP_15 = 0x5f,
  40. OP_16 = 0x60,
  41. // control
  42. OP_NOP = 0x61,
  43. OP_VER = 0x62,
  44. OP_IF = 0x63,
  45. OP_NOTIF = 0x64,
  46. OP_VERIF = 0x65,
  47. OP_VERNOTIF = 0x66,
  48. OP_ELSE = 0x67,
  49. OP_ENDIF = 0x68,
  50. OP_VERIFY = 0x69,
  51. OP_RETURN = 0x6a,
  52. // stack ops
  53. OP_TOALTSTACK = 0x6b,
  54. OP_FROMALTSTACK = 0x6c,
  55. OP_2DROP = 0x6d,
  56. OP_2DUP = 0x6e,
  57. OP_3DUP = 0x6f,
  58. OP_2OVER = 0x70,
  59. OP_2ROT = 0x71,
  60. OP_2SWAP = 0x72,
  61. OP_IFDUP = 0x73,
  62. OP_DEPTH = 0x74,
  63. OP_DROP = 0x75,
  64. OP_DUP = 0x76,
  65. OP_NIP = 0x77,
  66. OP_OVER = 0x78,
  67. OP_PICK = 0x79,
  68. OP_ROLL = 0x7a,
  69. OP_ROT = 0x7b,
  70. OP_SWAP = 0x7c,
  71. OP_TUCK = 0x7d,
  72. // splice ops
  73. OP_CAT = 0x7e,
  74. OP_SUBSTR = 0x7f,
  75. OP_LEFT = 0x80,
  76. OP_RIGHT = 0x81,
  77. OP_SIZE = 0x82,
  78. // bit logic
  79. OP_INVERT = 0x83,
  80. OP_AND = 0x84,
  81. OP_OR = 0x85,
  82. OP_XOR = 0x86,
  83. OP_EQUAL = 0x87,
  84. OP_EQUALVERIFY = 0x88,
  85. OP_RESERVED1 = 0x89,
  86. OP_RESERVED2 = 0x8a,
  87. // numeric
  88. OP_1ADD = 0x8b,
  89. OP_1SUB = 0x8c,
  90. OP_2MUL = 0x8d,
  91. OP_2DIV = 0x8e,
  92. OP_NEGATE = 0x8f,
  93. OP_ABS = 0x90,
  94. OP_NOT = 0x91,
  95. OP_0NOTEQUAL = 0x92,
  96. OP_ADD = 0x93,
  97. OP_SUB = 0x94,
  98. OP_MUL = 0x95,
  99. OP_DIV = 0x96,
  100. OP_MOD = 0x97,
  101. OP_LSHIFT = 0x98,
  102. OP_RSHIFT = 0x99,
  103. OP_BOOLAND = 0x9a,
  104. OP_BOOLOR = 0x9b,
  105. OP_NUMEQUAL = 0x9c,
  106. OP_NUMEQUALVERIFY = 0x9d,
  107. OP_NUMNOTEQUAL = 0x9e,
  108. OP_LESSTHAN = 0x9f,
  109. OP_GREATERTHAN = 0xa0,
  110. OP_LESSTHANOREQUAL = 0xa1,
  111. OP_GREATERTHANOREQUAL = 0xa2,
  112. OP_MIN = 0xa3,
  113. OP_MAX = 0xa4,
  114. OP_WITHIN = 0xa5,
  115. // crypto
  116. OP_RIPEMD160 = 0xa6,
  117. OP_SHA1 = 0xa7,
  118. OP_SHA256 = 0xa8,
  119. OP_HASH160 = 0xa9,
  120. OP_HASH256 = 0xaa,
  121. OP_CODESEPARATOR = 0xab,
  122. OP_CHECKSIG = 0xac,
  123. OP_CHECKSIGVERIFY = 0xad,
  124. OP_CHECKMULTISIG = 0xae,
  125. OP_CHECKMULTISIGVERIFY = 0xaf,
  126. // expansion
  127. OP_NOP1 = 0xb0,
  128. OP_NOP2 = 0xb1,
  129. OP_NOP3 = 0xb2,
  130. OP_NOP4 = 0xb3,
  131. OP_NOP5 = 0xb4,
  132. OP_NOP6 = 0xb5,
  133. OP_NOP7 = 0xb6,
  134. OP_NOP8 = 0xb7,
  135. OP_NOP9 = 0xb8,
  136. OP_NOP10 = 0xb9,
  137. // template matching params
  138. OP_SMALLDATA = 0xf9,
  139. OP_SMALLINTEGER = 0xfa,
  140. OP_PUBKEYS = 0xfb,
  141. OP_PUBKEYHASH = 0xfd,
  142. OP_PUBKEY = 0xfe,
  143. OP_INVALIDOPCODE = 0xff,
  144. };
  145. const char* GetOpName(opcodetype opcode);
  146. class scriptnum_error : public std::runtime_error
  147. {
  148. public:
  149. explicit scriptnum_error(const std::string& str) : std::runtime_error(str) {}
  150. };
  151. class CScriptNum
  152. {
  153. // Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
  154. // The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
  155. // but results may overflow (and are valid as long as they are not used in a subsequent
  156. // numeric operation). CScriptNum enforces those semantics by storing results as
  157. // an int64 and allowing out-of-range values to be returned as a vector of bytes but
  158. // throwing an exception if arithmetic is done or the result is interpreted as an integer.
  159. public:
  160. explicit CScriptNum(const int64_t& n)
  161. {
  162. m_value = n;
  163. }
  164. explicit CScriptNum(const std::vector<unsigned char>& vch)
  165. {
  166. if (vch.size() > nMaxNumSize)
  167. throw scriptnum_error("CScriptNum(const std::vector<unsigned char>&) : overflow");
  168. m_value = set_vch(vch);
  169. }
  170. inline bool operator==(const int64_t& rhs) const { return m_value == rhs; }
  171. inline bool operator!=(const int64_t& rhs) const { return m_value != rhs; }
  172. inline bool operator<=(const int64_t& rhs) const { return m_value <= rhs; }
  173. inline bool operator< (const int64_t& rhs) const { return m_value < rhs; }
  174. inline bool operator>=(const int64_t& rhs) const { return m_value >= rhs; }
  175. inline bool operator> (const int64_t& rhs) const { return m_value > rhs; }
  176. inline bool operator==(const CScriptNum& rhs) const { return operator==(rhs.m_value); }
  177. inline bool operator!=(const CScriptNum& rhs) const { return operator!=(rhs.m_value); }
  178. inline bool operator<=(const CScriptNum& rhs) const { return operator<=(rhs.m_value); }
  179. inline bool operator< (const CScriptNum& rhs) const { return operator< (rhs.m_value); }
  180. inline bool operator>=(const CScriptNum& rhs) const { return operator>=(rhs.m_value); }
  181. inline bool operator> (const CScriptNum& rhs) const { return operator> (rhs.m_value); }
  182. inline CScriptNum operator+( const int64_t& rhs) const { return CScriptNum(m_value + rhs);}
  183. inline CScriptNum operator-( const int64_t& rhs) const { return CScriptNum(m_value - rhs);}
  184. inline CScriptNum operator+( const CScriptNum& rhs) const { return operator+(rhs.m_value); }
  185. inline CScriptNum operator-( const CScriptNum& rhs) const { return operator-(rhs.m_value); }
  186. inline CScriptNum& operator+=( const CScriptNum& rhs) { return operator+=(rhs.m_value); }
  187. inline CScriptNum& operator-=( const CScriptNum& rhs) { return operator-=(rhs.m_value); }
  188. inline CScriptNum operator-() const
  189. {
  190. assert(m_value != std::numeric_limits<int64_t>::min());
  191. return CScriptNum(-m_value);
  192. }
  193. inline CScriptNum& operator=( const int64_t& rhs)
  194. {
  195. m_value = rhs;
  196. return *this;
  197. }
  198. inline CScriptNum& operator+=( const int64_t& rhs)
  199. {
  200. assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits<int64_t>::max() - rhs) ||
  201. (rhs < 0 && m_value >= std::numeric_limits<int64_t>::min() - rhs));
  202. m_value += rhs;
  203. return *this;
  204. }
  205. inline CScriptNum& operator-=( const int64_t& rhs)
  206. {
  207. assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits<int64_t>::min() + rhs) ||
  208. (rhs < 0 && m_value <= std::numeric_limits<int64_t>::max() + rhs));
  209. m_value -= rhs;
  210. return *this;
  211. }
  212. int getint() const
  213. {
  214. if (m_value > std::numeric_limits<int>::max())
  215. return std::numeric_limits<int>::max();
  216. else if (m_value < std::numeric_limits<int>::min())
  217. return std::numeric_limits<int>::min();
  218. return m_value;
  219. }
  220. std::vector<unsigned char> getvch() const
  221. {
  222. return serialize(m_value);
  223. }
  224. static std::vector<unsigned char> serialize(const int64_t& value)
  225. {
  226. if(value == 0)
  227. return std::vector<unsigned char>();
  228. std::vector<unsigned char> result;
  229. const bool neg = value < 0;
  230. uint64_t absvalue = neg ? -value : value;
  231. while(absvalue)
  232. {
  233. result.push_back(absvalue & 0xff);
  234. absvalue >>= 8;
  235. }
  236. // - If the most significant byte is >= 0x80 and the value is positive, push a
  237. // new zero-byte to make the significant byte < 0x80 again.
  238. // - If the most significant byte is >= 0x80 and the value is negative, push a
  239. // new 0x80 byte that will be popped off when converting to an integral.
  240. // - If the most significant byte is < 0x80 and the value is negative, add
  241. // 0x80 to it, since it will be subtracted and interpreted as a negative when
  242. // converting to an integral.
  243. if (result.back() & 0x80)
  244. result.push_back(neg ? 0x80 : 0);
  245. else if (neg)
  246. result.back() |= 0x80;
  247. return result;
  248. }
  249. static const size_t nMaxNumSize = 4;
  250. private:
  251. static int64_t set_vch(const std::vector<unsigned char>& vch)
  252. {
  253. if (vch.empty())
  254. return 0;
  255. int64_t result = 0;
  256. for (size_t i = 0; i != vch.size(); ++i)
  257. result |= static_cast<int64_t>(vch[i]) << 8*i;
  258. // If the input vector's most significant byte is 0x80, remove it from
  259. // the result's msb and return a negative.
  260. if (vch.back() & 0x80)
  261. return -((int64_t)(result & ~(0x80ULL << (8 * (vch.size() - 1)))));
  262. return result;
  263. }
  264. int64_t m_value;
  265. };
  266. inline std::string ValueString(const std::vector<unsigned char>& vch)
  267. {
  268. if (vch.size() <= 4)
  269. return strprintf("%d", CScriptNum(vch).getint());
  270. else
  271. return HexStr(vch);
  272. }
  273. /** Serialized script, used inside transaction inputs and outputs */
  274. class CScript : public std::vector<unsigned char>
  275. {
  276. protected:
  277. CScript& push_int64(int64_t n)
  278. {
  279. if (n == -1 || (n >= 1 && n <= 16))
  280. {
  281. push_back(n + (OP_1 - 1));
  282. }
  283. else
  284. {
  285. *this << CScriptNum::serialize(n);
  286. }
  287. return *this;
  288. }
  289. public:
  290. CScript() { }
  291. CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
  292. CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
  293. CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
  294. CScript& operator+=(const CScript& b)
  295. {
  296. insert(end(), b.begin(), b.end());
  297. return *this;
  298. }
  299. friend CScript operator+(const CScript& a, const CScript& b)
  300. {
  301. CScript ret = a;
  302. ret += b;
  303. return ret;
  304. }
  305. CScript(int64_t b) { operator<<(b); }
  306. explicit CScript(opcodetype b) { operator<<(b); }
  307. explicit CScript(const uint256& b) { operator<<(b); }
  308. explicit CScript(const CScriptNum& b) { operator<<(b); }
  309. explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
  310. CScript& operator<<(int64_t b) { return push_int64(b); }
  311. CScript& operator<<(opcodetype opcode)
  312. {
  313. if (opcode < 0 || opcode > 0xff)
  314. throw std::runtime_error("CScript::operator<<() : invalid opcode");
  315. insert(end(), (unsigned char)opcode);
  316. return *this;
  317. }
  318. CScript& operator<<(const uint160& b)
  319. {
  320. insert(end(), sizeof(b));
  321. insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
  322. return *this;
  323. }
  324. CScript& operator<<(const uint256& b)
  325. {
  326. insert(end(), sizeof(b));
  327. insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
  328. return *this;
  329. }
  330. CScript& operator<<(const CPubKey& key)
  331. {
  332. assert(key.size() < OP_PUSHDATA1);
  333. insert(end(), (unsigned char)key.size());
  334. insert(end(), key.begin(), key.end());
  335. return *this;
  336. }
  337. CScript& operator<<(const CScriptNum& b)
  338. {
  339. *this << b.getvch();
  340. return *this;
  341. }
  342. CScript& operator<<(const std::vector<unsigned char>& b)
  343. {
  344. if (b.size() < OP_PUSHDATA1)
  345. {
  346. insert(end(), (unsigned char)b.size());
  347. }
  348. else if (b.size() <= 0xff)
  349. {
  350. insert(end(), OP_PUSHDATA1);
  351. insert(end(), (unsigned char)b.size());
  352. }
  353. else if (b.size() <= 0xffff)
  354. {
  355. insert(end(), OP_PUSHDATA2);
  356. unsigned short nSize = b.size();
  357. insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
  358. }
  359. else
  360. {
  361. insert(end(), OP_PUSHDATA4);
  362. unsigned int nSize = b.size();
  363. insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
  364. }
  365. insert(end(), b.begin(), b.end());
  366. return *this;
  367. }
  368. CScript& operator<<(const CScript& b)
  369. {
  370. // I'm not sure if this should push the script or concatenate scripts.
  371. // If there's ever a use for pushing a script onto a script, delete this member fn
  372. assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
  373. return *this;
  374. }
  375. bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
  376. {
  377. // Wrapper so it can be called with either iterator or const_iterator
  378. const_iterator pc2 = pc;
  379. bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
  380. pc = begin() + (pc2 - begin());
  381. return fRet;
  382. }
  383. bool GetOp(iterator& pc, opcodetype& opcodeRet)
  384. {
  385. const_iterator pc2 = pc;
  386. bool fRet = GetOp2(pc2, opcodeRet, NULL);
  387. pc = begin() + (pc2 - begin());
  388. return fRet;
  389. }
  390. bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
  391. {
  392. return GetOp2(pc, opcodeRet, &vchRet);
  393. }
  394. bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
  395. {
  396. return GetOp2(pc, opcodeRet, NULL);
  397. }
  398. bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
  399. {
  400. opcodeRet = OP_INVALIDOPCODE;
  401. if (pvchRet)
  402. pvchRet->clear();
  403. if (pc >= end())
  404. return false;
  405. // Read instruction
  406. if (end() - pc < 1)
  407. return false;
  408. unsigned int opcode = *pc++;
  409. // Immediate operand
  410. if (opcode <= OP_PUSHDATA4)
  411. {
  412. unsigned int nSize = 0;
  413. if (opcode < OP_PUSHDATA1)
  414. {
  415. nSize = opcode;
  416. }
  417. else if (opcode == OP_PUSHDATA1)
  418. {
  419. if (end() - pc < 1)
  420. return false;
  421. nSize = *pc++;
  422. }
  423. else if (opcode == OP_PUSHDATA2)
  424. {
  425. if (end() - pc < 2)
  426. return false;
  427. nSize = 0;
  428. memcpy(&nSize, &pc[0], 2);
  429. pc += 2;
  430. }
  431. else if (opcode == OP_PUSHDATA4)
  432. {
  433. if (end() - pc < 4)
  434. return false;
  435. memcpy(&nSize, &pc[0], 4);
  436. pc += 4;
  437. }
  438. if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
  439. return false;
  440. if (pvchRet)
  441. pvchRet->assign(pc, pc + nSize);
  442. pc += nSize;
  443. }
  444. opcodeRet = (opcodetype)opcode;
  445. return true;
  446. }
  447. // Encode/decode small integers:
  448. static int DecodeOP_N(opcodetype opcode)
  449. {
  450. if (opcode == OP_0)
  451. return 0;
  452. assert(opcode >= OP_1 && opcode <= OP_16);
  453. return (int)opcode - (int)(OP_1 - 1);
  454. }
  455. static opcodetype EncodeOP_N(int n)
  456. {
  457. assert(n >= 0 && n <= 16);
  458. if (n == 0)
  459. return OP_0;
  460. return (opcodetype)(OP_1+n-1);
  461. }
  462. int FindAndDelete(const CScript& b)
  463. {
  464. int nFound = 0;
  465. if (b.empty())
  466. return nFound;
  467. iterator pc = begin();
  468. opcodetype opcode;
  469. do
  470. {
  471. while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
  472. {
  473. pc = erase(pc, pc + b.size());
  474. ++nFound;
  475. }
  476. }
  477. while (GetOp(pc, opcode));
  478. return nFound;
  479. }
  480. int Find(opcodetype op) const
  481. {
  482. int nFound = 0;
  483. opcodetype opcode;
  484. for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
  485. if (opcode == op)
  486. ++nFound;
  487. return nFound;
  488. }
  489. // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
  490. // as 20 sigops. With pay-to-script-hash, that changed:
  491. // CHECKMULTISIGs serialized in scriptSigs are
  492. // counted more accurately, assuming they are of the form
  493. // ... OP_N CHECKMULTISIG ...
  494. unsigned int GetSigOpCount(bool fAccurate) const;
  495. // Accurately count sigOps, including sigOps in
  496. // pay-to-script-hash transactions:
  497. unsigned int GetSigOpCount(const CScript& scriptSig) const;
  498. bool IsPayToScriptHash() const;
  499. // Called by IsStandardTx and P2SH VerifyScript (which makes it consensus-critical).
  500. bool IsPushOnly() const;
  501. // Called by IsStandardTx.
  502. bool HasCanonicalPushes() const;
  503. // Returns whether the script is guaranteed to fail at execution,
  504. // regardless of the initial stack. This allows outputs to be pruned
  505. // instantly when entering the UTXO set.
  506. bool IsUnspendable() const
  507. {
  508. return (size() > 0 && *begin() == OP_RETURN);
  509. }
  510. std::string ToString() const
  511. {
  512. std::string str;
  513. opcodetype opcode;
  514. std::vector<unsigned char> vch;
  515. const_iterator pc = begin();
  516. while (pc < end())
  517. {
  518. if (!str.empty())
  519. str += " ";
  520. if (!GetOp(pc, opcode, vch))
  521. {
  522. str += "[error]";
  523. return str;
  524. }
  525. if (0 <= opcode && opcode <= OP_PUSHDATA4)
  526. str += ValueString(vch);
  527. else
  528. str += GetOpName(opcode);
  529. }
  530. return str;
  531. }
  532. CScriptID GetID() const
  533. {
  534. return CScriptID(Hash160(*this));
  535. }
  536. void clear()
  537. {
  538. // The default std::vector::clear() does not release memory.
  539. std::vector<unsigned char>().swap(*this);
  540. }
  541. };
  542. #endif // H_BITCOIN_SCRIPT