Add constant for maximum stack size
[bitcoinplatinum.git] / src / script / script.h
blob95a5999a13b538be8d87a984b2c60ec608399a8c
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #ifndef BITCOIN_SCRIPT_SCRIPT_H
7 #define BITCOIN_SCRIPT_SCRIPT_H
9 #include "crypto/common.h"
10 #include "prevector.h"
12 #include <assert.h>
13 #include <climits>
14 #include <limits>
15 #include <stdexcept>
16 #include <stdint.h>
17 #include <string.h>
18 #include <string>
19 #include <vector>
21 // Maximum number of bytes pushable to the stack
22 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520;
24 // Maximum number of non-push operations per script
25 static const int MAX_OPS_PER_SCRIPT = 201;
27 // Maximum number of public keys per multisig
28 static const int MAX_PUBKEYS_PER_MULTISIG = 20;
30 // Maximum script length in bytes
31 static const int MAX_SCRIPT_SIZE = 10000;
33 // Maximum number of values on script interpreter stack
34 static const int MAX_STACK_SIZE = 1000;
36 // Threshold for nLockTime: below this value it is interpreted as block number,
37 // otherwise as UNIX timestamp.
38 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
40 template <typename T>
41 std::vector<unsigned char> ToByteVector(const T& in)
43 return std::vector<unsigned char>(in.begin(), in.end());
46 /** Script opcodes */
47 enum opcodetype
49 // push value
50 OP_0 = 0x00,
51 OP_FALSE = OP_0,
52 OP_PUSHDATA1 = 0x4c,
53 OP_PUSHDATA2 = 0x4d,
54 OP_PUSHDATA4 = 0x4e,
55 OP_1NEGATE = 0x4f,
56 OP_RESERVED = 0x50,
57 OP_1 = 0x51,
58 OP_TRUE=OP_1,
59 OP_2 = 0x52,
60 OP_3 = 0x53,
61 OP_4 = 0x54,
62 OP_5 = 0x55,
63 OP_6 = 0x56,
64 OP_7 = 0x57,
65 OP_8 = 0x58,
66 OP_9 = 0x59,
67 OP_10 = 0x5a,
68 OP_11 = 0x5b,
69 OP_12 = 0x5c,
70 OP_13 = 0x5d,
71 OP_14 = 0x5e,
72 OP_15 = 0x5f,
73 OP_16 = 0x60,
75 // control
76 OP_NOP = 0x61,
77 OP_VER = 0x62,
78 OP_IF = 0x63,
79 OP_NOTIF = 0x64,
80 OP_VERIF = 0x65,
81 OP_VERNOTIF = 0x66,
82 OP_ELSE = 0x67,
83 OP_ENDIF = 0x68,
84 OP_VERIFY = 0x69,
85 OP_RETURN = 0x6a,
87 // stack ops
88 OP_TOALTSTACK = 0x6b,
89 OP_FROMALTSTACK = 0x6c,
90 OP_2DROP = 0x6d,
91 OP_2DUP = 0x6e,
92 OP_3DUP = 0x6f,
93 OP_2OVER = 0x70,
94 OP_2ROT = 0x71,
95 OP_2SWAP = 0x72,
96 OP_IFDUP = 0x73,
97 OP_DEPTH = 0x74,
98 OP_DROP = 0x75,
99 OP_DUP = 0x76,
100 OP_NIP = 0x77,
101 OP_OVER = 0x78,
102 OP_PICK = 0x79,
103 OP_ROLL = 0x7a,
104 OP_ROT = 0x7b,
105 OP_SWAP = 0x7c,
106 OP_TUCK = 0x7d,
108 // splice ops
109 OP_CAT = 0x7e,
110 OP_SUBSTR = 0x7f,
111 OP_LEFT = 0x80,
112 OP_RIGHT = 0x81,
113 OP_SIZE = 0x82,
115 // bit logic
116 OP_INVERT = 0x83,
117 OP_AND = 0x84,
118 OP_OR = 0x85,
119 OP_XOR = 0x86,
120 OP_EQUAL = 0x87,
121 OP_EQUALVERIFY = 0x88,
122 OP_RESERVED1 = 0x89,
123 OP_RESERVED2 = 0x8a,
125 // numeric
126 OP_1ADD = 0x8b,
127 OP_1SUB = 0x8c,
128 OP_2MUL = 0x8d,
129 OP_2DIV = 0x8e,
130 OP_NEGATE = 0x8f,
131 OP_ABS = 0x90,
132 OP_NOT = 0x91,
133 OP_0NOTEQUAL = 0x92,
135 OP_ADD = 0x93,
136 OP_SUB = 0x94,
137 OP_MUL = 0x95,
138 OP_DIV = 0x96,
139 OP_MOD = 0x97,
140 OP_LSHIFT = 0x98,
141 OP_RSHIFT = 0x99,
143 OP_BOOLAND = 0x9a,
144 OP_BOOLOR = 0x9b,
145 OP_NUMEQUAL = 0x9c,
146 OP_NUMEQUALVERIFY = 0x9d,
147 OP_NUMNOTEQUAL = 0x9e,
148 OP_LESSTHAN = 0x9f,
149 OP_GREATERTHAN = 0xa0,
150 OP_LESSTHANOREQUAL = 0xa1,
151 OP_GREATERTHANOREQUAL = 0xa2,
152 OP_MIN = 0xa3,
153 OP_MAX = 0xa4,
155 OP_WITHIN = 0xa5,
157 // crypto
158 OP_RIPEMD160 = 0xa6,
159 OP_SHA1 = 0xa7,
160 OP_SHA256 = 0xa8,
161 OP_HASH160 = 0xa9,
162 OP_HASH256 = 0xaa,
163 OP_CODESEPARATOR = 0xab,
164 OP_CHECKSIG = 0xac,
165 OP_CHECKSIGVERIFY = 0xad,
166 OP_CHECKMULTISIG = 0xae,
167 OP_CHECKMULTISIGVERIFY = 0xaf,
169 // expansion
170 OP_NOP1 = 0xb0,
171 OP_CHECKLOCKTIMEVERIFY = 0xb1,
172 OP_NOP2 = OP_CHECKLOCKTIMEVERIFY,
173 OP_CHECKSEQUENCEVERIFY = 0xb2,
174 OP_NOP3 = OP_CHECKSEQUENCEVERIFY,
175 OP_NOP4 = 0xb3,
176 OP_NOP5 = 0xb4,
177 OP_NOP6 = 0xb5,
178 OP_NOP7 = 0xb6,
179 OP_NOP8 = 0xb7,
180 OP_NOP9 = 0xb8,
181 OP_NOP10 = 0xb9,
184 // template matching params
185 OP_SMALLINTEGER = 0xfa,
186 OP_PUBKEYS = 0xfb,
187 OP_PUBKEYHASH = 0xfd,
188 OP_PUBKEY = 0xfe,
190 OP_INVALIDOPCODE = 0xff,
193 const char* GetOpName(opcodetype opcode);
195 class scriptnum_error : public std::runtime_error
197 public:
198 explicit scriptnum_error(const std::string& str) : std::runtime_error(str) {}
201 class CScriptNum
204 * Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
205 * The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
206 * but results may overflow (and are valid as long as they are not used in a subsequent
207 * numeric operation). CScriptNum enforces those semantics by storing results as
208 * an int64 and allowing out-of-range values to be returned as a vector of bytes but
209 * throwing an exception if arithmetic is done or the result is interpreted as an integer.
211 public:
213 explicit CScriptNum(const int64_t& n)
215 m_value = n;
218 static const size_t nDefaultMaxNumSize = 4;
220 explicit CScriptNum(const std::vector<unsigned char>& vch, bool fRequireMinimal,
221 const size_t nMaxNumSize = nDefaultMaxNumSize)
223 if (vch.size() > nMaxNumSize) {
224 throw scriptnum_error("script number overflow");
226 if (fRequireMinimal && vch.size() > 0) {
227 // Check that the number is encoded with the minimum possible
228 // number of bytes.
230 // If the most-significant-byte - excluding the sign bit - is zero
231 // then we're not minimal. Note how this test also rejects the
232 // negative-zero encoding, 0x80.
233 if ((vch.back() & 0x7f) == 0) {
234 // One exception: if there's more than one byte and the most
235 // significant bit of the second-most-significant-byte is set
236 // it would conflict with the sign bit. An example of this case
237 // is +-255, which encode to 0xff00 and 0xff80 respectively.
238 // (big-endian).
239 if (vch.size() <= 1 || (vch[vch.size() - 2] & 0x80) == 0) {
240 throw scriptnum_error("non-minimally encoded script number");
244 m_value = set_vch(vch);
247 inline bool operator==(const int64_t& rhs) const { return m_value == rhs; }
248 inline bool operator!=(const int64_t& rhs) const { return m_value != rhs; }
249 inline bool operator<=(const int64_t& rhs) const { return m_value <= rhs; }
250 inline bool operator< (const int64_t& rhs) const { return m_value < rhs; }
251 inline bool operator>=(const int64_t& rhs) const { return m_value >= rhs; }
252 inline bool operator> (const int64_t& rhs) const { return m_value > rhs; }
254 inline bool operator==(const CScriptNum& rhs) const { return operator==(rhs.m_value); }
255 inline bool operator!=(const CScriptNum& rhs) const { return operator!=(rhs.m_value); }
256 inline bool operator<=(const CScriptNum& rhs) const { return operator<=(rhs.m_value); }
257 inline bool operator< (const CScriptNum& rhs) const { return operator< (rhs.m_value); }
258 inline bool operator>=(const CScriptNum& rhs) const { return operator>=(rhs.m_value); }
259 inline bool operator> (const CScriptNum& rhs) const { return operator> (rhs.m_value); }
261 inline CScriptNum operator+( const int64_t& rhs) const { return CScriptNum(m_value + rhs);}
262 inline CScriptNum operator-( const int64_t& rhs) const { return CScriptNum(m_value - rhs);}
263 inline CScriptNum operator+( const CScriptNum& rhs) const { return operator+(rhs.m_value); }
264 inline CScriptNum operator-( const CScriptNum& rhs) const { return operator-(rhs.m_value); }
266 inline CScriptNum& operator+=( const CScriptNum& rhs) { return operator+=(rhs.m_value); }
267 inline CScriptNum& operator-=( const CScriptNum& rhs) { return operator-=(rhs.m_value); }
269 inline CScriptNum operator&( const int64_t& rhs) const { return CScriptNum(m_value & rhs);}
270 inline CScriptNum operator&( const CScriptNum& rhs) const { return operator&(rhs.m_value); }
272 inline CScriptNum& operator&=( const CScriptNum& rhs) { return operator&=(rhs.m_value); }
274 inline CScriptNum operator-() const
276 assert(m_value != std::numeric_limits<int64_t>::min());
277 return CScriptNum(-m_value);
280 inline CScriptNum& operator=( const int64_t& rhs)
282 m_value = rhs;
283 return *this;
286 inline CScriptNum& operator+=( const int64_t& rhs)
288 assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits<int64_t>::max() - rhs) ||
289 (rhs < 0 && m_value >= std::numeric_limits<int64_t>::min() - rhs));
290 m_value += rhs;
291 return *this;
294 inline CScriptNum& operator-=( const int64_t& rhs)
296 assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits<int64_t>::min() + rhs) ||
297 (rhs < 0 && m_value <= std::numeric_limits<int64_t>::max() + rhs));
298 m_value -= rhs;
299 return *this;
302 inline CScriptNum& operator&=( const int64_t& rhs)
304 m_value &= rhs;
305 return *this;
308 int getint() const
310 if (m_value > std::numeric_limits<int>::max())
311 return std::numeric_limits<int>::max();
312 else if (m_value < std::numeric_limits<int>::min())
313 return std::numeric_limits<int>::min();
314 return m_value;
317 std::vector<unsigned char> getvch() const
319 return serialize(m_value);
322 static std::vector<unsigned char> serialize(const int64_t& value)
324 if(value == 0)
325 return std::vector<unsigned char>();
327 std::vector<unsigned char> result;
328 const bool neg = value < 0;
329 uint64_t absvalue = neg ? -value : value;
331 while(absvalue)
333 result.push_back(absvalue & 0xff);
334 absvalue >>= 8;
337 // - If the most significant byte is >= 0x80 and the value is positive, push a
338 // new zero-byte to make the significant byte < 0x80 again.
340 // - If the most significant byte is >= 0x80 and the value is negative, push a
341 // new 0x80 byte that will be popped off when converting to an integral.
343 // - If the most significant byte is < 0x80 and the value is negative, add
344 // 0x80 to it, since it will be subtracted and interpreted as a negative when
345 // converting to an integral.
347 if (result.back() & 0x80)
348 result.push_back(neg ? 0x80 : 0);
349 else if (neg)
350 result.back() |= 0x80;
352 return result;
355 private:
356 static int64_t set_vch(const std::vector<unsigned char>& vch)
358 if (vch.empty())
359 return 0;
361 int64_t result = 0;
362 for (size_t i = 0; i != vch.size(); ++i)
363 result |= static_cast<int64_t>(vch[i]) << 8*i;
365 // If the input vector's most significant byte is 0x80, remove it from
366 // the result's msb and return a negative.
367 if (vch.back() & 0x80)
368 return -((int64_t)(result & ~(0x80ULL << (8 * (vch.size() - 1)))));
370 return result;
373 int64_t m_value;
376 typedef prevector<28, unsigned char> CScriptBase;
378 /** Serialized script, used inside transaction inputs and outputs */
379 class CScript : public CScriptBase
381 protected:
382 CScript& push_int64(int64_t n)
384 if (n == -1 || (n >= 1 && n <= 16))
386 push_back(n + (OP_1 - 1));
388 else if (n == 0)
390 push_back(OP_0);
392 else
394 *this << CScriptNum::serialize(n);
396 return *this;
398 public:
399 CScript() { }
400 CScript(const_iterator pbegin, const_iterator pend) : CScriptBase(pbegin, pend) { }
401 CScript(std::vector<unsigned char>::const_iterator pbegin, std::vector<unsigned char>::const_iterator pend) : CScriptBase(pbegin, pend) { }
402 CScript(const unsigned char* pbegin, const unsigned char* pend) : CScriptBase(pbegin, pend) { }
404 CScript& operator+=(const CScript& b)
406 insert(end(), b.begin(), b.end());
407 return *this;
410 friend CScript operator+(const CScript& a, const CScript& b)
412 CScript ret = a;
413 ret += b;
414 return ret;
417 CScript(int64_t b) { operator<<(b); }
419 explicit CScript(opcodetype b) { operator<<(b); }
420 explicit CScript(const CScriptNum& b) { operator<<(b); }
421 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
424 CScript& operator<<(int64_t b) { return push_int64(b); }
426 CScript& operator<<(opcodetype opcode)
428 if (opcode < 0 || opcode > 0xff)
429 throw std::runtime_error("CScript::operator<<(): invalid opcode");
430 insert(end(), (unsigned char)opcode);
431 return *this;
434 CScript& operator<<(const CScriptNum& b)
436 *this << b.getvch();
437 return *this;
440 CScript& operator<<(const std::vector<unsigned char>& b)
442 if (b.size() < OP_PUSHDATA1)
444 insert(end(), (unsigned char)b.size());
446 else if (b.size() <= 0xff)
448 insert(end(), OP_PUSHDATA1);
449 insert(end(), (unsigned char)b.size());
451 else if (b.size() <= 0xffff)
453 insert(end(), OP_PUSHDATA2);
454 uint8_t _data[2];
455 WriteLE16(_data, b.size());
456 insert(end(), _data, _data + sizeof(_data));
458 else
460 insert(end(), OP_PUSHDATA4);
461 uint8_t _data[4];
462 WriteLE32(_data, b.size());
463 insert(end(), _data, _data + sizeof(_data));
465 insert(end(), b.begin(), b.end());
466 return *this;
469 CScript& operator<<(const CScript& b)
471 // I'm not sure if this should push the script or concatenate scripts.
472 // If there's ever a use for pushing a script onto a script, delete this member fn
473 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
474 return *this;
478 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
480 // Wrapper so it can be called with either iterator or const_iterator
481 const_iterator pc2 = pc;
482 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
483 pc = begin() + (pc2 - begin());
484 return fRet;
487 bool GetOp(iterator& pc, opcodetype& opcodeRet)
489 const_iterator pc2 = pc;
490 bool fRet = GetOp2(pc2, opcodeRet, NULL);
491 pc = begin() + (pc2 - begin());
492 return fRet;
495 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
497 return GetOp2(pc, opcodeRet, &vchRet);
500 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
502 return GetOp2(pc, opcodeRet, NULL);
505 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
507 opcodeRet = OP_INVALIDOPCODE;
508 if (pvchRet)
509 pvchRet->clear();
510 if (pc >= end())
511 return false;
513 // Read instruction
514 if (end() - pc < 1)
515 return false;
516 unsigned int opcode = *pc++;
518 // Immediate operand
519 if (opcode <= OP_PUSHDATA4)
521 unsigned int nSize = 0;
522 if (opcode < OP_PUSHDATA1)
524 nSize = opcode;
526 else if (opcode == OP_PUSHDATA1)
528 if (end() - pc < 1)
529 return false;
530 nSize = *pc++;
532 else if (opcode == OP_PUSHDATA2)
534 if (end() - pc < 2)
535 return false;
536 nSize = ReadLE16(&pc[0]);
537 pc += 2;
539 else if (opcode == OP_PUSHDATA4)
541 if (end() - pc < 4)
542 return false;
543 nSize = ReadLE32(&pc[0]);
544 pc += 4;
546 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
547 return false;
548 if (pvchRet)
549 pvchRet->assign(pc, pc + nSize);
550 pc += nSize;
553 opcodeRet = (opcodetype)opcode;
554 return true;
557 /** Encode/decode small integers: */
558 static int DecodeOP_N(opcodetype opcode)
560 if (opcode == OP_0)
561 return 0;
562 assert(opcode >= OP_1 && opcode <= OP_16);
563 return (int)opcode - (int)(OP_1 - 1);
565 static opcodetype EncodeOP_N(int n)
567 assert(n >= 0 && n <= 16);
568 if (n == 0)
569 return OP_0;
570 return (opcodetype)(OP_1+n-1);
573 int FindAndDelete(const CScript& b)
575 int nFound = 0;
576 if (b.empty())
577 return nFound;
578 CScript result;
579 iterator pc = begin(), pc2 = begin();
580 opcodetype opcode;
583 result.insert(result.end(), pc2, pc);
584 while (static_cast<size_t>(end() - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
586 pc = pc + b.size();
587 ++nFound;
589 pc2 = pc;
591 while (GetOp(pc, opcode));
593 if (nFound > 0) {
594 result.insert(result.end(), pc2, end());
595 *this = result;
598 return nFound;
600 int Find(opcodetype op) const
602 int nFound = 0;
603 opcodetype opcode;
604 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
605 if (opcode == op)
606 ++nFound;
607 return nFound;
611 * Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
612 * as 20 sigops. With pay-to-script-hash, that changed:
613 * CHECKMULTISIGs serialized in scriptSigs are
614 * counted more accurately, assuming they are of the form
615 * ... OP_N CHECKMULTISIG ...
617 unsigned int GetSigOpCount(bool fAccurate) const;
620 * Accurately count sigOps, including sigOps in
621 * pay-to-script-hash transactions:
623 unsigned int GetSigOpCount(const CScript& scriptSig) const;
625 bool IsPayToScriptHash() const;
626 bool IsPayToWitnessScriptHash() const;
627 bool IsWitnessProgram(int& version, std::vector<unsigned char>& program) const;
629 /** Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical). */
630 bool IsPushOnly(const_iterator pc) const;
631 bool IsPushOnly() const;
634 * Returns whether the script is guaranteed to fail at execution,
635 * regardless of the initial stack. This allows outputs to be pruned
636 * instantly when entering the UTXO set.
638 bool IsUnspendable() const
640 return (size() > 0 && *begin() == OP_RETURN) || (size() > MAX_SCRIPT_SIZE);
643 void clear()
645 // The default std::vector::clear() does not release memory.
646 CScriptBase().swap(*this);
650 struct CScriptWitness
652 // Note that this encodes the data elements being pushed, rather than
653 // encoding them as a CScript that pushes them.
654 std::vector<std::vector<unsigned char> > stack;
656 // Some compilers complain without a default constructor
657 CScriptWitness() { }
659 bool IsNull() const { return stack.empty(); }
661 void SetNull() { stack.clear(); stack.shrink_to_fit(); }
663 std::string ToString() const;
666 class CReserveScript
668 public:
669 CScript reserveScript;
670 virtual void KeepScript() {}
671 CReserveScript() {}
672 virtual ~CReserveScript() {}
675 #endif // BITCOIN_SCRIPT_SCRIPT_H