scripted-diff: Use the C++11 keyword nullptr to denote the pointer literal instead...
[bitcoinplatinum.git] / src / script / script.h
blob711ffa97f81257341d6517840fc44033ee19d51c
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"
11 #include "serialize.h"
13 #include <assert.h>
14 #include <climits>
15 #include <limits>
16 #include <stdexcept>
17 #include <stdint.h>
18 #include <string.h>
19 #include <string>
20 #include <vector>
22 // Maximum number of bytes pushable to the stack
23 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520;
25 // Maximum number of non-push operations per script
26 static const int MAX_OPS_PER_SCRIPT = 201;
28 // Maximum number of public keys per multisig
29 static const int MAX_PUBKEYS_PER_MULTISIG = 20;
31 // Maximum script length in bytes
32 static const int MAX_SCRIPT_SIZE = 10000;
34 // Maximum number of values on script interpreter stack
35 static const int MAX_STACK_SIZE = 1000;
37 // Threshold for nLockTime: below this value it is interpreted as block number,
38 // otherwise as UNIX timestamp.
39 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
41 template <typename T>
42 std::vector<unsigned char> ToByteVector(const T& in)
44 return std::vector<unsigned char>(in.begin(), in.end());
47 /** Script opcodes */
48 enum opcodetype
50 // push value
51 OP_0 = 0x00,
52 OP_FALSE = OP_0,
53 OP_PUSHDATA1 = 0x4c,
54 OP_PUSHDATA2 = 0x4d,
55 OP_PUSHDATA4 = 0x4e,
56 OP_1NEGATE = 0x4f,
57 OP_RESERVED = 0x50,
58 OP_1 = 0x51,
59 OP_TRUE=OP_1,
60 OP_2 = 0x52,
61 OP_3 = 0x53,
62 OP_4 = 0x54,
63 OP_5 = 0x55,
64 OP_6 = 0x56,
65 OP_7 = 0x57,
66 OP_8 = 0x58,
67 OP_9 = 0x59,
68 OP_10 = 0x5a,
69 OP_11 = 0x5b,
70 OP_12 = 0x5c,
71 OP_13 = 0x5d,
72 OP_14 = 0x5e,
73 OP_15 = 0x5f,
74 OP_16 = 0x60,
76 // control
77 OP_NOP = 0x61,
78 OP_VER = 0x62,
79 OP_IF = 0x63,
80 OP_NOTIF = 0x64,
81 OP_VERIF = 0x65,
82 OP_VERNOTIF = 0x66,
83 OP_ELSE = 0x67,
84 OP_ENDIF = 0x68,
85 OP_VERIFY = 0x69,
86 OP_RETURN = 0x6a,
88 // stack ops
89 OP_TOALTSTACK = 0x6b,
90 OP_FROMALTSTACK = 0x6c,
91 OP_2DROP = 0x6d,
92 OP_2DUP = 0x6e,
93 OP_3DUP = 0x6f,
94 OP_2OVER = 0x70,
95 OP_2ROT = 0x71,
96 OP_2SWAP = 0x72,
97 OP_IFDUP = 0x73,
98 OP_DEPTH = 0x74,
99 OP_DROP = 0x75,
100 OP_DUP = 0x76,
101 OP_NIP = 0x77,
102 OP_OVER = 0x78,
103 OP_PICK = 0x79,
104 OP_ROLL = 0x7a,
105 OP_ROT = 0x7b,
106 OP_SWAP = 0x7c,
107 OP_TUCK = 0x7d,
109 // splice ops
110 OP_CAT = 0x7e,
111 OP_SUBSTR = 0x7f,
112 OP_LEFT = 0x80,
113 OP_RIGHT = 0x81,
114 OP_SIZE = 0x82,
116 // bit logic
117 OP_INVERT = 0x83,
118 OP_AND = 0x84,
119 OP_OR = 0x85,
120 OP_XOR = 0x86,
121 OP_EQUAL = 0x87,
122 OP_EQUALVERIFY = 0x88,
123 OP_RESERVED1 = 0x89,
124 OP_RESERVED2 = 0x8a,
126 // numeric
127 OP_1ADD = 0x8b,
128 OP_1SUB = 0x8c,
129 OP_2MUL = 0x8d,
130 OP_2DIV = 0x8e,
131 OP_NEGATE = 0x8f,
132 OP_ABS = 0x90,
133 OP_NOT = 0x91,
134 OP_0NOTEQUAL = 0x92,
136 OP_ADD = 0x93,
137 OP_SUB = 0x94,
138 OP_MUL = 0x95,
139 OP_DIV = 0x96,
140 OP_MOD = 0x97,
141 OP_LSHIFT = 0x98,
142 OP_RSHIFT = 0x99,
144 OP_BOOLAND = 0x9a,
145 OP_BOOLOR = 0x9b,
146 OP_NUMEQUAL = 0x9c,
147 OP_NUMEQUALVERIFY = 0x9d,
148 OP_NUMNOTEQUAL = 0x9e,
149 OP_LESSTHAN = 0x9f,
150 OP_GREATERTHAN = 0xa0,
151 OP_LESSTHANOREQUAL = 0xa1,
152 OP_GREATERTHANOREQUAL = 0xa2,
153 OP_MIN = 0xa3,
154 OP_MAX = 0xa4,
156 OP_WITHIN = 0xa5,
158 // crypto
159 OP_RIPEMD160 = 0xa6,
160 OP_SHA1 = 0xa7,
161 OP_SHA256 = 0xa8,
162 OP_HASH160 = 0xa9,
163 OP_HASH256 = 0xaa,
164 OP_CODESEPARATOR = 0xab,
165 OP_CHECKSIG = 0xac,
166 OP_CHECKSIGVERIFY = 0xad,
167 OP_CHECKMULTISIG = 0xae,
168 OP_CHECKMULTISIGVERIFY = 0xaf,
170 // expansion
171 OP_NOP1 = 0xb0,
172 OP_CHECKLOCKTIMEVERIFY = 0xb1,
173 OP_NOP2 = OP_CHECKLOCKTIMEVERIFY,
174 OP_CHECKSEQUENCEVERIFY = 0xb2,
175 OP_NOP3 = OP_CHECKSEQUENCEVERIFY,
176 OP_NOP4 = 0xb3,
177 OP_NOP5 = 0xb4,
178 OP_NOP6 = 0xb5,
179 OP_NOP7 = 0xb6,
180 OP_NOP8 = 0xb7,
181 OP_NOP9 = 0xb8,
182 OP_NOP10 = 0xb9,
185 // template matching params
186 OP_SMALLINTEGER = 0xfa,
187 OP_PUBKEYS = 0xfb,
188 OP_PUBKEYHASH = 0xfd,
189 OP_PUBKEY = 0xfe,
191 OP_INVALIDOPCODE = 0xff,
194 // Maximum value that an opcode can be
195 static const unsigned int MAX_OPCODE = OP_NOP10;
197 const char* GetOpName(opcodetype opcode);
199 class scriptnum_error : public std::runtime_error
201 public:
202 explicit scriptnum_error(const std::string& str) : std::runtime_error(str) {}
205 class CScriptNum
208 * Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
209 * The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
210 * but results may overflow (and are valid as long as they are not used in a subsequent
211 * numeric operation). CScriptNum enforces those semantics by storing results as
212 * an int64 and allowing out-of-range values to be returned as a vector of bytes but
213 * throwing an exception if arithmetic is done or the result is interpreted as an integer.
215 public:
217 explicit CScriptNum(const int64_t& n)
219 m_value = n;
222 static const size_t nDefaultMaxNumSize = 4;
224 explicit CScriptNum(const std::vector<unsigned char>& vch, bool fRequireMinimal,
225 const size_t nMaxNumSize = nDefaultMaxNumSize)
227 if (vch.size() > nMaxNumSize) {
228 throw scriptnum_error("script number overflow");
230 if (fRequireMinimal && vch.size() > 0) {
231 // Check that the number is encoded with the minimum possible
232 // number of bytes.
234 // If the most-significant-byte - excluding the sign bit - is zero
235 // then we're not minimal. Note how this test also rejects the
236 // negative-zero encoding, 0x80.
237 if ((vch.back() & 0x7f) == 0) {
238 // One exception: if there's more than one byte and the most
239 // significant bit of the second-most-significant-byte is set
240 // it would conflict with the sign bit. An example of this case
241 // is +-255, which encode to 0xff00 and 0xff80 respectively.
242 // (big-endian).
243 if (vch.size() <= 1 || (vch[vch.size() - 2] & 0x80) == 0) {
244 throw scriptnum_error("non-minimally encoded script number");
248 m_value = set_vch(vch);
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; }
253 inline bool operator<=(const int64_t& rhs) const { return m_value <= rhs; }
254 inline bool operator< (const int64_t& rhs) const { return m_value < rhs; }
255 inline bool operator>=(const int64_t& rhs) const { return m_value >= rhs; }
256 inline bool operator> (const int64_t& rhs) const { return m_value > rhs; }
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); }
260 inline bool operator<=(const CScriptNum& rhs) const { return operator<=(rhs.m_value); }
261 inline bool operator< (const CScriptNum& rhs) const { return operator< (rhs.m_value); }
262 inline bool operator>=(const CScriptNum& rhs) const { return operator>=(rhs.m_value); }
263 inline bool operator> (const CScriptNum& rhs) const { return operator> (rhs.m_value); }
265 inline CScriptNum operator+( const int64_t& rhs) const { return CScriptNum(m_value + rhs);}
266 inline CScriptNum operator-( const int64_t& rhs) const { return CScriptNum(m_value - rhs);}
267 inline CScriptNum operator+( const CScriptNum& rhs) const { return operator+(rhs.m_value); }
268 inline CScriptNum operator-( const CScriptNum& rhs) const { return operator-(rhs.m_value); }
270 inline CScriptNum& operator+=( const CScriptNum& rhs) { return operator+=(rhs.m_value); }
271 inline CScriptNum& operator-=( const CScriptNum& rhs) { return operator-=(rhs.m_value); }
273 inline CScriptNum operator&( const int64_t& rhs) const { return CScriptNum(m_value & rhs);}
274 inline CScriptNum operator&( const CScriptNum& rhs) const { return operator&(rhs.m_value); }
276 inline CScriptNum& operator&=( const CScriptNum& rhs) { return operator&=(rhs.m_value); }
278 inline CScriptNum operator-() const
280 assert(m_value != std::numeric_limits<int64_t>::min());
281 return CScriptNum(-m_value);
284 inline CScriptNum& operator=( const int64_t& rhs)
286 m_value = rhs;
287 return *this;
290 inline CScriptNum& operator+=( const int64_t& rhs)
292 assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits<int64_t>::max() - rhs) ||
293 (rhs < 0 && m_value >= std::numeric_limits<int64_t>::min() - rhs));
294 m_value += rhs;
295 return *this;
298 inline CScriptNum& operator-=( const int64_t& rhs)
300 assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits<int64_t>::min() + rhs) ||
301 (rhs < 0 && m_value <= std::numeric_limits<int64_t>::max() + rhs));
302 m_value -= rhs;
303 return *this;
306 inline CScriptNum& operator&=( const int64_t& rhs)
308 m_value &= rhs;
309 return *this;
312 int getint() const
314 if (m_value > std::numeric_limits<int>::max())
315 return std::numeric_limits<int>::max();
316 else if (m_value < std::numeric_limits<int>::min())
317 return std::numeric_limits<int>::min();
318 return m_value;
321 std::vector<unsigned char> getvch() const
323 return serialize(m_value);
326 static std::vector<unsigned char> serialize(const int64_t& value)
328 if(value == 0)
329 return std::vector<unsigned char>();
331 std::vector<unsigned char> result;
332 const bool neg = value < 0;
333 uint64_t absvalue = neg ? -value : value;
335 while(absvalue)
337 result.push_back(absvalue & 0xff);
338 absvalue >>= 8;
341 // - If the most significant byte is >= 0x80 and the value is positive, push a
342 // new zero-byte to make the significant byte < 0x80 again.
344 // - If the most significant byte is >= 0x80 and the value is negative, push a
345 // new 0x80 byte that will be popped off when converting to an integral.
347 // - If the most significant byte is < 0x80 and the value is negative, add
348 // 0x80 to it, since it will be subtracted and interpreted as a negative when
349 // converting to an integral.
351 if (result.back() & 0x80)
352 result.push_back(neg ? 0x80 : 0);
353 else if (neg)
354 result.back() |= 0x80;
356 return result;
359 private:
360 static int64_t set_vch(const std::vector<unsigned char>& vch)
362 if (vch.empty())
363 return 0;
365 int64_t result = 0;
366 for (size_t i = 0; i != vch.size(); ++i)
367 result |= static_cast<int64_t>(vch[i]) << 8*i;
369 // If the input vector's most significant byte is 0x80, remove it from
370 // the result's msb and return a negative.
371 if (vch.back() & 0x80)
372 return -((int64_t)(result & ~(0x80ULL << (8 * (vch.size() - 1)))));
374 return result;
377 int64_t m_value;
380 typedef prevector<28, unsigned char> CScriptBase;
382 /** Serialized script, used inside transaction inputs and outputs */
383 class CScript : public CScriptBase
385 protected:
386 CScript& push_int64(int64_t n)
388 if (n == -1 || (n >= 1 && n <= 16))
390 push_back(n + (OP_1 - 1));
392 else if (n == 0)
394 push_back(OP_0);
396 else
398 *this << CScriptNum::serialize(n);
400 return *this;
402 public:
403 CScript() { }
404 CScript(const_iterator pbegin, const_iterator pend) : CScriptBase(pbegin, pend) { }
405 CScript(std::vector<unsigned char>::const_iterator pbegin, std::vector<unsigned char>::const_iterator pend) : CScriptBase(pbegin, pend) { }
406 CScript(const unsigned char* pbegin, const unsigned char* pend) : CScriptBase(pbegin, pend) { }
408 ADD_SERIALIZE_METHODS;
410 template <typename Stream, typename Operation>
411 inline void SerializationOp(Stream& s, Operation ser_action) {
412 READWRITE(static_cast<CScriptBase&>(*this));
415 CScript& operator+=(const CScript& b)
417 insert(end(), b.begin(), b.end());
418 return *this;
421 friend CScript operator+(const CScript& a, const CScript& b)
423 CScript ret = a;
424 ret += b;
425 return ret;
428 CScript(int64_t b) { operator<<(b); }
430 explicit CScript(opcodetype b) { operator<<(b); }
431 explicit CScript(const CScriptNum& b) { operator<<(b); }
432 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
435 CScript& operator<<(int64_t b) { return push_int64(b); }
437 CScript& operator<<(opcodetype opcode)
439 if (opcode < 0 || opcode > 0xff)
440 throw std::runtime_error("CScript::operator<<(): invalid opcode");
441 insert(end(), (unsigned char)opcode);
442 return *this;
445 CScript& operator<<(const CScriptNum& b)
447 *this << b.getvch();
448 return *this;
451 CScript& operator<<(const std::vector<unsigned char>& b)
453 if (b.size() < OP_PUSHDATA1)
455 insert(end(), (unsigned char)b.size());
457 else if (b.size() <= 0xff)
459 insert(end(), OP_PUSHDATA1);
460 insert(end(), (unsigned char)b.size());
462 else if (b.size() <= 0xffff)
464 insert(end(), OP_PUSHDATA2);
465 uint8_t _data[2];
466 WriteLE16(_data, b.size());
467 insert(end(), _data, _data + sizeof(_data));
469 else
471 insert(end(), OP_PUSHDATA4);
472 uint8_t _data[4];
473 WriteLE32(_data, b.size());
474 insert(end(), _data, _data + sizeof(_data));
476 insert(end(), b.begin(), b.end());
477 return *this;
480 CScript& operator<<(const CScript& b)
482 // I'm not sure if this should push the script or concatenate scripts.
483 // If there's ever a use for pushing a script onto a script, delete this member fn
484 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
485 return *this;
489 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
491 // Wrapper so it can be called with either iterator or const_iterator
492 const_iterator pc2 = pc;
493 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
494 pc = begin() + (pc2 - begin());
495 return fRet;
498 bool GetOp(iterator& pc, opcodetype& opcodeRet)
500 const_iterator pc2 = pc;
501 bool fRet = GetOp2(pc2, opcodeRet, nullptr);
502 pc = begin() + (pc2 - begin());
503 return fRet;
506 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
508 return GetOp2(pc, opcodeRet, &vchRet);
511 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
513 return GetOp2(pc, opcodeRet, nullptr);
516 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
518 opcodeRet = OP_INVALIDOPCODE;
519 if (pvchRet)
520 pvchRet->clear();
521 if (pc >= end())
522 return false;
524 // Read instruction
525 if (end() - pc < 1)
526 return false;
527 unsigned int opcode = *pc++;
529 // Immediate operand
530 if (opcode <= OP_PUSHDATA4)
532 unsigned int nSize = 0;
533 if (opcode < OP_PUSHDATA1)
535 nSize = opcode;
537 else if (opcode == OP_PUSHDATA1)
539 if (end() - pc < 1)
540 return false;
541 nSize = *pc++;
543 else if (opcode == OP_PUSHDATA2)
545 if (end() - pc < 2)
546 return false;
547 nSize = ReadLE16(&pc[0]);
548 pc += 2;
550 else if (opcode == OP_PUSHDATA4)
552 if (end() - pc < 4)
553 return false;
554 nSize = ReadLE32(&pc[0]);
555 pc += 4;
557 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
558 return false;
559 if (pvchRet)
560 pvchRet->assign(pc, pc + nSize);
561 pc += nSize;
564 opcodeRet = (opcodetype)opcode;
565 return true;
568 /** Encode/decode small integers: */
569 static int DecodeOP_N(opcodetype opcode)
571 if (opcode == OP_0)
572 return 0;
573 assert(opcode >= OP_1 && opcode <= OP_16);
574 return (int)opcode - (int)(OP_1 - 1);
576 static opcodetype EncodeOP_N(int n)
578 assert(n >= 0 && n <= 16);
579 if (n == 0)
580 return OP_0;
581 return (opcodetype)(OP_1+n-1);
584 int FindAndDelete(const CScript& b)
586 int nFound = 0;
587 if (b.empty())
588 return nFound;
589 CScript result;
590 iterator pc = begin(), pc2 = begin();
591 opcodetype opcode;
594 result.insert(result.end(), pc2, pc);
595 while (static_cast<size_t>(end() - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
597 pc = pc + b.size();
598 ++nFound;
600 pc2 = pc;
602 while (GetOp(pc, opcode));
604 if (nFound > 0) {
605 result.insert(result.end(), pc2, end());
606 *this = result;
609 return nFound;
611 int Find(opcodetype op) const
613 int nFound = 0;
614 opcodetype opcode;
615 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
616 if (opcode == op)
617 ++nFound;
618 return nFound;
622 * Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
623 * as 20 sigops. With pay-to-script-hash, that changed:
624 * CHECKMULTISIGs serialized in scriptSigs are
625 * counted more accurately, assuming they are of the form
626 * ... OP_N CHECKMULTISIG ...
628 unsigned int GetSigOpCount(bool fAccurate) const;
631 * Accurately count sigOps, including sigOps in
632 * pay-to-script-hash transactions:
634 unsigned int GetSigOpCount(const CScript& scriptSig) const;
636 bool IsPayToScriptHash() const;
637 bool IsPayToWitnessScriptHash() const;
638 bool IsWitnessProgram(int& version, std::vector<unsigned char>& program) const;
640 /** Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical). */
641 bool IsPushOnly(const_iterator pc) const;
642 bool IsPushOnly() const;
644 /** Check if the script contains valid OP_CODES */
645 bool HasValidOps() const;
648 * Returns whether the script is guaranteed to fail at execution,
649 * regardless of the initial stack. This allows outputs to be pruned
650 * instantly when entering the UTXO set.
652 bool IsUnspendable() const
654 return (size() > 0 && *begin() == OP_RETURN) || (size() > MAX_SCRIPT_SIZE);
657 void clear()
659 // The default prevector::clear() does not release memory
660 CScriptBase::clear();
661 shrink_to_fit();
665 struct CScriptWitness
667 // Note that this encodes the data elements being pushed, rather than
668 // encoding them as a CScript that pushes them.
669 std::vector<std::vector<unsigned char> > stack;
671 // Some compilers complain without a default constructor
672 CScriptWitness() { }
674 bool IsNull() const { return stack.empty(); }
676 void SetNull() { stack.clear(); stack.shrink_to_fit(); }
678 std::string ToString() const;
681 class CReserveScript
683 public:
684 CScript reserveScript;
685 virtual void KeepScript() {}
686 CReserveScript() {}
687 virtual ~CReserveScript() {}
690 #endif // BITCOIN_SCRIPT_SCRIPT_H