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>
12 #include <boost/variant.hpp>
17 typedef std::vector<unsigned char> valtype;
21 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
23 /** Signature hash types/flags */
29 SIGHASH_ANYONECANPAY = 0x80,
32 /** Script verification flags */
35 SCRIPT_VERIFY_NONE = 0,
36 SCRIPT_VERIFY_P2SH = (1U << 0), // evaluate P2SH (BIP16) subscripts
37 SCRIPT_VERIFY_STRICTENC = (1U << 1), // enforce strict conformance to DER and SEC2 for signatures and pubkeys
38 SCRIPT_VERIFY_LOW_S = (1U << 2), // enforce low S values in signatures (depends on STRICTENC)
39 SCRIPT_VERIFY_NOCACHE = (1U << 3), // do not store results in signature cache (but do query it)
40 SCRIPT_VERIFY_NULLDUMMY = (1U << 4), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length
43 // Strict verification:
45 // * force DER encoding;
47 // * ensure that CHECKMULTISIG dummy argument is null.
48 static const unsigned int STRICT_FORMAT_FLAGS = SCRIPT_VERIFY_STRICTENC | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_NULLDUMMY;
50 // Mandatory script verification flags that all new blocks must comply with for
51 // them to be valid. (but old blocks may not comply with) Currently just P2SH,
52 // but in the future other flags may be added, such as a soft-fork to enforce
53 // strict DER encoding.
55 // Failing one of these tests may trigger a DoS ban - see ConnectInputs() for
57 static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH;
59 // Standard script verification flags that standard transactions will comply
60 // with. However scripts violating these flags may still be present in valid
61 // blocks and we must accept those blocks.
62 static const unsigned int STRICT_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS | STRICT_FORMAT_FLAGS;
64 // Soft verifications, no extended signature format checkings
65 static const unsigned int SOFT_FLAGS = STRICT_FLAGS & ~STRICT_FORMAT_FLAGS;
70 // 'standard' transaction types:
78 class CNoDestination {
80 friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
81 friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
84 /** A txout script template with a specific destination. It is either:
85 * * CNoDestination: no destination set
86 * * CKeyID: TX_PUBKEYHASH destination
87 * * CScriptID: TX_SCRIPTHASH destination
88 * A CTxDestination is the internal data type encoded in a CBitcoinAddress
90 typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
92 const char* GetTxnOutputType(txnouttype t);
136 OP_TOALTSTACK = 0x6b,
137 OP_FROMALTSTACK = 0x6c,
169 OP_EQUALVERIFY = 0x88,
194 OP_NUMEQUALVERIFY = 0x9d,
195 OP_NUMNOTEQUAL = 0x9e,
197 OP_GREATERTHAN = 0xa0,
198 OP_LESSTHANOREQUAL = 0xa1,
199 OP_GREATERTHANOREQUAL = 0xa2,
211 OP_CODESEPARATOR = 0xab,
213 OP_CHECKSIGVERIFY = 0xad,
214 OP_CHECKMULTISIG = 0xae,
215 OP_CHECKMULTISIGVERIFY = 0xaf,
231 // template matching params
233 OP_SMALLINTEGER = 0xfa,
235 OP_PUBKEYHASH = 0xfd,
238 OP_INVALIDOPCODE = 0xff,
241 const char* GetOpName(opcodetype opcode);
245 inline std::string ValueString(const std::vector<unsigned char>& vch)
248 return strprintf("%d", CBigNum(vch).getint());
253 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
256 BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
260 str += ValueString(vch);
272 /** Serialized script, used inside transaction inputs and outputs */
273 class CScript : public std::vector<unsigned char>
276 CScript& push_int64(int64 n)
278 if (n == -1 || (n >= 1 && n <= 16))
280 push_back(n + (OP_1 - 1));
285 *this << bn.getvch();
290 CScript& push_uint64(uint64 n)
292 if (n >= 1 && n <= 16)
294 push_back(n + (OP_1 - 1));
299 *this << bn.getvch();
306 CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
307 CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
309 CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
312 CScript& operator+=(const CScript& b)
314 insert(end(), b.begin(), b.end());
318 friend CScript operator+(const CScript& a, const CScript& b)
326 //explicit CScript(char b) is not portable. Use 'signed char' or 'unsigned char'.
327 explicit CScript(signed char b) { operator<<(b); }
328 explicit CScript(short b) { operator<<(b); }
329 explicit CScript(int b) { operator<<(b); }
330 explicit CScript(long b) { operator<<(b); }
331 explicit CScript(int64 b) { operator<<(b); }
332 explicit CScript(unsigned char b) { operator<<(b); }
333 explicit CScript(unsigned int b) { operator<<(b); }
334 explicit CScript(unsigned short b) { operator<<(b); }
335 explicit CScript(unsigned long b) { operator<<(b); }
336 explicit CScript(uint64 b) { operator<<(b); }
338 explicit CScript(opcodetype b) { operator<<(b); }
339 explicit CScript(const uint256& b) { operator<<(b); }
340 explicit CScript(const CBigNum& b) { operator<<(b); }
341 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
344 //CScript& operator<<(char b) is not portable. Use 'signed char' or 'unsigned char'.
345 CScript& operator<<(signed char b) { return push_int64(b); }
346 CScript& operator<<(short b) { return push_int64(b); }
347 CScript& operator<<(int b) { return push_int64(b); }
348 CScript& operator<<(long b) { return push_int64(b); }
349 CScript& operator<<(int64 b) { return push_int64(b); }
350 CScript& operator<<(unsigned char b) { return push_uint64(b); }
351 CScript& operator<<(unsigned int b) { return push_uint64(b); }
352 CScript& operator<<(unsigned short b) { return push_uint64(b); }
353 CScript& operator<<(unsigned long b) { return push_uint64(b); }
354 CScript& operator<<(uint64 b) { return push_uint64(b); }
356 CScript& operator<<(opcodetype opcode)
358 if (opcode < 0 || opcode > 0xff)
359 throw std::runtime_error("CScript::operator<<() : invalid opcode");
360 insert(end(), (unsigned char)opcode);
364 CScript& operator<<(const uint160& b)
366 insert(end(), sizeof(b));
367 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
371 CScript& operator<<(const uint256& b)
373 insert(end(), sizeof(b));
374 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
378 CScript& operator<<(const CPubKey& key)
380 std::vector<unsigned char> vchKey = key.Raw();
381 return (*this) << vchKey;
384 CScript& operator<<(const CBigNum& b)
390 CScript& operator<<(const std::vector<unsigned char>& b)
392 if (b.size() < OP_PUSHDATA1)
394 insert(end(), (unsigned char)b.size());
396 else if (b.size() <= 0xff)
398 insert(end(), OP_PUSHDATA1);
399 insert(end(), (unsigned char)b.size());
401 else if (b.size() <= 0xffff)
403 insert(end(), OP_PUSHDATA2);
404 unsigned short nSize = b.size();
405 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
409 insert(end(), OP_PUSHDATA4);
410 unsigned int nSize = b.size();
411 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
413 insert(end(), b.begin(), b.end());
417 CScript& operator<<(const CScript& b)
419 // I'm not sure if this should push the script or concatenate scripts.
420 // If there's ever a use for pushing a script onto a script, delete this member fn
421 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
426 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
428 // Wrapper so it can be called with either iterator or const_iterator
429 const_iterator pc2 = pc;
430 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
431 pc = begin() + (pc2 - begin());
435 bool GetOp(iterator& pc, opcodetype& opcodeRet)
437 const_iterator pc2 = pc;
438 bool fRet = GetOp2(pc2, opcodeRet, NULL);
439 pc = begin() + (pc2 - begin());
443 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
445 return GetOp2(pc, opcodeRet, &vchRet);
448 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
450 return GetOp2(pc, opcodeRet, NULL);
453 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
455 opcodeRet = OP_INVALIDOPCODE;
464 unsigned int opcode = *pc++;
467 if (opcode <= OP_PUSHDATA4)
470 if (opcode < OP_PUSHDATA1)
474 else if (opcode == OP_PUSHDATA1)
480 else if (opcode == OP_PUSHDATA2)
485 memcpy(&nSize, &pc[0], 2);
488 else if (opcode == OP_PUSHDATA4)
492 memcpy(&nSize, &pc[0], 4);
495 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
498 pvchRet->assign(pc, pc + nSize);
502 opcodeRet = (opcodetype)opcode;
506 // Encode/decode small integers:
507 static int DecodeOP_N(opcodetype opcode)
511 assert(opcode >= OP_1 && opcode <= OP_16);
512 return (int)opcode - (int)(OP_1 - 1);
514 static opcodetype EncodeOP_N(int n)
516 assert(n >= 0 && n <= 16);
519 return (opcodetype)(OP_1+n-1);
522 int FindAndDelete(const CScript& b)
527 iterator pc = begin();
531 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
533 erase(pc, pc + b.size());
537 while (GetOp(pc, opcode));
540 int Find(opcodetype op) const
544 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
550 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
551 // as 20 sigops. With pay-to-script-hash, that changed:
552 // CHECKMULTISIGs serialized in scriptSigs are
553 // counted more accurately, assuming they are of the form
554 // ... OP_N CHECKMULTISIG ...
555 unsigned int GetSigOpCount(bool fAccurate) const;
557 // Accurately count sigOps, including sigOps in
558 // pay-to-script-hash transactions:
559 unsigned int GetSigOpCount(const CScript& scriptSig) const;
561 bool IsPayToScriptHash() const;
563 // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
564 bool IsPushOnly() const
566 const_iterator pc = begin();
570 if (!GetOp(pc, opcode))
578 // Called by CTransaction::IsStandard.
579 bool HasCanonicalPushes() const;
581 void SetDestination(const CTxDestination& address);
582 void SetMultisig(int nRequired, const std::vector<CKey>& keys);
585 void PrintHex() const
587 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
590 std::string ToString(bool fShort=false) const
594 std::vector<unsigned char> vch;
595 const_iterator pc = begin();
600 if (!GetOp(pc, opcode, vch))
605 if (0 <= opcode && opcode <= OP_PUSHDATA4)
606 str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
608 str += GetOpName(opcode);
615 printf("%s\n", ToString().c_str());
618 CScriptID GetID() const
620 return CScriptID(Hash160(*this));
624 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey, unsigned int flags);
625 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig, unsigned int flags);
628 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
629 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
630 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
631 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
632 bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
633 bool IsMine(const CKeyStore& keystore, const CTxDestination &dest);
634 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
635 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
636 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
637 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
638 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
639 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
641 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
642 // combine them intelligently and return the result.
643 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);