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 typedef std::vector<unsigned char> valtype;
22 /** Signature hash types/flags */
28 SIGHASH_ANYONECANPAY = 0x80,
35 // 'standard' transaction types:
42 class CNoDestination {
44 friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
45 friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
48 /** A txout script template with a specific destination. It is either:
49 * * CNoDestination: no destination set
50 * * CKeyID: TX_PUBKEYHASH destination
51 * * CScriptID: TX_SCRIPTHASH destination
52 * A CTxDestination is the internal data type encoded in a CBitcoinAddress
54 typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
56 const char* GetTxnOutputType(txnouttype t);
100 OP_TOALTSTACK = 0x6b,
101 OP_FROMALTSTACK = 0x6c,
133 OP_EQUALVERIFY = 0x88,
158 OP_NUMEQUALVERIFY = 0x9d,
159 OP_NUMNOTEQUAL = 0x9e,
161 OP_GREATERTHAN = 0xa0,
162 OP_LESSTHANOREQUAL = 0xa1,
163 OP_GREATERTHANOREQUAL = 0xa2,
175 OP_CODESEPARATOR = 0xab,
177 OP_CHECKSIGVERIFY = 0xad,
178 OP_CHECKMULTISIG = 0xae,
179 OP_CHECKMULTISIGVERIFY = 0xaf,
195 // template matching params
196 OP_SMALLINTEGER = 0xfa,
198 OP_PUBKEYHASH = 0xfd,
201 OP_INVALIDOPCODE = 0xff,
204 const char* GetOpName(opcodetype opcode);
208 inline std::string ValueString(const std::vector<unsigned char>& vch)
211 return strprintf("%d", CBigNum(vch).getint());
216 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
219 BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
223 str += ValueString(vch);
235 /** Serialized script, used inside transaction inputs and outputs */
236 class CScript : public std::vector<unsigned char>
239 CScript& push_int64(int64 n)
241 if (n == -1 || (n >= 1 && n <= 16))
243 push_back(n + (OP_1 - 1));
248 *this << bn.getvch();
253 CScript& push_uint64(uint64 n)
255 if (n >= 1 && n <= 16)
257 push_back(n + (OP_1 - 1));
262 *this << bn.getvch();
269 CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
270 CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
272 CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
275 CScript& operator+=(const CScript& b)
277 insert(end(), b.begin(), b.end());
281 friend CScript operator+(const CScript& a, const CScript& b)
289 //explicit CScript(char b) is not portable. Use 'signed char' or 'unsigned char'.
290 explicit CScript(signed char b) { operator<<(b); }
291 explicit CScript(short b) { operator<<(b); }
292 explicit CScript(int b) { operator<<(b); }
293 explicit CScript(long b) { operator<<(b); }
294 explicit CScript(int64 b) { operator<<(b); }
295 explicit CScript(unsigned char b) { operator<<(b); }
296 explicit CScript(unsigned int b) { operator<<(b); }
297 explicit CScript(unsigned short b) { operator<<(b); }
298 explicit CScript(unsigned long b) { operator<<(b); }
299 explicit CScript(uint64 b) { operator<<(b); }
301 explicit CScript(opcodetype b) { operator<<(b); }
302 explicit CScript(const uint256& b) { operator<<(b); }
303 explicit CScript(const CBigNum& b) { operator<<(b); }
304 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
307 //CScript& operator<<(char b) is not portable. Use 'signed char' or 'unsigned char'.
308 CScript& operator<<(signed char b) { return push_int64(b); }
309 CScript& operator<<(short b) { return push_int64(b); }
310 CScript& operator<<(int b) { return push_int64(b); }
311 CScript& operator<<(long b) { return push_int64(b); }
312 CScript& operator<<(int64 b) { return push_int64(b); }
313 CScript& operator<<(unsigned char b) { return push_uint64(b); }
314 CScript& operator<<(unsigned int b) { return push_uint64(b); }
315 CScript& operator<<(unsigned short b) { return push_uint64(b); }
316 CScript& operator<<(unsigned long b) { return push_uint64(b); }
317 CScript& operator<<(uint64 b) { return push_uint64(b); }
319 CScript& operator<<(opcodetype opcode)
321 if (opcode < 0 || opcode > 0xff)
322 throw std::runtime_error("CScript::operator<<() : invalid opcode");
323 insert(end(), (unsigned char)opcode);
327 CScript& operator<<(const uint160& b)
329 insert(end(), sizeof(b));
330 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
334 CScript& operator<<(const uint256& b)
336 insert(end(), sizeof(b));
337 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
341 CScript& operator<<(const CPubKey& key)
343 std::vector<unsigned char> vchKey = key.Raw();
344 return (*this) << vchKey;
347 CScript& operator<<(const CBigNum& b)
353 CScript& operator<<(const std::vector<unsigned char>& b)
355 if (b.size() < OP_PUSHDATA1)
357 insert(end(), (unsigned char)b.size());
359 else if (b.size() <= 0xff)
361 insert(end(), OP_PUSHDATA1);
362 insert(end(), (unsigned char)b.size());
364 else if (b.size() <= 0xffff)
366 insert(end(), OP_PUSHDATA2);
367 unsigned short nSize = b.size();
368 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
372 insert(end(), OP_PUSHDATA4);
373 unsigned int nSize = b.size();
374 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
376 insert(end(), b.begin(), b.end());
380 CScript& operator<<(const CScript& b)
382 // I'm not sure if this should push the script or concatenate scripts.
383 // If there's ever a use for pushing a script onto a script, delete this member fn
384 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
389 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
391 // Wrapper so it can be called with either iterator or const_iterator
392 const_iterator pc2 = pc;
393 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
394 pc = begin() + (pc2 - begin());
398 bool GetOp(iterator& pc, opcodetype& opcodeRet)
400 const_iterator pc2 = pc;
401 bool fRet = GetOp2(pc2, opcodeRet, NULL);
402 pc = begin() + (pc2 - begin());
406 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
408 return GetOp2(pc, opcodeRet, &vchRet);
411 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
413 return GetOp2(pc, opcodeRet, NULL);
416 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
418 opcodeRet = OP_INVALIDOPCODE;
427 unsigned int opcode = *pc++;
430 if (opcode <= OP_PUSHDATA4)
433 if (opcode < OP_PUSHDATA1)
437 else if (opcode == OP_PUSHDATA1)
443 else if (opcode == OP_PUSHDATA2)
448 memcpy(&nSize, &pc[0], 2);
451 else if (opcode == OP_PUSHDATA4)
455 memcpy(&nSize, &pc[0], 4);
458 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
461 pvchRet->assign(pc, pc + nSize);
465 opcodeRet = (opcodetype)opcode;
469 // Encode/decode small integers:
470 static int DecodeOP_N(opcodetype opcode)
474 assert(opcode >= OP_1 && opcode <= OP_16);
475 return (int)opcode - (int)(OP_1 - 1);
477 static opcodetype EncodeOP_N(int n)
479 assert(n >= 0 && n <= 16);
482 return (opcodetype)(OP_1+n-1);
485 int FindAndDelete(const CScript& b)
490 iterator pc = begin();
494 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
496 erase(pc, pc + b.size());
500 while (GetOp(pc, opcode));
503 int Find(opcodetype op) const
507 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
513 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
514 // as 20 sigops. With pay-to-script-hash, that changed:
515 // CHECKMULTISIGs serialized in scriptSigs are
516 // counted more accurately, assuming they are of the form
517 // ... OP_N CHECKMULTISIG ...
518 unsigned int GetSigOpCount(bool fAccurate) const;
520 // Accurately count sigOps, including sigOps in
521 // pay-to-script-hash transactions:
522 unsigned int GetSigOpCount(const CScript& scriptSig) const;
524 bool IsPayToScriptHash() const;
526 // Called by CTransaction::IsStandard
527 bool IsPushOnly() const
529 const_iterator pc = begin();
533 if (!GetOp(pc, opcode))
541 // Called by CTransaction::IsStandard.
542 bool HasCanonicalPushes() const;
544 void SetDestination(const CTxDestination& address);
545 void SetMultisig(int nRequired, const std::vector<CKey>& keys);
548 void PrintHex() const
550 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
553 std::string ToString() const
557 std::vector<unsigned char> vch;
558 const_iterator pc = begin();
563 if (!GetOp(pc, opcode, vch))
568 if (0 <= opcode && opcode <= OP_PUSHDATA4)
569 str += ValueString(vch);
571 str += GetOpName(opcode);
578 printf("%s\n", ToString().c_str());
581 CScriptID GetID() const
583 return CScriptID(Hash160(*this));
587 /** Compact serializer for scripts.
589 * It detects common cases and encodes them much more efficiently.
590 * 3 special cases are defined:
591 * * Pay to pubkey hash (encoded as 21 bytes)
592 * * Pay to script hash (encoded as 21 bytes)
593 * * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
595 * Other scripts up to 121 bytes require 1 byte + script length. Above
596 * that, scripts up to 16505 bytes require 2 bytes + script length.
598 class CScriptCompressor
601 // make this static for now (there are only 6 special scripts defined)
602 // this can potentially be extended together with a new nVersion for
603 // transactions, in which case this value becomes dependent on nVersion
604 // and nHeight of the enclosing transaction.
605 static const unsigned int nSpecialScripts = 6;
609 // These check for scripts for which a special case with a shorter encoding is defined.
610 // They are implemented separately from the CScript test, as these test for exact byte
611 // sequence correspondences, and are more strict. For example, IsToPubKey also verifies
612 // whether the public key is valid (as invalid ones cannot be represented in compressed
614 bool IsToKeyID(CKeyID &hash) const;
615 bool IsToScriptID(CScriptID &hash) const;
616 bool IsToPubKey(std::vector<unsigned char> &pubkey) const;
618 bool Compress(std::vector<unsigned char> &out) const;
619 unsigned int GetSpecialSize(unsigned int nSize) const;
620 bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
622 CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
624 unsigned int GetSerializeSize(int nType, int nVersion) const {
625 std::vector<unsigned char> compr;
628 unsigned int nSize = script.size() + nSpecialScripts;
629 return script.size() + VARINT(nSize).GetSerializeSize(nType, nVersion);
632 template<typename Stream>
633 void Serialize(Stream &s, int nType, int nVersion) const {
634 std::vector<unsigned char> compr;
635 if (Compress(compr)) {
636 s << CFlatData(&compr[0], &compr[compr.size()]);
639 unsigned int nSize = script.size() + nSpecialScripts;
641 s << CFlatData(&script[0], &script[script.size()]);
644 template<typename Stream>
645 void Unserialize(Stream &s, int nType, int nVersion) {
648 if (nSize < nSpecialScripts) {
649 std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
650 s >> REF(CFlatData(&vch[0], &vch[vch.size()]));
651 Decompress(nSize, vch);
654 nSize -= nSpecialScripts;
655 script.resize(nSize);
656 s >> REF(CFlatData(&script[0], &script[script.size()]));
660 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey);
661 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig);
663 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, bool fStrictEncodings, int nHashType);
664 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
665 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
666 bool IsStandard(const CScript& scriptPubKey);
667 bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
668 bool IsMine(const CKeyStore& keystore, const CTxDestination &dest);
670 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
671 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
672 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
673 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
674 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
675 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
676 bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType);
677 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType);
679 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
680 // combine them intelligently and return the result.
681 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);