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

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