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>
20 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
22 /** Signature hash types/flags */
28 SIGHASH_ANYONECANPAY = 0x80,
31 /** Script verification flags */
34 SCRIPT_VERIFY_NONE = 0,
35 SCRIPT_VERIFY_P2SH = (1U << 0),
36 SCRIPT_VERIFY_STRICTENC = (1U << 1),
37 SCRIPT_VERIFY_NOCACHE = (1U << 2),
43 // 'standard' transaction types:
50 class CNoDestination {
52 friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
53 friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
56 /** A txout script template with a specific destination. It is either:
57 * * CNoDestination: no destination set
58 * * CKeyID: TX_PUBKEYHASH destination
59 * * CScriptID: TX_SCRIPTHASH destination
60 * A CTxDestination is the internal data type encoded in a CBitcoinAddress
62 typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
64 const char* GetTxnOutputType(txnouttype t);
108 OP_TOALTSTACK = 0x6b,
109 OP_FROMALTSTACK = 0x6c,
141 OP_EQUALVERIFY = 0x88,
166 OP_NUMEQUALVERIFY = 0x9d,
167 OP_NUMNOTEQUAL = 0x9e,
169 OP_GREATERTHAN = 0xa0,
170 OP_LESSTHANOREQUAL = 0xa1,
171 OP_GREATERTHANOREQUAL = 0xa2,
183 OP_CODESEPARATOR = 0xab,
185 OP_CHECKSIGVERIFY = 0xad,
186 OP_CHECKMULTISIG = 0xae,
187 OP_CHECKMULTISIGVERIFY = 0xaf,
203 // template matching params
204 OP_SMALLINTEGER = 0xfa,
206 OP_PUBKEYHASH = 0xfd,
209 OP_INVALIDOPCODE = 0xff,
212 const char* GetOpName(opcodetype opcode);
216 inline std::string ValueString(const std::vector<unsigned char>& vch)
219 return strprintf("%d", CBigNum(vch).getint());
224 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
227 BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
231 str += ValueString(vch);
243 /** Serialized script, used inside transaction inputs and outputs */
244 class CScript : public std::vector<unsigned char>
247 CScript& push_int64(int64 n)
249 if (n == -1 || (n >= 1 && n <= 16))
251 push_back(n + (OP_1 - 1));
256 *this << bn.getvch();
261 CScript& push_uint64(uint64 n)
263 if (n >= 1 && n <= 16)
265 push_back(n + (OP_1 - 1));
270 *this << bn.getvch();
277 CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
278 CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
280 CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
283 CScript& operator+=(const CScript& b)
285 insert(end(), b.begin(), b.end());
289 friend CScript operator+(const CScript& a, const CScript& b)
297 //explicit CScript(char b) is not portable. Use 'signed char' or 'unsigned char'.
298 explicit CScript(signed char b) { operator<<(b); }
299 explicit CScript(short b) { operator<<(b); }
300 explicit CScript(int b) { operator<<(b); }
301 explicit CScript(long b) { operator<<(b); }
302 explicit CScript(int64 b) { operator<<(b); }
303 explicit CScript(unsigned char b) { operator<<(b); }
304 explicit CScript(unsigned int b) { operator<<(b); }
305 explicit CScript(unsigned short b) { operator<<(b); }
306 explicit CScript(unsigned long b) { operator<<(b); }
307 explicit CScript(uint64 b) { operator<<(b); }
309 explicit CScript(opcodetype b) { operator<<(b); }
310 explicit CScript(const uint256& b) { operator<<(b); }
311 explicit CScript(const CBigNum& b) { operator<<(b); }
312 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
315 //CScript& operator<<(char b) is not portable. Use 'signed char' or 'unsigned char'.
316 CScript& operator<<(signed char b) { return push_int64(b); }
317 CScript& operator<<(short b) { return push_int64(b); }
318 CScript& operator<<(int b) { return push_int64(b); }
319 CScript& operator<<(long b) { return push_int64(b); }
320 CScript& operator<<(int64 b) { return push_int64(b); }
321 CScript& operator<<(unsigned char b) { return push_uint64(b); }
322 CScript& operator<<(unsigned int b) { return push_uint64(b); }
323 CScript& operator<<(unsigned short b) { return push_uint64(b); }
324 CScript& operator<<(unsigned long b) { return push_uint64(b); }
325 CScript& operator<<(uint64 b) { return push_uint64(b); }
327 CScript& operator<<(opcodetype opcode)
329 if (opcode < 0 || opcode > 0xff)
330 throw std::runtime_error("CScript::operator<<() : invalid opcode");
331 insert(end(), (unsigned char)opcode);
335 CScript& operator<<(const uint160& b)
337 insert(end(), sizeof(b));
338 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
342 CScript& operator<<(const uint256& b)
344 insert(end(), sizeof(b));
345 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
349 CScript& operator<<(const CPubKey& key)
351 std::vector<unsigned char> vchKey = key.Raw();
352 return (*this) << vchKey;
355 CScript& operator<<(const CBigNum& b)
361 CScript& operator<<(const std::vector<unsigned char>& b)
363 if (b.size() < OP_PUSHDATA1)
365 insert(end(), (unsigned char)b.size());
367 else if (b.size() <= 0xff)
369 insert(end(), OP_PUSHDATA1);
370 insert(end(), (unsigned char)b.size());
372 else if (b.size() <= 0xffff)
374 insert(end(), OP_PUSHDATA2);
375 unsigned short nSize = b.size();
376 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
380 insert(end(), OP_PUSHDATA4);
381 unsigned int nSize = b.size();
382 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
384 insert(end(), b.begin(), b.end());
388 CScript& operator<<(const CScript& b)
390 // I'm not sure if this should push the script or concatenate scripts.
391 // If there's ever a use for pushing a script onto a script, delete this member fn
392 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
397 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
399 // Wrapper so it can be called with either iterator or const_iterator
400 const_iterator pc2 = pc;
401 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
402 pc = begin() + (pc2 - begin());
406 bool GetOp(iterator& pc, opcodetype& opcodeRet)
408 const_iterator pc2 = pc;
409 bool fRet = GetOp2(pc2, opcodeRet, NULL);
410 pc = begin() + (pc2 - begin());
414 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
416 return GetOp2(pc, opcodeRet, &vchRet);
419 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
421 return GetOp2(pc, opcodeRet, NULL);
424 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
426 opcodeRet = OP_INVALIDOPCODE;
435 unsigned int opcode = *pc++;
438 if (opcode <= OP_PUSHDATA4)
440 unsigned int nSize = 0;
441 if (opcode < OP_PUSHDATA1)
445 else if (opcode == OP_PUSHDATA1)
451 else if (opcode == OP_PUSHDATA2)
456 memcpy(&nSize, &pc[0], 2);
459 else if (opcode == OP_PUSHDATA4)
463 memcpy(&nSize, &pc[0], 4);
466 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
469 pvchRet->assign(pc, pc + nSize);
473 opcodeRet = (opcodetype)opcode;
477 // Encode/decode small integers:
478 static int DecodeOP_N(opcodetype opcode)
482 assert(opcode >= OP_1 && opcode <= OP_16);
483 return (int)opcode - (int)(OP_1 - 1);
485 static opcodetype EncodeOP_N(int n)
487 assert(n >= 0 && n <= 16);
490 return (opcodetype)(OP_1+n-1);
493 int FindAndDelete(const CScript& b)
498 iterator pc = begin();
502 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
504 erase(pc, pc + b.size());
508 while (GetOp(pc, opcode));
511 int Find(opcodetype op) const
515 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
521 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
522 // as 20 sigops. With pay-to-script-hash, that changed:
523 // CHECKMULTISIGs serialized in scriptSigs are
524 // counted more accurately, assuming they are of the form
525 // ... OP_N CHECKMULTISIG ...
526 unsigned int GetSigOpCount(bool fAccurate) const;
528 // Accurately count sigOps, including sigOps in
529 // pay-to-script-hash transactions:
530 unsigned int GetSigOpCount(const CScript& scriptSig) const;
532 bool IsPayToScriptHash() const;
534 // Called by CTransaction::IsStandard
535 bool IsPushOnly() const
537 const_iterator pc = begin();
541 if (!GetOp(pc, opcode))
550 void SetDestination(const CTxDestination& address);
551 void SetMultisig(int nRequired, const std::vector<CKey>& keys);
554 void PrintHex() const
556 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
559 std::string ToString() const
563 std::vector<unsigned char> vch;
564 const_iterator pc = begin();
569 if (!GetOp(pc, opcode, vch))
574 if (0 <= opcode && opcode <= OP_PUSHDATA4)
575 str += ValueString(vch);
577 str += GetOpName(opcode);
584 printf("%s\n", ToString().c_str());
587 CScriptID GetID() const
589 return CScriptID(Hash160(*this));
593 /** Compact serializer for scripts.
595 * It detects common cases and encodes them much more efficiently.
596 * 3 special cases are defined:
597 * * Pay to pubkey hash (encoded as 21 bytes)
598 * * Pay to script hash (encoded as 21 bytes)
599 * * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
601 * Other scripts up to 121 bytes require 1 byte + script length. Above
602 * that, scripts up to 16505 bytes require 2 bytes + script length.
604 class CScriptCompressor
607 // make this static for now (there are only 6 special scripts defined)
608 // this can potentially be extended together with a new nVersion for
609 // transactions, in which case this value becomes dependent on nVersion
610 // and nHeight of the enclosing transaction.
611 static const unsigned int nSpecialScripts = 6;
615 // These check for scripts for which a special case with a shorter encoding is defined.
616 // They are implemented separately from the CScript test, as these test for exact byte
617 // sequence correspondences, and are more strict. For example, IsToPubKey also verifies
618 // whether the public key is valid (as invalid ones cannot be represented in compressed
620 bool IsToKeyID(CKeyID &hash) const;
621 bool IsToScriptID(CScriptID &hash) const;
622 bool IsToPubKey(std::vector<unsigned char> &pubkey) const;
624 bool Compress(std::vector<unsigned char> &out) const;
625 unsigned int GetSpecialSize(unsigned int nSize) const;
626 bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
628 CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
630 unsigned int GetSerializeSize(int nType, int nVersion) const {
631 std::vector<unsigned char> compr;
634 unsigned int nSize = script.size() + nSpecialScripts;
635 return script.size() + VARINT(nSize).GetSerializeSize(nType, nVersion);
638 template<typename Stream>
639 void Serialize(Stream &s, int nType, int nVersion) const {
640 std::vector<unsigned char> compr;
641 if (Compress(compr)) {
642 s << CFlatData(&compr[0], &compr[compr.size()]);
645 unsigned int nSize = script.size() + nSpecialScripts;
647 s << CFlatData(&script[0], &script[script.size()]);
650 template<typename Stream>
651 void Unserialize(Stream &s, int nType, int nVersion) {
652 unsigned int nSize = 0;
654 if (nSize < nSpecialScripts) {
655 std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
656 s >> REF(CFlatData(&vch[0], &vch[vch.size()]));
657 Decompress(nSize, vch);
660 nSize -= nSpecialScripts;
661 script.resize(nSize);
662 s >> REF(CFlatData(&script[0], &script[script.size()]));
666 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey);
667 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig);
669 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
670 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
671 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
672 bool IsStandard(const CScript& scriptPubKey);
673 bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
674 bool IsMine(const CKeyStore& keystore, const CTxDestination &dest);
675 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
676 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
677 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
678 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
679 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
681 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
682 // combine them intelligently and return the result.
683 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);