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 https://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"
22 #include "pbaas/reserves.h"
24 #define OPRETTYPE_TIMELOCK 1
25 #define OPRETTYPE_STAKEPARAMS 2
26 #define OPRETTYPE_STAKECHEAT 3
27 #define OPRETTYPE_OBJECT 4
28 #define OPRETTYPE_OBJECTARR 5
29 #define OPRETTYPE_STAKEPARAMS2 6
34 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE_V2 = 1024;
35 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE_IDENTITY = 3073; // fulfillment maximum size + 1, MAKE SURE TO KEEP MAX_BINARY_CC_SIZE IN SYNC WITH THIS-1, BUF_SIZE in crypto conditions, should be >=
37 // Maximum script length in bytes
38 static const int MAX_SCRIPT_SIZE = 10000;
40 // Threshold for nLockTime: below this value it is interpreted as block number,
41 // otherwise as UNIX timestamp.
42 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
45 std::vector<unsigned char> ToByteVector(const T& in)
47 return std::vector<unsigned char>(in.begin(), in.end());
93 OP_FROMALTSTACK = 0x6c,
125 OP_EQUALVERIFY = 0x88,
150 OP_NUMEQUALVERIFY = 0x9d,
151 OP_NUMNOTEQUAL = 0x9e,
153 OP_GREATERTHAN = 0xa0,
154 OP_LESSTHANOREQUAL = 0xa1,
155 OP_GREATERTHANOREQUAL = 0xa2,
167 OP_CODESEPARATOR = 0xab,
169 OP_CHECKSIGVERIFY = 0xad,
170 OP_CHECKMULTISIG = 0xae,
171 OP_CHECKMULTISIGVERIFY = 0xaf,
172 OP_CHECKCRYPTOCONDITION = 0xcc,
173 OP_CHECKCRYPTOCONDITIONVERIFY = 0xcd,
178 OP_CHECKLOCKTIMEVERIFY = OP_NOP2,
188 // template matching params
190 OP_SMALLINTEGER = 0xfa,
192 OP_PUBKEYHASH = 0xfd,
194 OP_CRYPTOCONDITION = 0xfc,
196 OP_INVALIDOPCODE = 0xff,
199 const char* GetOpName(opcodetype opcode);
201 class scriptnum_error : public std::runtime_error
204 explicit scriptnum_error(const std::string& str) : std::runtime_error(str) {}
210 * Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
211 * The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
212 * but results may overflow (and are valid as long as they are not used in a subsequent
213 * numeric operation). CScriptNum enforces those semantics by storing results as
214 * an int64 and allowing out-of-range values to be returned as a vector of bytes but
215 * throwing an exception if arithmetic is done or the result is interpreted as an integer.
219 explicit CScriptNum(const int64_t& n)
224 static const size_t nDefaultMaxNumSize = 4;
226 explicit CScriptNum(const std::vector<unsigned char>& vch, bool fRequireMinimal,
227 const size_t nMaxNumSize = nDefaultMaxNumSize)
229 if (vch.size() > nMaxNumSize) {
230 throw scriptnum_error("script number overflow");
232 if (fRequireMinimal && vch.size() > 0) {
233 // Check that the number is encoded with the minimum possible
236 // If the most-significant-byte - excluding the sign bit - is zero
237 // then we're not minimal. Note how this test also rejects the
238 // negative-zero encoding, 0x80.
239 if ((vch.back() & 0x7f) == 0) {
240 // One exception: if there's more than one byte and the most
241 // significant bit of the second-most-significant-byte is set
242 // it would conflict with the sign bit. An example of this case
243 // is +-255, which encode to 0xff00 and 0xff80 respectively.
245 if (vch.size() <= 1 || (vch[vch.size() - 2] & 0x80) == 0) {
246 throw scriptnum_error("non-minimally encoded script number");
250 m_value = set_vch(vch);
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; }
257 inline bool operator>=(const int64_t& rhs) const { return m_value >= rhs; }
258 inline bool operator> (const int64_t& rhs) const { return m_value > rhs; }
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); }
264 inline bool operator>=(const CScriptNum& rhs) const { return operator>=(rhs.m_value); }
265 inline bool operator> (const CScriptNum& rhs) const { return operator> (rhs.m_value); }
267 inline CScriptNum operator+( const int64_t& rhs) const { return CScriptNum(m_value + rhs);}
268 inline CScriptNum operator-( const int64_t& rhs) const { return CScriptNum(m_value - rhs);}
269 inline CScriptNum operator+( const CScriptNum& rhs) const { return operator+(rhs.m_value); }
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); }
273 inline CScriptNum& operator-=( const CScriptNum& rhs) { return operator-=(rhs.m_value); }
275 inline CScriptNum operator-() const
277 assert(m_value != std::numeric_limits<int64_t>::min());
278 return CScriptNum(-m_value);
281 inline CScriptNum& operator=( const int64_t& rhs)
287 inline CScriptNum& operator+=( const int64_t& rhs)
289 assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits<int64_t>::max() - rhs) ||
290 (rhs < 0 && m_value >= std::numeric_limits<int64_t>::min() - rhs));
295 inline CScriptNum& operator-=( const int64_t& rhs)
297 assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits<int64_t>::min() + rhs) ||
298 (rhs < 0 && m_value <= std::numeric_limits<int64_t>::max() + rhs));
305 if (m_value > std::numeric_limits<int>::max())
306 return std::numeric_limits<int>::max();
307 else if (m_value < std::numeric_limits<int>::min())
308 return std::numeric_limits<int>::min();
312 std::vector<unsigned char> getvch() const
314 return serialize(m_value);
317 static std::vector<unsigned char> serialize(const int64_t& value)
320 return std::vector<unsigned char>();
322 std::vector<unsigned char> result;
323 const bool neg = value < 0;
324 uint64_t absvalue = neg ? -value : value;
328 result.push_back(absvalue & 0xff);
332 // - If the most significant byte is >= 0x80 and the value is positive, push a
333 // new zero-byte to make the significant byte < 0x80 again.
335 // - If the most significant byte is >= 0x80 and the value is negative, push a
336 // new 0x80 byte that will be popped off when converting to an integral.
338 // - If the most significant byte is < 0x80 and the value is negative, add
339 // 0x80 to it, since it will be subtracted and interpreted as a negative when
340 // converting to an integral.
342 if (result.back() & 0x80)
343 result.push_back(neg ? 0x80 : 0);
345 result.back() |= 0x80;
351 static int64_t set_vch(const std::vector<unsigned char>& vch)
357 for (size_t i = 0; i != vch.size(); ++i)
358 result |= static_cast<int64_t>(vch[i]) << 8*i;
360 // If the input vector's most significant byte is 0x80, remove it from
361 // the result's msb and return a negative.
362 if (vch.back() & 0x80)
363 return -((int64_t)(result & ~(0x80ULL << (8 * (vch.size() - 1)))));
371 typedef prevector<28, unsigned char> CScriptBase;
377 class CNoDestination {
379 friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
380 friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
383 /** A reference to a CScript: the Hash160 of its serialization (see script.h) */
384 class CScriptID : public uint160
387 CScriptID() : uint160() {}
388 CScriptID(const CScript& in);
389 CScriptID(const uint160& in) : uint160(in) {}
392 uint160 GetNameID(const std::string &Name, const uint160 &parent);
394 /** A reference to an identity: the Hash160 of a specific serialization if its name and parent chain (see script.h) */
395 class CIdentityID : public uint160
398 CIdentityID() : uint160() {}
399 CIdentityID(const std::string& in, const uint160 &parent=uint160()) : uint160(GetNameID(in, parent)) {}
400 CIdentityID(const uint160& in) : uint160(in) {}
403 /** A reference to a quantum public key: the Hash160 of its serialization (see script.h), which it is indexed by in an output */
404 class CQuantumID : public uint160
407 CQuantumID() : uint160() {}
408 CQuantumID(const std::string& in, const uint160 &parent=uint160()) : uint160(GetNameID(in, parent)) {}
409 CQuantumID(const uint160& in) : uint160(in) {}
412 /** A reference to an index only address type, not used in the API or externally, but
413 * reserved as an index for specific types of transaction outputs that can then be queried
414 * and assumed to be valid and checked if found.
415 * CQuantum public keys are indexed by a CIndexID that represents a hash of the quantum public key. */
416 class CIndexID : public uint160
419 CIndexID() : uint160() {}
420 CIndexID(const uint160& in) : uint160(in) {}
424 * A txout script template with a specific destination. It is either:
425 * * CNoDestination: no destination set
426 * * CKeyID: TX_PUBKEYHASH destination
427 * * CScriptID: TX_SCRIPTHASH destination
428 * A CTxDestination is the internal data type encoded in a bitcoin address
430 typedef boost::variant<CNoDestination, CPubKey, CKeyID, CScriptID, CIdentityID, CIndexID, CQuantumID> CTxDestination;
432 CTxDestination TransferDestinationToDestination(const CTransferDestination &transferDest);
433 CTransferDestination DestinationToTransferDestination(const CTxDestination &dest);
434 CTransferDestination IdentityToTransferDestination(const CIdentity &identity);
435 CIdentity TransferDestinationToIdentity(const CTransferDestination &dest);
436 std::vector<CTxDestination> TransferDestinationsToDestinations(const std::vector<CTransferDestination> &transferDests);
437 std::vector<CTransferDestination> DestinationsToTransferDestinations(const std::vector<CTxDestination> &dests);
442 static const uint8_t VERSION_V1 = 1;
443 static const uint8_t VERSION_V2 = 2;
444 static const uint8_t VERSION_V3 = 3;
446 static const uint8_t ADDRTYPE_INVALID = 0;
447 static const uint8_t ADDRTYPE_PK = 1;
448 static const uint8_t ADDRTYPE_PKH = 2;
449 static const uint8_t ADDRTYPE_SH = 3;
450 static const uint8_t ADDRTYPE_ID = 4;
451 static const uint8_t ADDRTYPE_INDEX = 5;
452 static const uint8_t ADDRTYPE_QUANTUM = 6;
453 static const uint8_t ADDRTYPE_LAST = 6;
457 uint8_t m, n; // for m of n sigs required, n pub keys for sigs will follow
458 std::vector<CTxDestination> vKeys;
459 std::vector<std::vector<unsigned char>> vData; // extra parameters
461 COptCCParams() : version(0), evalCode(0), m(0), n(0) {}
463 COptCCParams(uint8_t ver, uint8_t code, uint8_t _m, uint8_t _n, const std::vector<CTxDestination> &vkeys, const std::vector<std::vector<unsigned char>> &vdata) :
464 version(ver), evalCode(code), m(_m), n(_n), vKeys(vkeys), vData(vdata) {}
466 COptCCParams(const std::vector<unsigned char> &vch);
468 bool IsValid() const { return version == VERSION_V1 || version == VERSION_V2 || version == VERSION_V3; }
470 std::vector<unsigned char> AsVector() const;
472 std::set<CIndexID> GetIndexKeys() const;
473 std::map<uint160, uint32_t> GetIndexHeightOffsets(uint32_t height) const;
474 std::vector<CTxDestination> GetDestinations() const;
477 // This is for STAKEGUARD2, which is versioned and enables staking the reserve of a reserve currency
478 // chain, where this native currency is a reserve of a native currency that is being notarized into
492 uint32_t sourceHeight;
496 CStakeInfo() : version(VERSION_INVALID), height(0), sourceHeight(0) {}
497 CStakeInfo(uint32_t Height, uint32_t SourceHeight, const uint256 &UTXO, const uint256 &PrevHash, uint32_t Version=VERSION_CURRENT) :
498 version(Version), height(0), sourceHeight(0), utxo(UTXO), prevHash(PrevHash) {}
499 CStakeInfo(std::vector<unsigned char> vch);
501 std::vector<unsigned char> AsVector() const;
503 ADD_SERIALIZE_METHODS;
505 template <typename Stream, typename Operation>
506 inline void SerializationOp(Stream& s, Operation ser_action) {
507 READWRITE(VARINT(version));
508 READWRITE(VARINT(height));
509 READWRITE(VARINT(sourceHeight));
515 // used when creating crypto condition outputs
516 template <typename T>
522 const std::vector<CTxDestination> dests;
525 CConditionObj(uint8_t eCode, const std::vector<CTxDestination> &Dests, int M, const T *pO=nullptr) : evalCode(eCode), m(M), dests(Dests), objectValid(false)
533 bool HaveObject() const
550 /** Serialized script, used inside transaction inputs and outputs */
551 class CScript : public CScriptBase
554 CScript& push_int64(int64_t n)
556 if (n == -1 || (n >= 1 && n <= 16))
558 push_back(n + (OP_1 - 1));
566 *this << CScriptNum::serialize(n);
570 bool GetBalancedData(const_iterator& pc, std::vector<std::vector<unsigned char>>& vSolutions) const;
572 static unsigned int MAX_SCRIPT_ELEMENT_SIZE; // bytes
575 CScript(const CScript& b) : CScriptBase(b.begin(), b.end()) { }
576 CScript(const_iterator pbegin, const_iterator pend) : CScriptBase(pbegin, pend) { }
577 CScript(std::vector<unsigned char>::const_iterator pbegin, std::vector<unsigned char>::const_iterator pend) : CScriptBase(pbegin, pend) { }
578 CScript(const unsigned char* pbegin, const unsigned char* pend) : CScriptBase(pbegin, pend) { }
580 CScript& operator+=(const CScript& b)
582 insert(end(), b.begin(), b.end());
586 friend CScript operator+(const CScript& a, const CScript& b)
593 CScript(int64_t b) { operator<<(b); }
594 explicit CScript(opcodetype b) { operator<<(b); }
595 explicit CScript(const CScriptNum& b) { operator<<(b); }
596 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
598 CScript& operator<<(int64_t b) { return push_int64(b); }
600 CScript& operator<<(opcodetype opcode)
602 if (opcode < 0 || opcode > 0xff)
603 throw std::runtime_error("CScript::operator<<(): invalid opcode");
604 insert(end(), (unsigned char)opcode);
608 CScript& operator<<(const CScriptNum& b)
614 CScript& operator<<(const std::vector<unsigned char>& b)
616 if (b.size() < OP_PUSHDATA1)
618 insert(end(), (unsigned char)b.size());
620 else if (b.size() <= 0xff)
622 insert(end(), OP_PUSHDATA1);
623 insert(end(), (unsigned char)b.size());
625 else if (b.size() <= 0xffff)
627 insert(end(), OP_PUSHDATA2);
629 WriteLE16(data, b.size());
630 insert(end(), data, data + sizeof(data));
634 insert(end(), OP_PUSHDATA4);
636 WriteLE32(data, b.size());
637 insert(end(), data, data + sizeof(data));
639 insert(end(), b.begin(), b.end());
643 CScript& operator<<(const CScript& b)
645 // I'm not sure if this should push the script or concatenate scripts.
646 // If there's ever a use for pushing a script onto a script, delete this member fn
647 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
652 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
654 // Wrapper so it can be called with either iterator or const_iterator
655 const_iterator pc2 = pc;
656 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
657 pc = begin() + (pc2 - begin());
661 bool GetOp(iterator& pc, opcodetype& opcodeRet)
663 const_iterator pc2 = pc;
664 bool fRet = GetOp2(pc2, opcodeRet, NULL);
665 pc = begin() + (pc2 - begin());
669 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
671 return GetOp2(pc, opcodeRet, &vchRet);
674 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
676 return GetOp2(pc, opcodeRet, NULL);
679 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
681 opcodeRet = OP_INVALIDOPCODE;
690 unsigned int opcode = *pc++;
693 if (opcode <= OP_PUSHDATA4)
695 unsigned int nSize = 0;
696 if (opcode < OP_PUSHDATA1)
700 else if (opcode == OP_PUSHDATA1)
706 else if (opcode == OP_PUSHDATA2)
710 nSize = ReadLE16(&pc[0]);
713 else if (opcode == OP_PUSHDATA4)
717 nSize = ReadLE32(&pc[0]);
720 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
723 pvchRet->assign(pc, pc + nSize);
727 opcodeRet = (opcodetype)opcode;
731 /** Encode/decode small integers: */
732 static int DecodeOP_N(opcodetype opcode)
736 assert(opcode >= OP_1 && opcode <= OP_16);
737 return (int)opcode - (int)(OP_1 - 1);
739 static opcodetype EncodeOP_N(int n)
741 assert(n >= 0 && n <= 16);
744 return (opcodetype)(OP_1+n-1);
748 * Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
749 * as 20 sigops. With pay-to-script-hash, that changed:
750 * CHECKMULTISIGs serialized in scriptSigs are
751 * counted more accurately, assuming they are of the form
752 * ... OP_N CHECKMULTISIG ...
754 unsigned int GetSigOpCount(bool fAccurate) const;
757 * Accurately count sigOps, including sigOps in
758 * pay-to-script-hash transactions:
760 unsigned int GetSigOpCount(const CScript& scriptSig) const;
762 bool IsPayToPublicKeyHash() const;
763 bool IsPayToPublicKey() const;
765 bool IsPayToScriptHash() const;
766 bool GetPushedData(CScript::const_iterator pc, std::vector<std::vector<unsigned char>>& vData) const;
767 bool IsOpReturn() const { return size() > 0 && (*this)[0] == OP_RETURN; }
768 bool GetOpretData(std::vector<std::vector<unsigned char>>& vData) const;
770 bool IsPayToCryptoCondition(COptCCParams &ccParams) const;
771 bool IsPayToCryptoCondition(CScript *ccSubScript, std::vector<std::vector<unsigned char>> &vParams, COptCCParams &optParams) const;
772 bool IsPayToCryptoCondition(CScript *ccSubScript, std::vector<std::vector<unsigned char>> &vParams) const;
773 bool IsPayToCryptoCondition(CScript *ccSubScript) const;
774 bool IsPayToCryptoCondition(uint32_t *ecode) const;
775 bool IsPayToCryptoCondition() const;
776 CScript &ReplaceCCParams(const COptCCParams ¶ms);
778 bool IsSpendableOutputType(const COptCCParams &p) const;
779 bool IsSpendableOutputType() const;
780 CCurrencyValueMap ReserveOutValue() const;
781 CCurrencyValueMap ReserveOutValue(COptCCParams &p, bool spendingOnly=false) const;
782 bool SetReserveOutValue(const CCurrencyValueMap &newValue);
784 bool IsCoinImport() const;
785 bool MayAcceptCryptoCondition() const;
786 bool MayAcceptCryptoCondition(int evalCode) const;
787 bool IsInstantSpend() const;
789 // insightexplorer, there may be more script types in the future
790 enum ScriptType : int {
792 P2PKH = 1, // the same index value is used for all types that can have destinations represented by public key hash
794 P2CC = 1, // CCs are actually not an address type, but as a type of transaction, they are identified historicall as P2PKH. they now can also pay to IDs.
801 ScriptType GetType() const;
802 uint160 AddressHash() const;
803 std::vector<CTxDestination> GetDestinations() const;
805 /** Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical). */
806 bool IsPushOnly() const;
808 /** if the front of the script has check lock time verify. this is a fairly simple check.
809 * accepts NULL as parameter if unlockTime is not needed.
811 bool IsCheckLockTimeVerify(int64_t *unlockTime) const;
813 bool IsCheckLockTimeVerify() const;
816 * Returns whether the script is guaranteed to fail at execution,
817 * regardless of the initial stack. This allows outputs to be pruned
818 * instantly when entering the UTXO set.
820 bool IsUnspendable() const
822 return (size() > 0 && *begin() == OP_RETURN) || (size() > MAX_SCRIPT_SIZE);
825 std::string ToString() const;
829 // The default std::vector::clear() does not release memory.
830 CScriptBase().swap(*this);
837 CScript reserveScript;
838 virtual void KeepScript() {}
840 virtual ~CReserveScript() {}
843 #endif // BITCOIN_SCRIPT_SCRIPT_H