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.
6 #ifndef H_BITCOIN_SCRIPT
7 #define H_BITCOIN_SCRIPT
10 #include "utilstrencodings.h"
11 #include "tinyformat.h"
18 #include <boost/variant.hpp>
22 struct CMutableTransaction;
24 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
25 static const unsigned int MAX_OP_RETURN_RELAY = 40; // bytes
27 class scriptnum_error : public std::runtime_error
30 explicit scriptnum_error(const std::string& str) : std::runtime_error(str) {}
35 // Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
36 // The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
37 // but results may overflow (and are valid as long as they are not used in a subsequent
38 // numeric operation). CScriptNum enforces those semantics by storing results as
39 // an int64 and allowing out-of-range values to be returned as a vector of bytes but
40 // throwing an exception if arithmetic is done or the result is interpreted as an integer.
43 explicit CScriptNum(const int64_t& n)
48 explicit CScriptNum(const std::vector<unsigned char>& vch)
50 if (vch.size() > nMaxNumSize)
51 throw scriptnum_error("CScriptNum(const std::vector<unsigned char>&) : overflow");
52 m_value = set_vch(vch);
55 inline bool operator==(const int64_t& rhs) const { return m_value == rhs; }
56 inline bool operator!=(const int64_t& rhs) const { return m_value != rhs; }
57 inline bool operator<=(const int64_t& rhs) const { return m_value <= rhs; }
58 inline bool operator< (const int64_t& rhs) const { return m_value < rhs; }
59 inline bool operator>=(const int64_t& rhs) const { return m_value >= rhs; }
60 inline bool operator> (const int64_t& rhs) const { return m_value > rhs; }
62 inline bool operator==(const CScriptNum& rhs) const { return operator==(rhs.m_value); }
63 inline bool operator!=(const CScriptNum& rhs) const { return operator!=(rhs.m_value); }
64 inline bool operator<=(const CScriptNum& rhs) const { return operator<=(rhs.m_value); }
65 inline bool operator< (const CScriptNum& rhs) const { return operator< (rhs.m_value); }
66 inline bool operator>=(const CScriptNum& rhs) const { return operator>=(rhs.m_value); }
67 inline bool operator> (const CScriptNum& rhs) const { return operator> (rhs.m_value); }
69 inline CScriptNum operator+( const int64_t& rhs) const { return CScriptNum(m_value + rhs);}
70 inline CScriptNum operator-( const int64_t& rhs) const { return CScriptNum(m_value - rhs);}
71 inline CScriptNum operator+( const CScriptNum& rhs) const { return operator+(rhs.m_value); }
72 inline CScriptNum operator-( const CScriptNum& rhs) const { return operator-(rhs.m_value); }
74 inline CScriptNum& operator+=( const CScriptNum& rhs) { return operator+=(rhs.m_value); }
75 inline CScriptNum& operator-=( const CScriptNum& rhs) { return operator-=(rhs.m_value); }
77 inline CScriptNum operator-() const
79 assert(m_value != std::numeric_limits<int64_t>::min());
80 return CScriptNum(-m_value);
83 inline CScriptNum& operator=( const int64_t& rhs)
89 inline CScriptNum& operator+=( const int64_t& rhs)
91 assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits<int64_t>::max() - rhs) ||
92 (rhs < 0 && m_value >= std::numeric_limits<int64_t>::min() - rhs));
97 inline CScriptNum& operator-=( const int64_t& rhs)
99 assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits<int64_t>::min() + rhs) ||
100 (rhs < 0 && m_value <= std::numeric_limits<int64_t>::max() + rhs));
107 if (m_value > std::numeric_limits<int>::max())
108 return std::numeric_limits<int>::max();
109 else if (m_value < std::numeric_limits<int>::min())
110 return std::numeric_limits<int>::min();
114 std::vector<unsigned char> getvch() const
116 return serialize(m_value);
119 static std::vector<unsigned char> serialize(const int64_t& value)
122 return std::vector<unsigned char>();
124 std::vector<unsigned char> result;
125 const bool neg = value < 0;
126 uint64_t absvalue = neg ? -value : value;
130 result.push_back(absvalue & 0xff);
135 // - If the most significant byte is >= 0x80 and the value is positive, push a
136 // new zero-byte to make the significant byte < 0x80 again.
138 // - If the most significant byte is >= 0x80 and the value is negative, push a
139 // new 0x80 byte that will be popped off when converting to an integral.
141 // - If the most significant byte is < 0x80 and the value is negative, add
142 // 0x80 to it, since it will be subtracted and interpreted as a negative when
143 // converting to an integral.
145 if (result.back() & 0x80)
146 result.push_back(neg ? 0x80 : 0);
148 result.back() |= 0x80;
153 static const size_t nMaxNumSize = 4;
156 static int64_t set_vch(const std::vector<unsigned char>& vch)
162 for (size_t i = 0; i != vch.size(); ++i)
163 result |= static_cast<int64_t>(vch[i]) << 8*i;
165 // If the input vector's most significant byte is 0x80, remove it from
166 // the result's msb and return a negative.
167 if (vch.back() & 0x80)
168 return -(result & ~(0x80ULL << (8 * (vch.size() - 1))));
176 /** Signature hash types/flags */
182 SIGHASH_ANYONECANPAY = 0x80,
185 /** Script verification flags */
188 SCRIPT_VERIFY_NONE = 0,
189 SCRIPT_VERIFY_P2SH = (1U << 0), // evaluate P2SH (BIP16) subscripts
190 SCRIPT_VERIFY_STRICTENC = (1U << 1), // enforce strict conformance to DER and SEC2 for signatures and pubkeys
191 SCRIPT_VERIFY_LOW_S = (1U << 2), // enforce low S values (<n/2) in signatures (depends on STRICTENC)
192 SCRIPT_VERIFY_NOCACHE = (1U << 3), // do not store results in signature cache (but do query it)
193 SCRIPT_VERIFY_NULLDUMMY = (1U << 4), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length
196 /** IsMine() return codes */
200 ISMINE_WATCH_ONLY = 1,
201 ISMINE_SPENDABLE = 2,
202 ISMINE_ALL = ISMINE_WATCH_ONLY | ISMINE_SPENDABLE
204 /** used for bitflags of isminetype */
205 typedef uint8_t isminefilter;
207 // Mandatory script verification flags that all new blocks must comply with for
208 // them to be valid. (but old blocks may not comply with) Currently just P2SH,
209 // but in the future other flags may be added, such as a soft-fork to enforce
210 // strict DER encoding.
212 // Failing one of these tests may trigger a DoS ban - see CheckInputs() for
214 static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH;
216 // Standard script verification flags that standard transactions will comply
217 // with. However scripts violating these flags may still be present in valid
218 // blocks and we must accept those blocks.
219 static const unsigned int STANDARD_SCRIPT_VERIFY_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS |
220 SCRIPT_VERIFY_STRICTENC |
221 SCRIPT_VERIFY_NULLDUMMY;
223 // For convenience, standard but not mandatory verify flags.
224 static const unsigned int STANDARD_NOT_MANDATORY_VERIFY_FLAGS = STANDARD_SCRIPT_VERIFY_FLAGS & ~MANDATORY_SCRIPT_VERIFY_FLAGS;
229 // 'standard' transaction types:
237 class CNoDestination {
239 friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
240 friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
243 /** A txout script template with a specific destination. It is either:
244 * * CNoDestination: no destination set
245 * * CKeyID: TX_PUBKEYHASH destination
246 * * CScriptID: TX_SCRIPTHASH destination
247 * A CTxDestination is the internal data type encoded in a CBitcoinAddress
249 typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
251 const char* GetTxnOutputType(txnouttype t);
253 /** Script opcodes */
295 OP_TOALTSTACK = 0x6b,
296 OP_FROMALTSTACK = 0x6c,
328 OP_EQUALVERIFY = 0x88,
353 OP_NUMEQUALVERIFY = 0x9d,
354 OP_NUMNOTEQUAL = 0x9e,
356 OP_GREATERTHAN = 0xa0,
357 OP_LESSTHANOREQUAL = 0xa1,
358 OP_GREATERTHANOREQUAL = 0xa2,
370 OP_CODESEPARATOR = 0xab,
372 OP_CHECKSIGVERIFY = 0xad,
373 OP_CHECKMULTISIG = 0xae,
374 OP_CHECKMULTISIGVERIFY = 0xaf,
390 // template matching params
392 OP_SMALLINTEGER = 0xfa,
394 OP_PUBKEYHASH = 0xfd,
397 OP_INVALIDOPCODE = 0xff,
400 const char* GetOpName(opcodetype opcode);
404 inline std::string ValueString(const std::vector<unsigned char>& vch)
407 return strprintf("%d", CScriptNum(vch).getint());
412 /** Serialized script, used inside transaction inputs and outputs */
413 class CScript : public std::vector<unsigned char>
416 CScript& push_int64(int64_t n)
418 if (n == -1 || (n >= 1 && n <= 16))
420 push_back(n + (OP_1 - 1));
424 *this << CScriptNum::serialize(n);
430 CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
431 CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
433 CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
436 CScript& operator+=(const CScript& b)
438 insert(end(), b.begin(), b.end());
442 friend CScript operator+(const CScript& a, const CScript& b)
450 CScript(int64_t b) { operator<<(b); }
452 explicit CScript(opcodetype b) { operator<<(b); }
453 explicit CScript(const uint256& b) { operator<<(b); }
454 explicit CScript(const CScriptNum& b) { operator<<(b); }
455 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
458 CScript& operator<<(int64_t b) { return push_int64(b); }
460 CScript& operator<<(opcodetype opcode)
462 if (opcode < 0 || opcode > 0xff)
463 throw std::runtime_error("CScript::operator<<() : invalid opcode");
464 insert(end(), (unsigned char)opcode);
468 CScript& operator<<(const uint160& b)
470 insert(end(), sizeof(b));
471 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
475 CScript& operator<<(const uint256& b)
477 insert(end(), sizeof(b));
478 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
482 CScript& operator<<(const CPubKey& key)
484 assert(key.size() < OP_PUSHDATA1);
485 insert(end(), (unsigned char)key.size());
486 insert(end(), key.begin(), key.end());
490 CScript& operator<<(const CScriptNum& b)
496 CScript& operator<<(const std::vector<unsigned char>& b)
498 if (b.size() < OP_PUSHDATA1)
500 insert(end(), (unsigned char)b.size());
502 else if (b.size() <= 0xff)
504 insert(end(), OP_PUSHDATA1);
505 insert(end(), (unsigned char)b.size());
507 else if (b.size() <= 0xffff)
509 insert(end(), OP_PUSHDATA2);
510 unsigned short nSize = b.size();
511 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
515 insert(end(), OP_PUSHDATA4);
516 unsigned int nSize = b.size();
517 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
519 insert(end(), b.begin(), b.end());
523 CScript& operator<<(const CScript& b)
525 // I'm not sure if this should push the script or concatenate scripts.
526 // If there's ever a use for pushing a script onto a script, delete this member fn
527 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
532 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
534 // Wrapper so it can be called with either iterator or const_iterator
535 const_iterator pc2 = pc;
536 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
537 pc = begin() + (pc2 - begin());
541 bool GetOp(iterator& pc, opcodetype& opcodeRet)
543 const_iterator pc2 = pc;
544 bool fRet = GetOp2(pc2, opcodeRet, NULL);
545 pc = begin() + (pc2 - begin());
549 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
551 return GetOp2(pc, opcodeRet, &vchRet);
554 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
556 return GetOp2(pc, opcodeRet, NULL);
559 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
561 opcodeRet = OP_INVALIDOPCODE;
570 unsigned int opcode = *pc++;
573 if (opcode <= OP_PUSHDATA4)
575 unsigned int nSize = 0;
576 if (opcode < OP_PUSHDATA1)
580 else if (opcode == OP_PUSHDATA1)
586 else if (opcode == OP_PUSHDATA2)
591 memcpy(&nSize, &pc[0], 2);
594 else if (opcode == OP_PUSHDATA4)
598 memcpy(&nSize, &pc[0], 4);
601 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
604 pvchRet->assign(pc, pc + nSize);
608 opcodeRet = (opcodetype)opcode;
612 // Encode/decode small integers:
613 static int DecodeOP_N(opcodetype opcode)
617 assert(opcode >= OP_1 && opcode <= OP_16);
618 return (int)opcode - (int)(OP_1 - 1);
620 static opcodetype EncodeOP_N(int n)
622 assert(n >= 0 && n <= 16);
625 return (opcodetype)(OP_1+n-1);
628 int FindAndDelete(const CScript& b)
633 iterator pc = begin();
637 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
639 erase(pc, pc + b.size());
643 while (GetOp(pc, opcode));
646 int Find(opcodetype op) const
650 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
656 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
657 // as 20 sigops. With pay-to-script-hash, that changed:
658 // CHECKMULTISIGs serialized in scriptSigs are
659 // counted more accurately, assuming they are of the form
660 // ... OP_N CHECKMULTISIG ...
661 unsigned int GetSigOpCount(bool fAccurate) const;
663 // Accurately count sigOps, including sigOps in
664 // pay-to-script-hash transactions:
665 unsigned int GetSigOpCount(const CScript& scriptSig) const;
667 bool IsPayToScriptHash() const;
669 // Called by IsStandardTx and P2SH VerifyScript (which makes it consensus-critical).
670 bool IsPushOnly() const;
672 // Called by IsStandardTx.
673 bool HasCanonicalPushes() const;
675 // Returns whether the script is guaranteed to fail at execution,
676 // regardless of the initial stack. This allows outputs to be pruned
677 // instantly when entering the UTXO set.
678 bool IsUnspendable() const
680 return (size() > 0 && *begin() == OP_RETURN);
683 void SetDestination(const CTxDestination& address);
684 void SetMultisig(int nRequired, const std::vector<CPubKey>& keys);
686 std::string ToString() const
690 std::vector<unsigned char> vch;
691 const_iterator pc = begin();
696 if (!GetOp(pc, opcode, vch))
701 if (0 <= opcode && opcode <= OP_PUSHDATA4)
702 str += ValueString(vch);
704 str += GetOpName(opcode);
709 CScriptID GetID() const
711 return CScriptID(Hash160(*this));
716 // The default std::vector::clear() does not release memory.
717 std::vector<unsigned char>().swap(*this);
721 /** Compact serializer for scripts.
723 * It detects common cases and encodes them much more efficiently.
724 * 3 special cases are defined:
725 * * Pay to pubkey hash (encoded as 21 bytes)
726 * * Pay to script hash (encoded as 21 bytes)
727 * * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
729 * Other scripts up to 121 bytes require 1 byte + script length. Above
730 * that, scripts up to 16505 bytes require 2 bytes + script length.
732 class CScriptCompressor
735 // make this static for now (there are only 6 special scripts defined)
736 // this can potentially be extended together with a new nVersion for
737 // transactions, in which case this value becomes dependent on nVersion
738 // and nHeight of the enclosing transaction.
739 static const unsigned int nSpecialScripts = 6;
743 // These check for scripts for which a special case with a shorter encoding is defined.
744 // They are implemented separately from the CScript test, as these test for exact byte
745 // sequence correspondences, and are more strict. For example, IsToPubKey also verifies
746 // whether the public key is valid (as invalid ones cannot be represented in compressed
748 bool IsToKeyID(CKeyID &hash) const;
749 bool IsToScriptID(CScriptID &hash) const;
750 bool IsToPubKey(CPubKey &pubkey) const;
752 bool Compress(std::vector<unsigned char> &out) const;
753 unsigned int GetSpecialSize(unsigned int nSize) const;
754 bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
756 CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
758 unsigned int GetSerializeSize(int nType, int nVersion) const {
759 std::vector<unsigned char> compr;
762 unsigned int nSize = script.size() + nSpecialScripts;
763 return script.size() + VARINT(nSize).GetSerializeSize(nType, nVersion);
766 template<typename Stream>
767 void Serialize(Stream &s, int nType, int nVersion) const {
768 std::vector<unsigned char> compr;
769 if (Compress(compr)) {
770 s << CFlatData(compr);
773 unsigned int nSize = script.size() + nSpecialScripts;
775 s << CFlatData(script);
778 template<typename Stream>
779 void Unserialize(Stream &s, int nType, int nVersion) {
780 unsigned int nSize = 0;
782 if (nSize < nSpecialScripts) {
783 std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
784 s >> REF(CFlatData(vch));
785 Decompress(nSize, vch);
788 nSize -= nSpecialScripts;
789 script.resize(nSize);
790 s >> REF(CFlatData(script));
794 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey, unsigned int flags);
795 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig, unsigned int flags);
797 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
798 uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
799 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
800 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
801 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
802 isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
803 isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest);
804 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
805 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
806 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
807 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
808 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
809 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
811 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
812 // combine them intelligently and return the result.
813 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);
815 #endif // H_BITCOIN_SCRIPT