1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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.
5 #ifndef H_BITCOIN_SCRIPT
6 #define H_BITCOIN_SCRIPT
16 typedef std::vector<uint8_t> valtype;
19 class CBitcoinAddress;
21 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
23 // Setting nSequence to this value for every input in a transaction
24 // disables nLockTime.
25 static const uint32_t SEQUENCE_FINAL = 0xffffffff;
27 // Threshold for inverted nSequence: below this value it is interpreted
28 // as a relative lock-time, otherwise ignored.
29 //static const uint32_t SEQUENCE_THRESHOLD = 0x80000000;
31 // If this flag set, CTxIn::nSequence is NOT interpreted as a
32 // relative lock-time.
33 static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = 0x80000000;
35 // If CTxIn::nSequence encodes a relative lock-time and this flag
36 // is set, the relative lock-time has units of 512 seconds,
37 // otherwise it specifies blocks with a granularity of 1.
38 static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = 0x00400000;
40 // If CTxIn::nSequence encodes a relative lock-time, this mask is
41 // applied to extract that lock-time from the sequence field.
42 static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
44 // IsMine() return codes
50 MINE_ALL = MINE_WATCH_ONLY | MINE_SPENDABLE
53 typedef uint8_t isminefilter;
55 // Signature hash types/flags
61 SIGHASH_ANYONECANPAY = 0x80
64 // Script verification flags
67 SCRIPT_VERIFY_NONE = 0,
68 SCRIPT_VERIFY_P2SH = (1U << 0), // evaluate P2SH (BIP16) subscripts
69 SCRIPT_VERIFY_STRICTENC = (1U << 1), // enforce strict conformance to DER and SEC2 for signatures and pubkeys
70 SCRIPT_VERIFY_LOW_S = (1U << 2), // enforce low S values in signatures (depends on STRICTENC)
71 SCRIPT_VERIFY_NOCACHE = (1U << 3), // do not store results in signature cache (but do query it)
72 SCRIPT_VERIFY_NULLDUMMY = (1U << 4), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length
73 SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = (1U << 9),
74 SCRIPT_VERIFY_CHECKSEQUENCEVERIFY = (1U << 10)
77 // Strict verification:
79 // * force DER encoding;
81 // * ensure that CHECKMULTISIG dummy argument is null.
82 static const unsigned int STRICT_FORMAT_FLAGS = SCRIPT_VERIFY_STRICTENC | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_NULLDUMMY;
84 // Mandatory script verification flags that all new blocks must comply with for
85 // them to be valid. (but old blocks may not comply with) Currently just P2SH,
86 // but in the future other flags may be added, such as a soft-fork to enforce
87 // strict DER encoding.
89 // Failing one of these tests may trigger a DoS ban - see ConnectInputs() for
91 static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH;
93 // Standard script verification flags that standard transactions will comply
94 // with. However scripts violating these flags may still be present in valid
95 // blocks and we must accept those blocks.
96 static const unsigned int STRICT_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS | STRICT_FORMAT_FLAGS;
101 // 'standard' transaction types:
110 const char* GetTxnOutputType(txnouttype t);
152 OP_CHECKLOCKTIMEVERIFY = 0xb1,
153 OP_CHECKSEQUENCEVERIFY = 0xb2,
156 OP_TOALTSTACK = 0x6b,
157 OP_FROMALTSTACK = 0x6c,
189 OP_EQUALVERIFY = 0x88,
214 OP_NUMEQUALVERIFY = 0x9d,
215 OP_NUMNOTEQUAL = 0x9e,
217 OP_GREATERTHAN = 0xa0,
218 OP_LESSTHANOREQUAL = 0xa1,
219 OP_GREATERTHANOREQUAL = 0xa2,
231 OP_CODESEPARATOR = 0xab,
233 OP_CHECKSIGVERIFY = 0xad,
234 OP_CHECKMULTISIG = 0xae,
235 OP_CHECKMULTISIGVERIFY = 0xaf,
247 // template matching params
249 OP_SMALLINTEGER = 0xfa,
252 OP_PUBKEYHASH = 0xfd,
255 OP_INVALIDOPCODE = 0xff
258 const char* GetOpName(opcodetype opcode);
260 inline std::string ValueString(const std::vector<unsigned char>& vch)
263 return strprintf("%d", CBigNum(vch).getint32());
268 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
271 for (const std::vector<unsigned char>& vch : vStack)
275 str += ValueString(vch);
280 // Serialized script, used inside transaction inputs and outputs
281 class CScript : public std::vector<uint8_t>
284 CScript& push_int64(int64_t n)
286 if (n == -1 || (n >= 1 && n <= 16))
288 push_back((uint8_t)n + (OP_1 - 1));
293 *this << bn.getvch();
298 CScript& push_uint64(uint64_t n)
300 if (n >= 1 && n <= 16)
302 push_back((uint8_t)n + (OP_1 - 1));
307 *this << bn.getvch();
314 CScript(const CScript& b) : std::vector<uint8_t>(b.begin(), b.end()) { }
315 CScript(const_iterator pbegin, const_iterator pend) : std::vector<uint8_t>(pbegin, pend) { }
317 CScript(const uint8_t* pbegin, const uint8_t* pend) : std::vector<uint8_t>(pbegin, pend) { }
320 CScript& operator=(const CScript&) = default;
322 CScript& operator+=(const CScript& b)
324 insert(end(), b.begin(), b.end());
328 friend CScript operator+(const CScript& a, const CScript& b)
335 explicit CScript(int8_t b) { operator<<(b); }
336 explicit CScript(int16_t b) { operator<<(b); }
337 explicit CScript(int32_t b) { operator<<(b); }
338 explicit CScript(int64_t b) { operator<<(b); }
340 explicit CScript(uint8_t b) { operator<<(b); }
341 explicit CScript(uint16_t b) { operator<<(b); }
342 explicit CScript(uint32_t b) { operator<<(b); }
343 explicit CScript(uint64_t b) { operator<<(b); }
345 explicit CScript(opcodetype b) { operator<<(b); }
346 explicit CScript(const uint256& b) { operator<<(b); }
347 explicit CScript(const CBigNum& b) { operator<<(b); }
348 explicit CScript(const std::vector<uint8_t>& b) { operator<<(b); }
350 CScript& operator<<(int8_t b) { return push_int64(b); }
351 CScript& operator<<(int16_t b) { return push_int64(b); }
352 CScript& operator<<(int32_t b) { return push_int64(b); }
353 CScript& operator<<(int64_t b) { return push_int64(b); }
355 CScript& operator<<(uint8_t b) { return push_uint64(b); }
356 CScript& operator<<(uint16_t b) { return push_uint64(b); }
357 CScript& operator<<(uint32_t b) { return push_uint64(b); }
358 CScript& operator<<(uint64_t b) { return push_uint64(b); }
360 CScript& operator<<(opcodetype opcode)
362 if (opcode < 0 || opcode > 0xff)
363 throw std::runtime_error("CScript::operator<<() : invalid opcode");
364 insert(end(), (uint8_t)opcode);
368 CScript& operator<<(const uint160& b)
370 insert(end(), sizeof(b));
371 insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
375 CScript& operator<<(const uint256& b)
377 insert(end(), sizeof(b));
378 insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
382 CScript& operator<<(const CPubKey& key)
384 std::vector<uint8_t> vchKey(key.begin(), key.end());
385 return (*this) << vchKey;
388 CScript& operator<<(const CBigNum& b)
394 CScript& operator<<(const std::vector<uint8_t>& b)
396 if (b.size() < OP_PUSHDATA1)
398 insert(end(), (uint8_t)b.size());
400 else if (b.size() <= 0xff)
402 insert(end(), OP_PUSHDATA1);
403 insert(end(), (uint8_t)b.size());
405 else if (b.size() <= 0xffff)
407 insert(end(), OP_PUSHDATA2);
408 uint16_t nSize = (uint16_t) b.size();
409 insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
413 insert(end(), OP_PUSHDATA4);
414 uint32_t nSize = (uint32_t) b.size();
415 insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
417 insert(end(), b.begin(), b.end());
421 CScript& operator<<(const CScript& b)
423 // I'm not sure if this should push the script or concatenate scripts.
424 // If there's ever a use for pushing a script onto a script, delete this member fn
425 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
430 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet)
432 // Wrapper so it can be called with either iterator or const_iterator
433 const_iterator pc2 = pc;
434 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
435 pc = begin() + (pc2 - begin());
439 bool GetOp(iterator& pc, opcodetype& opcodeRet)
441 const_iterator pc2 = pc;
442 bool fRet = GetOp2(pc2, opcodeRet, NULL);
443 pc = begin() + (pc2 - begin());
447 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet) const
449 return GetOp2(pc, opcodeRet, &vchRet);
452 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
454 return GetOp2(pc, opcodeRet, NULL);
457 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>* pvchRet) const
459 opcodeRet = OP_INVALIDOPCODE;
468 uint32_t opcode = *pc++;
471 if (opcode <= OP_PUSHDATA4)
473 uint32_t nSize = OP_0;
474 if (opcode < OP_PUSHDATA1)
478 else if (opcode == OP_PUSHDATA1)
484 else if (opcode == OP_PUSHDATA2)
488 memcpy(&nSize, &pc[0], 2);
491 else if (opcode == OP_PUSHDATA4)
495 memcpy(&nSize, &pc[0], 4);
498 if (end() - pc < 0 || (uint32_t)(end() - pc) < nSize)
501 pvchRet->assign(pc, pc + nSize);
505 opcodeRet = (opcodetype)opcode;
509 // Encode/decode small integers:
510 static int DecodeOP_N(opcodetype opcode)
514 assert(opcode >= OP_1 && opcode <= OP_16);
515 return (opcode - (OP_1 - 1));
517 static opcodetype EncodeOP_N(int n)
519 assert(n >= 0 && n <= 16);
522 return (opcodetype)(OP_1+n-1);
525 int FindAndDelete(const CScript& b)
530 iterator pc = begin();
534 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
536 erase(pc, pc + b.size());
540 while (GetOp(pc, opcode));
543 int Find(opcodetype op) const
547 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
553 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
554 // as 20 sigops. With pay-to-script-hash, that changed:
555 // CHECKMULTISIGs serialized in scriptSigs are
556 // counted more accurately, assuming they are of the form
557 // ... OP_N CHECKMULTISIG ...
558 unsigned int GetSigOpCount(bool fAccurate) const;
560 // Accurately count sigOps, including sigOps in
561 // pay-to-script-hash transactions:
562 unsigned int GetSigOpCount(const CScript& scriptSig) const;
564 bool IsPayToScriptHash() const;
566 bool IsPushOnly(const_iterator pc) const
571 if (!GetOp(pc, opcode))
579 // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
580 bool IsPushOnly() const
582 return this->IsPushOnly(begin());
585 // Called by CTransaction::IsStandard.
586 bool HasCanonicalPushes() const;
588 void SetDestination(const CTxDestination& address);
589 void SetAddress(const CBitcoinAddress& dest);
590 void SetMultisig(int nRequired, const std::vector<CPubKey>& keys);
593 void PrintHex() const
595 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
598 std::string ToString(bool fShort=false) const
602 std::vector<uint8_t> vch;
603 const_iterator pc = begin();
608 if (!GetOp(pc, opcode, vch))
613 if (0 <= opcode && opcode <= OP_PUSHDATA4)
614 str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
616 str += GetOpName(opcode);
623 printf("%s\n", ToString().c_str());
626 CScriptID GetID() const
628 return CScriptID(Hash160(*this));
632 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey, unsigned int flags);
633 bool IsDERSignature(const valtype &vchSig, bool fWithHashType=false, bool fCheckLow=false);
634 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig, unsigned int flags);
636 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
637 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
638 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
639 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
640 isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
641 //isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest);
642 isminetype IsMine(const CKeyStore& keystore, const CBitcoinAddress& dest);
643 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
644 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
645 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet);
646 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
647 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
648 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
649 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
651 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
652 // combine them intelligently and return the result.
653 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);