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:
43 class CNoDestination {
45 friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
46 friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
49 /** A txout script template with a specific destination. It is either:
50 * * CNoDestination: no destination set
51 * * CKeyID: TX_PUBKEYHASH destination
52 * * CScriptID: TX_SCRIPTHASH destination
53 * A CTxDestination is the internal data type encoded in a CBitcoinAddress
55 typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
57 const char* GetTxnOutputType(txnouttype t);
101 OP_TOALTSTACK = 0x6b,
102 OP_FROMALTSTACK = 0x6c,
134 OP_EQUALVERIFY = 0x88,
159 OP_NUMEQUALVERIFY = 0x9d,
160 OP_NUMNOTEQUAL = 0x9e,
162 OP_GREATERTHAN = 0xa0,
163 OP_LESSTHANOREQUAL = 0xa1,
164 OP_GREATERTHANOREQUAL = 0xa2,
176 OP_CODESEPARATOR = 0xab,
178 OP_CHECKSIGVERIFY = 0xad,
179 OP_CHECKMULTISIG = 0xae,
180 OP_CHECKMULTISIGVERIFY = 0xaf,
196 // template matching params
198 OP_SMALLINTEGER = 0xfa,
200 OP_PUBKEYHASH = 0xfd,
203 OP_INVALIDOPCODE = 0xff,
206 const char* GetOpName(opcodetype opcode);
210 inline std::string ValueString(const std::vector<unsigned char>& vch)
213 return strprintf("%d", CBigNum(vch).getint());
218 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
221 BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
225 str += ValueString(vch);
237 /** Serialized script, used inside transaction inputs and outputs */
238 class CScript : public std::vector<unsigned char>
241 CScript& push_int64(int64 n)
243 if (n == -1 || (n >= 1 && n <= 16))
245 push_back(n + (OP_1 - 1));
250 *this << bn.getvch();
255 CScript& push_uint64(uint64 n)
257 if (n >= 1 && n <= 16)
259 push_back(n + (OP_1 - 1));
264 *this << bn.getvch();
271 CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
272 CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
274 CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
277 CScript& operator+=(const CScript& b)
279 insert(end(), b.begin(), b.end());
283 friend CScript operator+(const CScript& a, const CScript& b)
291 //explicit CScript(char b) is not portable. Use 'signed char' or 'unsigned char'.
292 explicit CScript(signed char b) { operator<<(b); }
293 explicit CScript(short b) { operator<<(b); }
294 explicit CScript(int b) { operator<<(b); }
295 explicit CScript(long b) { operator<<(b); }
296 explicit CScript(int64 b) { operator<<(b); }
297 explicit CScript(unsigned char b) { operator<<(b); }
298 explicit CScript(unsigned int b) { operator<<(b); }
299 explicit CScript(unsigned short b) { operator<<(b); }
300 explicit CScript(unsigned long b) { operator<<(b); }
301 explicit CScript(uint64 b) { operator<<(b); }
303 explicit CScript(opcodetype b) { operator<<(b); }
304 explicit CScript(const uint256& b) { operator<<(b); }
305 explicit CScript(const CBigNum& b) { operator<<(b); }
306 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
309 //CScript& operator<<(char b) is not portable. Use 'signed char' or 'unsigned char'.
310 CScript& operator<<(signed char b) { return push_int64(b); }
311 CScript& operator<<(short b) { return push_int64(b); }
312 CScript& operator<<(int b) { return push_int64(b); }
313 CScript& operator<<(long b) { return push_int64(b); }
314 CScript& operator<<(int64 b) { return push_int64(b); }
315 CScript& operator<<(unsigned char b) { return push_uint64(b); }
316 CScript& operator<<(unsigned int b) { return push_uint64(b); }
317 CScript& operator<<(unsigned short b) { return push_uint64(b); }
318 CScript& operator<<(unsigned long b) { return push_uint64(b); }
319 CScript& operator<<(uint64 b) { return push_uint64(b); }
321 CScript& operator<<(opcodetype opcode)
323 if (opcode < 0 || opcode > 0xff)
324 throw std::runtime_error("CScript::operator<<() : invalid opcode");
325 insert(end(), (unsigned char)opcode);
329 CScript& operator<<(const uint160& b)
331 insert(end(), sizeof(b));
332 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
336 CScript& operator<<(const uint256& b)
338 insert(end(), sizeof(b));
339 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
343 CScript& operator<<(const CPubKey& key)
345 std::vector<unsigned char> vchKey = key.Raw();
346 return (*this) << vchKey;
349 CScript& operator<<(const CBigNum& b)
355 CScript& operator<<(const std::vector<unsigned char>& b)
357 if (b.size() < OP_PUSHDATA1)
359 insert(end(), (unsigned char)b.size());
361 else if (b.size() <= 0xff)
363 insert(end(), OP_PUSHDATA1);
364 insert(end(), (unsigned char)b.size());
366 else if (b.size() <= 0xffff)
368 insert(end(), OP_PUSHDATA2);
369 unsigned short nSize = b.size();
370 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
374 insert(end(), OP_PUSHDATA4);
375 unsigned int nSize = b.size();
376 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
378 insert(end(), b.begin(), b.end());
382 CScript& operator<<(const CScript& b)
384 // I'm not sure if this should push the script or concatenate scripts.
385 // If there's ever a use for pushing a script onto a script, delete this member fn
386 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
391 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
393 // Wrapper so it can be called with either iterator or const_iterator
394 const_iterator pc2 = pc;
395 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
396 pc = begin() + (pc2 - begin());
400 bool GetOp(iterator& pc, opcodetype& opcodeRet)
402 const_iterator pc2 = pc;
403 bool fRet = GetOp2(pc2, opcodeRet, NULL);
404 pc = begin() + (pc2 - begin());
408 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
410 return GetOp2(pc, opcodeRet, &vchRet);
413 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
415 return GetOp2(pc, opcodeRet, NULL);
418 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
420 opcodeRet = OP_INVALIDOPCODE;
429 unsigned int opcode = *pc++;
432 if (opcode <= OP_PUSHDATA4)
435 if (opcode < OP_PUSHDATA1)
439 else if (opcode == OP_PUSHDATA1)
445 else if (opcode == OP_PUSHDATA2)
450 memcpy(&nSize, &pc[0], 2);
453 else if (opcode == OP_PUSHDATA4)
457 memcpy(&nSize, &pc[0], 4);
460 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
463 pvchRet->assign(pc, pc + nSize);
467 opcodeRet = (opcodetype)opcode;
471 // Encode/decode small integers:
472 static int DecodeOP_N(opcodetype opcode)
476 assert(opcode >= OP_1 && opcode <= OP_16);
477 return (int)opcode - (int)(OP_1 - 1);
479 static opcodetype EncodeOP_N(int n)
481 assert(n >= 0 && n <= 16);
484 return (opcodetype)(OP_1+n-1);
487 int FindAndDelete(const CScript& b)
492 iterator pc = begin();
496 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
498 erase(pc, pc + b.size());
502 while (GetOp(pc, opcode));
505 int Find(opcodetype op) const
509 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
515 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
516 // as 20 sigops. With pay-to-script-hash, that changed:
517 // CHECKMULTISIGs serialized in scriptSigs are
518 // counted more accurately, assuming they are of the form
519 // ... OP_N CHECKMULTISIG ...
520 unsigned int GetSigOpCount(bool fAccurate) const;
522 // Accurately count sigOps, including sigOps in
523 // pay-to-script-hash transactions:
524 unsigned int GetSigOpCount(const CScript& scriptSig) const;
526 bool IsPayToScriptHash() const;
528 // Called by CTransaction::IsStandard
529 bool IsPushOnly() const
531 const_iterator pc = begin();
535 if (!GetOp(pc, opcode))
543 // Called by CTransaction::IsStandard.
544 bool HasCanonicalPushes() const;
546 void SetDestination(const CTxDestination& address);
547 void SetMultisig(int nRequired, const std::vector<CKey>& keys);
550 void PrintHex() const
552 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
555 std::string ToString() const
559 std::vector<unsigned char> vch;
560 const_iterator pc = begin();
565 if (!GetOp(pc, opcode, vch))
570 if (0 <= opcode && opcode <= OP_PUSHDATA4)
571 str += ValueString(vch);
573 str += GetOpName(opcode);
580 printf("%s\n", ToString().c_str());
583 CScriptID GetID() const
585 return CScriptID(Hash160(*this));
589 /** Compact serializer for scripts.
591 * It detects common cases and encodes them much more efficiently.
592 * 3 special cases are defined:
593 * * Pay to pubkey hash (encoded as 21 bytes)
594 * * Pay to script hash (encoded as 21 bytes)
595 * * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
597 * Other scripts up to 121 bytes require 1 byte + script length. Above
598 * that, scripts up to 16505 bytes require 2 bytes + script length.
600 class CScriptCompressor
603 // make this static for now (there are only 6 special scripts defined)
604 // this can potentially be extended together with a new nVersion for
605 // transactions, in which case this value becomes dependent on nVersion
606 // and nHeight of the enclosing transaction.
607 static const unsigned int nSpecialScripts = 6;
611 // These check for scripts for which a special case with a shorter encoding is defined.
612 // They are implemented separately from the CScript test, as these test for exact byte
613 // sequence correspondences, and are more strict. For example, IsToPubKey also verifies
614 // whether the public key is valid (as invalid ones cannot be represented in compressed
616 bool IsToKeyID(CKeyID &hash) const;
617 bool IsToScriptID(CScriptID &hash) const;
618 bool IsToPubKey(std::vector<unsigned char> &pubkey) const;
620 bool Compress(std::vector<unsigned char> &out) const;
621 unsigned int GetSpecialSize(unsigned int nSize) const;
622 bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
624 CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
626 unsigned int GetSerializeSize(int nType, int nVersion) const {
627 std::vector<unsigned char> compr;
630 unsigned int nSize = script.size() + nSpecialScripts;
631 return script.size() + VARINT(nSize).GetSerializeSize(nType, nVersion);
634 template<typename Stream>
635 void Serialize(Stream &s, int nType, int nVersion) const {
636 std::vector<unsigned char> compr;
637 if (Compress(compr)) {
638 s << CFlatData(&compr[0], &compr[compr.size()]);
641 unsigned int nSize = script.size() + nSpecialScripts;
643 s << CFlatData(&script[0], &script[script.size()]);
646 template<typename Stream>
647 void Unserialize(Stream &s, int nType, int nVersion) {
650 if (nSize < nSpecialScripts) {
651 std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
652 s >> REF(CFlatData(&vch[0], &vch[vch.size()]));
653 Decompress(nSize, vch);
656 nSize -= nSpecialScripts;
657 script.resize(nSize);
658 s >> REF(CFlatData(&script[0], &script[script.size()]));
662 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey);
663 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig);
665 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
667 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, bool fStrictEncodings, int nHashType);
668 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
669 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
670 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
671 bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
672 bool IsMine(const CKeyStore& keystore, const CTxDestination &dest);
674 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
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,
680 bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType);
681 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType);
683 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
684 // combine them intelligently and return the result.
685 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);