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>
16 typedef std::vector<unsigned char> valtype;
20 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
22 /** IsMine() return codes */
28 MINE_ALL = MINE_WATCH_ONLY | MINE_SPENDABLE
31 typedef uint8_t isminefilter;
33 /** Signature hash types/flags */
39 SIGHASH_ANYONECANPAY = 0x80,
42 /** Script verification flags */
45 SCRIPT_VERIFY_NONE = 0,
46 SCRIPT_VERIFY_P2SH = (1U << 0), // evaluate P2SH (BIP16) subscripts
47 SCRIPT_VERIFY_STRICTENC = (1U << 1), // enforce strict conformance to DER and SEC2 for signatures and pubkeys
48 SCRIPT_VERIFY_LOW_S = (1U << 2), // enforce low S values in signatures (depends on STRICTENC)
49 SCRIPT_VERIFY_NOCACHE = (1U << 3), // do not store results in signature cache (but do query it)
50 SCRIPT_VERIFY_NULLDUMMY = (1U << 4), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length
53 // Strict verification:
55 // * force DER encoding;
57 // * ensure that CHECKMULTISIG dummy argument is null.
58 static const unsigned int STRICT_FORMAT_FLAGS = SCRIPT_VERIFY_STRICTENC | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_NULLDUMMY;
60 // Mandatory script verification flags that all new blocks must comply with for
61 // them to be valid. (but old blocks may not comply with) Currently just P2SH,
62 // but in the future other flags may be added, such as a soft-fork to enforce
63 // strict DER encoding.
65 // Failing one of these tests may trigger a DoS ban - see ConnectInputs() for
67 static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH;
69 // Standard script verification flags that standard transactions will comply
70 // with. However scripts violating these flags may still be present in valid
71 // blocks and we must accept those blocks.
72 static const unsigned int STRICT_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS | STRICT_FORMAT_FLAGS;
74 // Soft verifications, no extended signature format checkings
75 static const unsigned int SOFT_FLAGS = STRICT_FLAGS & ~STRICT_FORMAT_FLAGS;
80 // 'standard' transaction types:
88 const char* GetTxnOutputType(txnouttype t);
132 OP_TOALTSTACK = 0x6b,
133 OP_FROMALTSTACK = 0x6c,
165 OP_EQUALVERIFY = 0x88,
190 OP_NUMEQUALVERIFY = 0x9d,
191 OP_NUMNOTEQUAL = 0x9e,
193 OP_GREATERTHAN = 0xa0,
194 OP_LESSTHANOREQUAL = 0xa1,
195 OP_GREATERTHANOREQUAL = 0xa2,
207 OP_CODESEPARATOR = 0xab,
209 OP_CHECKSIGVERIFY = 0xad,
210 OP_CHECKMULTISIG = 0xae,
211 OP_CHECKMULTISIGVERIFY = 0xaf,
227 // template matching params
229 OP_SMALLINTEGER = 0xfa,
231 OP_PUBKEYHASH = 0xfd,
234 OP_INVALIDOPCODE = 0xff,
237 const char* GetOpName(opcodetype opcode);
241 inline std::string ValueString(const std::vector<unsigned char>& vch)
244 return strprintf("%d", CBigNum(vch).getint());
249 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
252 BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
256 str += ValueString(vch);
268 /** Serialized script, used inside transaction inputs and outputs */
269 class CScript : public std::vector<unsigned char>
272 CScript& push_int64(int64 n)
274 if (n == -1 || (n >= 1 && n <= 16))
276 push_back(n + (OP_1 - 1));
281 *this << bn.getvch();
286 CScript& push_uint64(uint64 n)
288 if (n >= 1 && n <= 16)
290 push_back(n + (OP_1 - 1));
295 *this << bn.getvch();
302 CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
303 CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
305 CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
308 CScript& operator+=(const CScript& b)
310 insert(end(), b.begin(), b.end());
314 friend CScript operator+(const CScript& a, const CScript& b)
322 //explicit CScript(char b) is not portable. Use 'signed char' or 'unsigned char'.
323 explicit CScript(signed char b) { operator<<(b); }
324 explicit CScript(short b) { operator<<(b); }
325 explicit CScript(int b) { operator<<(b); }
326 explicit CScript(long b) { operator<<(b); }
327 explicit CScript(int64 b) { operator<<(b); }
328 explicit CScript(unsigned char b) { operator<<(b); }
329 explicit CScript(unsigned int b) { operator<<(b); }
330 explicit CScript(unsigned short b) { operator<<(b); }
331 explicit CScript(unsigned long b) { operator<<(b); }
332 explicit CScript(uint64 b) { operator<<(b); }
334 explicit CScript(opcodetype b) { operator<<(b); }
335 explicit CScript(const uint256& b) { operator<<(b); }
336 explicit CScript(const CBigNum& b) { operator<<(b); }
337 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
340 //CScript& operator<<(char b) is not portable. Use 'signed char' or 'unsigned char'.
341 CScript& operator<<(signed char b) { return push_int64(b); }
342 CScript& operator<<(short b) { return push_int64(b); }
343 CScript& operator<<(int b) { return push_int64(b); }
344 CScript& operator<<(long b) { return push_int64(b); }
345 CScript& operator<<(int64 b) { return push_int64(b); }
346 CScript& operator<<(unsigned char b) { return push_uint64(b); }
347 CScript& operator<<(unsigned int b) { return push_uint64(b); }
348 CScript& operator<<(unsigned short b) { return push_uint64(b); }
349 CScript& operator<<(unsigned long b) { return push_uint64(b); }
350 CScript& operator<<(uint64 b) { return push_uint64(b); }
352 CScript& operator<<(opcodetype opcode)
354 if (opcode < 0 || opcode > 0xff)
355 throw std::runtime_error("CScript::operator<<() : invalid opcode");
356 insert(end(), (unsigned char)opcode);
360 CScript& operator<<(const uint160& b)
362 insert(end(), sizeof(b));
363 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
367 CScript& operator<<(const uint256& b)
369 insert(end(), sizeof(b));
370 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
374 CScript& operator<<(const CPubKey& key)
376 std::vector<unsigned char> vchKey = key.Raw();
377 return (*this) << vchKey;
380 CScript& operator<<(const CBigNum& b)
386 CScript& operator<<(const std::vector<unsigned char>& b)
388 if (b.size() < OP_PUSHDATA1)
390 insert(end(), (unsigned char)b.size());
392 else if (b.size() <= 0xff)
394 insert(end(), OP_PUSHDATA1);
395 insert(end(), (unsigned char)b.size());
397 else if (b.size() <= 0xffff)
399 insert(end(), OP_PUSHDATA2);
400 unsigned short nSize = b.size();
401 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
405 insert(end(), OP_PUSHDATA4);
406 unsigned int nSize = b.size();
407 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
409 insert(end(), b.begin(), b.end());
413 CScript& operator<<(const CScript& b)
415 // I'm not sure if this should push the script or concatenate scripts.
416 // If there's ever a use for pushing a script onto a script, delete this member fn
417 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
422 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
424 // Wrapper so it can be called with either iterator or const_iterator
425 const_iterator pc2 = pc;
426 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
427 pc = begin() + (pc2 - begin());
431 bool GetOp(iterator& pc, opcodetype& opcodeRet)
433 const_iterator pc2 = pc;
434 bool fRet = GetOp2(pc2, opcodeRet, NULL);
435 pc = begin() + (pc2 - begin());
439 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
441 return GetOp2(pc, opcodeRet, &vchRet);
444 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
446 return GetOp2(pc, opcodeRet, NULL);
449 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
451 opcodeRet = OP_INVALIDOPCODE;
460 unsigned int opcode = *pc++;
463 if (opcode <= OP_PUSHDATA4)
466 if (opcode < OP_PUSHDATA1)
470 else if (opcode == OP_PUSHDATA1)
476 else if (opcode == OP_PUSHDATA2)
481 memcpy(&nSize, &pc[0], 2);
484 else if (opcode == OP_PUSHDATA4)
488 memcpy(&nSize, &pc[0], 4);
491 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
494 pvchRet->assign(pc, pc + nSize);
498 opcodeRet = (opcodetype)opcode;
502 // Encode/decode small integers:
503 static int DecodeOP_N(opcodetype opcode)
507 assert(opcode >= OP_1 && opcode <= OP_16);
508 return (int)opcode - (int)(OP_1 - 1);
510 static opcodetype EncodeOP_N(int n)
512 assert(n >= 0 && n <= 16);
515 return (opcodetype)(OP_1+n-1);
518 int FindAndDelete(const CScript& b)
523 iterator pc = begin();
527 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
529 erase(pc, pc + b.size());
533 while (GetOp(pc, opcode));
536 int Find(opcodetype op) const
540 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
546 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
547 // as 20 sigops. With pay-to-script-hash, that changed:
548 // CHECKMULTISIGs serialized in scriptSigs are
549 // counted more accurately, assuming they are of the form
550 // ... OP_N CHECKMULTISIG ...
551 unsigned int GetSigOpCount(bool fAccurate) const;
553 // Accurately count sigOps, including sigOps in
554 // pay-to-script-hash transactions:
555 unsigned int GetSigOpCount(const CScript& scriptSig) const;
557 bool IsPayToScriptHash() const;
559 // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
560 bool IsPushOnly() const
562 const_iterator pc = begin();
566 if (!GetOp(pc, opcode))
574 // Called by CTransaction::IsStandard.
575 bool HasCanonicalPushes() const;
577 void SetDestination(const CTxDestination& address);
578 void SetMultisig(int nRequired, const std::vector<CKey>& keys);
581 void PrintHex() const
583 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
586 std::string ToString(bool fShort=false) const
590 std::vector<unsigned char> vch;
591 const_iterator pc = begin();
596 if (!GetOp(pc, opcode, vch))
601 if (0 <= opcode && opcode <= OP_PUSHDATA4)
602 str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
604 str += GetOpName(opcode);
611 printf("%s\n", ToString().c_str());
614 CScriptID GetID() const
616 return CScriptID(Hash160(*this));
620 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey, unsigned int flags);
621 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig, unsigned int flags);
624 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
625 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
626 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
627 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
628 isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
629 isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest);
630 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
631 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
632 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
633 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
634 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
635 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
637 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
638 // combine them intelligently and return the result.
639 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);