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
11 #include <boost/foreach.hpp>
17 typedef std::vector<uint8_t> valtype;
20 class CBitcoinAddress;
22 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
24 // Setting nSequence to this value for every input in a transaction
25 // disables nLockTime.
26 static const uint32_t SEQUENCE_FINAL = 0xffffffff;
28 // Threshold for inverted nSequence: below this value it is interpreted
29 // as a relative lock-time, otherwise ignored.
30 //static const uint32_t SEQUENCE_THRESHOLD = 0x80000000;
32 // If this flag set, CTxIn::nSequence is NOT interpreted as a
33 // relative lock-time.
34 static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = 0x80000000;
36 // If CTxIn::nSequence encodes a relative lock-time and this flag
37 // is set, the relative lock-time has units of 512 seconds,
38 // otherwise it specifies blocks with a granularity of 1.
39 static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = 0x00400000;
41 // If CTxIn::nSequence encodes a relative lock-time, this mask is
42 // applied to extract that lock-time from the sequence field.
43 static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
45 // IsMine() return codes
51 MINE_ALL = MINE_WATCH_ONLY | MINE_SPENDABLE
54 typedef uint8_t isminefilter;
56 // Signature hash types/flags
62 SIGHASH_ANYONECANPAY = 0x80
65 // Script verification flags
68 SCRIPT_VERIFY_NONE = 0,
69 SCRIPT_VERIFY_P2SH = (1U << 0), // evaluate P2SH (BIP16) subscripts
70 SCRIPT_VERIFY_STRICTENC = (1U << 1), // enforce strict conformance to DER and SEC2 for signatures and pubkeys
71 SCRIPT_VERIFY_LOW_S = (1U << 2), // enforce low S values in signatures (depends on STRICTENC)
72 SCRIPT_VERIFY_NOCACHE = (1U << 3), // do not store results in signature cache (but do query it)
73 SCRIPT_VERIFY_NULLDUMMY = (1U << 4), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length
74 SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = (1U << 9),
75 SCRIPT_VERIFY_CHECKSEQUENCEVERIFY = (1U << 10)
78 // Strict verification:
80 // * force DER encoding;
82 // * ensure that CHECKMULTISIG dummy argument is null.
83 static const unsigned int STRICT_FORMAT_FLAGS = SCRIPT_VERIFY_STRICTENC | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_NULLDUMMY;
85 // Mandatory script verification flags that all new blocks must comply with for
86 // them to be valid. (but old blocks may not comply with) Currently just P2SH,
87 // but in the future other flags may be added, such as a soft-fork to enforce
88 // strict DER encoding.
90 // Failing one of these tests may trigger a DoS ban - see ConnectInputs() for
92 static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH;
94 // Standard script verification flags that standard transactions will comply
95 // with. However scripts violating these flags may still be present in valid
96 // blocks and we must accept those blocks.
97 static const unsigned int STRICT_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS | STRICT_FORMAT_FLAGS;
102 // 'standard' transaction types:
111 const char* GetTxnOutputType(txnouttype t);
153 OP_CHECKLOCKTIMEVERIFY = 0xb1,
154 OP_CHECKSEQUENCEVERIFY = 0xb2,
157 OP_TOALTSTACK = 0x6b,
158 OP_FROMALTSTACK = 0x6c,
190 OP_EQUALVERIFY = 0x88,
215 OP_NUMEQUALVERIFY = 0x9d,
216 OP_NUMNOTEQUAL = 0x9e,
218 OP_GREATERTHAN = 0xa0,
219 OP_LESSTHANOREQUAL = 0xa1,
220 OP_GREATERTHANOREQUAL = 0xa2,
232 OP_CODESEPARATOR = 0xab,
234 OP_CHECKSIGVERIFY = 0xad,
235 OP_CHECKMULTISIG = 0xae,
236 OP_CHECKMULTISIGVERIFY = 0xaf,
248 // template matching params
250 OP_SMALLINTEGER = 0xfa,
253 OP_PUBKEYHASH = 0xfd,
256 OP_INVALIDOPCODE = 0xff
259 const char* GetOpName(opcodetype opcode);
261 inline std::string ValueString(const std::vector<unsigned char>& vch)
264 return strprintf("%d", CBigNum(vch).getint32());
269 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
272 BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
276 str += ValueString(vch);
281 // Serialized script, used inside transaction inputs and outputs
282 class CScript : public std::vector<uint8_t>
285 CScript& push_int64(int64_t n)
287 if (n == -1 || (n >= 1 && n <= 16))
289 push_back((uint8_t)n + (OP_1 - 1));
294 *this << bn.getvch();
299 CScript& push_uint64(uint64_t n)
301 if (n >= 1 && n <= 16)
303 push_back((uint8_t)n + (OP_1 - 1));
308 *this << bn.getvch();
315 CScript(const CScript& b) : std::vector<uint8_t>(b.begin(), b.end()) { }
316 CScript(const_iterator pbegin, const_iterator pend) : std::vector<uint8_t>(pbegin, pend) { }
318 CScript(const uint8_t* pbegin, const uint8_t* pend) : std::vector<uint8_t>(pbegin, pend) { }
321 CScript& operator+=(const CScript& b)
323 insert(end(), b.begin(), b.end());
327 friend CScript operator+(const CScript& a, const CScript& b)
334 explicit CScript(int8_t b) { operator<<(b); }
335 explicit CScript(int16_t b) { operator<<(b); }
336 explicit CScript(int32_t b) { operator<<(b); }
337 explicit CScript(int64_t b) { operator<<(b); }
339 explicit CScript(uint8_t b) { operator<<(b); }
340 explicit CScript(uint16_t b) { operator<<(b); }
341 explicit CScript(uint32_t b) { operator<<(b); }
342 explicit CScript(uint64_t b) { operator<<(b); }
344 explicit CScript(opcodetype b) { operator<<(b); }
345 explicit CScript(const uint256& b) { operator<<(b); }
346 explicit CScript(const CBigNum& b) { operator<<(b); }
347 explicit CScript(const std::vector<uint8_t>& b) { operator<<(b); }
349 CScript& operator<<(int8_t b) { return push_int64(b); }
350 CScript& operator<<(int16_t b) { return push_int64(b); }
351 CScript& operator<<(int32_t b) { return push_int64(b); }
352 CScript& operator<<(int64_t b) { return push_int64(b); }
354 CScript& operator<<(uint8_t b) { return push_uint64(b); }
355 CScript& operator<<(uint16_t b) { return push_uint64(b); }
356 CScript& operator<<(uint32_t b) { return push_uint64(b); }
357 CScript& operator<<(uint64_t b) { return push_uint64(b); }
359 CScript& operator<<(opcodetype opcode)
361 if (opcode < 0 || opcode > 0xff)
362 throw std::runtime_error("CScript::operator<<() : invalid opcode");
363 insert(end(), (uint8_t)opcode);
367 CScript& operator<<(const uint160& b)
369 insert(end(), sizeof(b));
370 insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
374 CScript& operator<<(const uint256& b)
376 insert(end(), sizeof(b));
377 insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
381 CScript& operator<<(const CPubKey& key)
383 std::vector<uint8_t> vchKey(key.begin(), key.end());
384 return (*this) << vchKey;
387 CScript& operator<<(const CBigNum& b)
393 CScript& operator<<(const std::vector<uint8_t>& b)
395 if (b.size() < OP_PUSHDATA1)
397 insert(end(), (uint8_t)b.size());
399 else if (b.size() <= 0xff)
401 insert(end(), OP_PUSHDATA1);
402 insert(end(), (uint8_t)b.size());
404 else if (b.size() <= 0xffff)
406 insert(end(), OP_PUSHDATA2);
407 uint16_t nSize = (uint16_t) b.size();
408 insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
412 insert(end(), OP_PUSHDATA4);
413 uint32_t nSize = (uint32_t) b.size();
414 insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
416 insert(end(), b.begin(), b.end());
420 CScript& operator<<(const CScript& b)
422 // I'm not sure if this should push the script or concatenate scripts.
423 // If there's ever a use for pushing a script onto a script, delete this member fn
424 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
429 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet)
431 // Wrapper so it can be called with either iterator or const_iterator
432 const_iterator pc2 = pc;
433 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
434 pc = begin() + (pc2 - begin());
438 bool GetOp(iterator& pc, opcodetype& opcodeRet)
440 const_iterator pc2 = pc;
441 bool fRet = GetOp2(pc2, opcodeRet, NULL);
442 pc = begin() + (pc2 - begin());
446 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet) const
448 return GetOp2(pc, opcodeRet, &vchRet);
451 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
453 return GetOp2(pc, opcodeRet, NULL);
456 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>* pvchRet) const
458 opcodeRet = OP_INVALIDOPCODE;
467 uint32_t opcode = *pc++;
470 if (opcode <= OP_PUSHDATA4)
472 uint32_t nSize = OP_0;
473 if (opcode < OP_PUSHDATA1)
477 else if (opcode == OP_PUSHDATA1)
483 else if (opcode == OP_PUSHDATA2)
487 memcpy(&nSize, &pc[0], 2);
490 else if (opcode == OP_PUSHDATA4)
494 memcpy(&nSize, &pc[0], 4);
497 if (end() - pc < 0 || (uint32_t)(end() - pc) < nSize)
500 pvchRet->assign(pc, pc + nSize);
504 opcodeRet = (opcodetype)opcode;
508 // Encode/decode small integers:
509 static int DecodeOP_N(opcodetype opcode)
513 assert(opcode >= OP_1 && opcode <= OP_16);
514 return (opcode - (OP_1 - 1));
516 static opcodetype EncodeOP_N(int n)
518 assert(n >= 0 && n <= 16);
521 return (opcodetype)(OP_1+n-1);
524 int FindAndDelete(const CScript& b)
529 iterator pc = begin();
533 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
535 erase(pc, pc + b.size());
539 while (GetOp(pc, opcode));
542 int Find(opcodetype op) const
546 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
552 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
553 // as 20 sigops. With pay-to-script-hash, that changed:
554 // CHECKMULTISIGs serialized in scriptSigs are
555 // counted more accurately, assuming they are of the form
556 // ... OP_N CHECKMULTISIG ...
557 unsigned int GetSigOpCount(bool fAccurate) const;
559 // Accurately count sigOps, including sigOps in
560 // pay-to-script-hash transactions:
561 unsigned int GetSigOpCount(const CScript& scriptSig) const;
563 bool IsPayToScriptHash() const;
565 bool IsPushOnly(const_iterator pc) const
570 if (!GetOp(pc, opcode))
578 // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
579 bool IsPushOnly() const
581 return this->IsPushOnly(begin());
584 // Called by CTransaction::IsStandard.
585 bool HasCanonicalPushes() const;
587 void SetDestination(const CTxDestination& address);
588 void SetAddress(const CBitcoinAddress& dest);
589 void SetMultisig(int nRequired, const std::vector<CPubKey>& keys);
592 void PrintHex() const
594 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
597 std::string ToString(bool fShort=false) const
601 std::vector<uint8_t> vch;
602 const_iterator pc = begin();
607 if (!GetOp(pc, opcode, vch))
612 if (0 <= opcode && opcode <= OP_PUSHDATA4)
613 str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
615 str += GetOpName(opcode);
622 printf("%s\n", ToString().c_str());
625 CScriptID GetID() const
627 return CScriptID(Hash160(*this));
631 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey, unsigned int flags);
632 bool IsDERSignature(const valtype &vchSig, bool fWithHashType=false, bool fCheckLow=false);
633 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig, unsigned int flags);
635 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
636 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
637 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
638 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
639 isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
640 //isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest);
641 isminetype IsMine(const CKeyStore& keystore, const CBitcoinAddress& dest);
642 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
643 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
644 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet);
645 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
646 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
647 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
648 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
650 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
651 // combine them intelligently and return the result.
652 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);