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 */
30 /** Signature hash types/flags */
36 SIGHASH_ANYONECANPAY = 0x80,
39 /** Script verification flags */
42 SCRIPT_VERIFY_NONE = 0,
43 SCRIPT_VERIFY_P2SH = (1U << 0), // evaluate P2SH (BIP16) subscripts
44 SCRIPT_VERIFY_STRICTENC = (1U << 1), // enforce strict conformance to DER and SEC2 for signatures and pubkeys
45 SCRIPT_VERIFY_LOW_S = (1U << 2), // enforce low S values in signatures (depends on STRICTENC)
46 SCRIPT_VERIFY_NOCACHE = (1U << 3), // do not store results in signature cache (but do query it)
47 SCRIPT_VERIFY_NULLDUMMY = (1U << 4), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length
50 // Strict verification:
52 // * force DER encoding;
54 // * ensure that CHECKMULTISIG dummy argument is null.
55 static const unsigned int STRICT_FORMAT_FLAGS = SCRIPT_VERIFY_STRICTENC | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_NULLDUMMY;
57 // Mandatory script verification flags that all new blocks must comply with for
58 // them to be valid. (but old blocks may not comply with) Currently just P2SH,
59 // but in the future other flags may be added, such as a soft-fork to enforce
60 // strict DER encoding.
62 // Failing one of these tests may trigger a DoS ban - see ConnectInputs() for
64 static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH;
66 // Standard script verification flags that standard transactions will comply
67 // with. However scripts violating these flags may still be present in valid
68 // blocks and we must accept those blocks.
69 static const unsigned int STRICT_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS | STRICT_FORMAT_FLAGS;
71 // Soft verifications, no extended signature format checkings
72 static const unsigned int SOFT_FLAGS = STRICT_FLAGS & ~STRICT_FORMAT_FLAGS;
77 // 'standard' transaction types:
85 const char* GetTxnOutputType(txnouttype t);
129 OP_TOALTSTACK = 0x6b,
130 OP_FROMALTSTACK = 0x6c,
162 OP_EQUALVERIFY = 0x88,
187 OP_NUMEQUALVERIFY = 0x9d,
188 OP_NUMNOTEQUAL = 0x9e,
190 OP_GREATERTHAN = 0xa0,
191 OP_LESSTHANOREQUAL = 0xa1,
192 OP_GREATERTHANOREQUAL = 0xa2,
204 OP_CODESEPARATOR = 0xab,
206 OP_CHECKSIGVERIFY = 0xad,
207 OP_CHECKMULTISIG = 0xae,
208 OP_CHECKMULTISIGVERIFY = 0xaf,
224 // template matching params
226 OP_SMALLINTEGER = 0xfa,
228 OP_PUBKEYHASH = 0xfd,
231 OP_INVALIDOPCODE = 0xff,
234 const char* GetOpName(opcodetype opcode);
238 inline std::string ValueString(const std::vector<unsigned char>& vch)
241 return strprintf("%d", CBigNum(vch).getint());
246 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
249 BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
253 str += ValueString(vch);
265 /** Serialized script, used inside transaction inputs and outputs */
266 class CScript : public std::vector<unsigned char>
269 CScript& push_int64(int64 n)
271 if (n == -1 || (n >= 1 && n <= 16))
273 push_back(n + (OP_1 - 1));
278 *this << bn.getvch();
283 CScript& push_uint64(uint64 n)
285 if (n >= 1 && n <= 16)
287 push_back(n + (OP_1 - 1));
292 *this << bn.getvch();
299 CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
300 CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
302 CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
305 CScript& operator+=(const CScript& b)
307 insert(end(), b.begin(), b.end());
311 friend CScript operator+(const CScript& a, const CScript& b)
319 //explicit CScript(char b) is not portable. Use 'signed char' or 'unsigned char'.
320 explicit CScript(signed char b) { operator<<(b); }
321 explicit CScript(short b) { operator<<(b); }
322 explicit CScript(int b) { operator<<(b); }
323 explicit CScript(long b) { operator<<(b); }
324 explicit CScript(int64 b) { operator<<(b); }
325 explicit CScript(unsigned char b) { operator<<(b); }
326 explicit CScript(unsigned int b) { operator<<(b); }
327 explicit CScript(unsigned short b) { operator<<(b); }
328 explicit CScript(unsigned long b) { operator<<(b); }
329 explicit CScript(uint64 b) { operator<<(b); }
331 explicit CScript(opcodetype b) { operator<<(b); }
332 explicit CScript(const uint256& b) { operator<<(b); }
333 explicit CScript(const CBigNum& b) { operator<<(b); }
334 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
337 //CScript& operator<<(char b) is not portable. Use 'signed char' or 'unsigned char'.
338 CScript& operator<<(signed char b) { return push_int64(b); }
339 CScript& operator<<(short b) { return push_int64(b); }
340 CScript& operator<<(int b) { return push_int64(b); }
341 CScript& operator<<(long b) { return push_int64(b); }
342 CScript& operator<<(int64 b) { return push_int64(b); }
343 CScript& operator<<(unsigned char b) { return push_uint64(b); }
344 CScript& operator<<(unsigned int b) { return push_uint64(b); }
345 CScript& operator<<(unsigned short b) { return push_uint64(b); }
346 CScript& operator<<(unsigned long b) { return push_uint64(b); }
347 CScript& operator<<(uint64 b) { return push_uint64(b); }
349 CScript& operator<<(opcodetype opcode)
351 if (opcode < 0 || opcode > 0xff)
352 throw std::runtime_error("CScript::operator<<() : invalid opcode");
353 insert(end(), (unsigned char)opcode);
357 CScript& operator<<(const uint160& b)
359 insert(end(), sizeof(b));
360 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
364 CScript& operator<<(const uint256& b)
366 insert(end(), sizeof(b));
367 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
371 CScript& operator<<(const CPubKey& key)
373 std::vector<unsigned char> vchKey = key.Raw();
374 return (*this) << vchKey;
377 CScript& operator<<(const CBigNum& b)
383 CScript& operator<<(const std::vector<unsigned char>& b)
385 if (b.size() < OP_PUSHDATA1)
387 insert(end(), (unsigned char)b.size());
389 else if (b.size() <= 0xff)
391 insert(end(), OP_PUSHDATA1);
392 insert(end(), (unsigned char)b.size());
394 else if (b.size() <= 0xffff)
396 insert(end(), OP_PUSHDATA2);
397 unsigned short nSize = b.size();
398 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
402 insert(end(), OP_PUSHDATA4);
403 unsigned int nSize = b.size();
404 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
406 insert(end(), b.begin(), b.end());
410 CScript& operator<<(const CScript& b)
412 // I'm not sure if this should push the script or concatenate scripts.
413 // If there's ever a use for pushing a script onto a script, delete this member fn
414 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
419 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
421 // Wrapper so it can be called with either iterator or const_iterator
422 const_iterator pc2 = pc;
423 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
424 pc = begin() + (pc2 - begin());
428 bool GetOp(iterator& pc, opcodetype& opcodeRet)
430 const_iterator pc2 = pc;
431 bool fRet = GetOp2(pc2, opcodeRet, NULL);
432 pc = begin() + (pc2 - begin());
436 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
438 return GetOp2(pc, opcodeRet, &vchRet);
441 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
443 return GetOp2(pc, opcodeRet, NULL);
446 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
448 opcodeRet = OP_INVALIDOPCODE;
457 unsigned int opcode = *pc++;
460 if (opcode <= OP_PUSHDATA4)
463 if (opcode < OP_PUSHDATA1)
467 else if (opcode == OP_PUSHDATA1)
473 else if (opcode == OP_PUSHDATA2)
478 memcpy(&nSize, &pc[0], 2);
481 else if (opcode == OP_PUSHDATA4)
485 memcpy(&nSize, &pc[0], 4);
488 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
491 pvchRet->assign(pc, pc + nSize);
495 opcodeRet = (opcodetype)opcode;
499 // Encode/decode small integers:
500 static int DecodeOP_N(opcodetype opcode)
504 assert(opcode >= OP_1 && opcode <= OP_16);
505 return (int)opcode - (int)(OP_1 - 1);
507 static opcodetype EncodeOP_N(int n)
509 assert(n >= 0 && n <= 16);
512 return (opcodetype)(OP_1+n-1);
515 int FindAndDelete(const CScript& b)
520 iterator pc = begin();
524 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
526 erase(pc, pc + b.size());
530 while (GetOp(pc, opcode));
533 int Find(opcodetype op) const
537 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
543 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
544 // as 20 sigops. With pay-to-script-hash, that changed:
545 // CHECKMULTISIGs serialized in scriptSigs are
546 // counted more accurately, assuming they are of the form
547 // ... OP_N CHECKMULTISIG ...
548 unsigned int GetSigOpCount(bool fAccurate) const;
550 // Accurately count sigOps, including sigOps in
551 // pay-to-script-hash transactions:
552 unsigned int GetSigOpCount(const CScript& scriptSig) const;
554 bool IsPayToScriptHash() const;
556 // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
557 bool IsPushOnly() const
559 const_iterator pc = begin();
563 if (!GetOp(pc, opcode))
571 // Called by CTransaction::IsStandard.
572 bool HasCanonicalPushes() const;
574 void SetDestination(const CTxDestination& address);
575 void SetMultisig(int nRequired, const std::vector<CKey>& keys);
578 void PrintHex() const
580 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
583 std::string ToString(bool fShort=false) const
587 std::vector<unsigned char> vch;
588 const_iterator pc = begin();
593 if (!GetOp(pc, opcode, vch))
598 if (0 <= opcode && opcode <= OP_PUSHDATA4)
599 str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
601 str += GetOpName(opcode);
608 printf("%s\n", ToString().c_str());
611 CScriptID GetID() const
613 return CScriptID(Hash160(*this));
617 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey, unsigned int flags);
618 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig, unsigned int flags);
621 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
622 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
623 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
624 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
625 isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
626 isminetype IsMine(const CKeyStore& keystore, const CTxDestination &dest);
627 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
628 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
629 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
630 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
631 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
632 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
634 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
635 // combine them intelligently and return the result.
636 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);