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 /** Signature hash types/flags */
26 SIGHASH_ANYONECANPAY = 0x80,
33 // 'standard' transaction types:
40 class CNoDestination {
42 friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
43 friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
46 /** A txout script template with a specific destination. It is either:
47 * * CNoDestination: no destination set
48 * * CKeyID: TX_PUBKEYHASH destination
49 * * CScriptID: TX_SCRIPTHASH destination
50 * A CTxDestination is the internal data type encoded in a CBitcoinAddress
52 typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
54 const char* GetTxnOutputType(txnouttype t);
99 OP_FROMALTSTACK = 0x6c,
131 OP_EQUALVERIFY = 0x88,
156 OP_NUMEQUALVERIFY = 0x9d,
157 OP_NUMNOTEQUAL = 0x9e,
159 OP_GREATERTHAN = 0xa0,
160 OP_LESSTHANOREQUAL = 0xa1,
161 OP_GREATERTHANOREQUAL = 0xa2,
173 OP_CODESEPARATOR = 0xab,
175 OP_CHECKSIGVERIFY = 0xad,
176 OP_CHECKMULTISIG = 0xae,
177 OP_CHECKMULTISIGVERIFY = 0xaf,
193 // template matching params
194 OP_SMALLINTEGER = 0xfa,
196 OP_PUBKEYHASH = 0xfd,
199 OP_INVALIDOPCODE = 0xff,
202 const char* GetOpName(opcodetype opcode);
206 inline std::string ValueString(const std::vector<unsigned char>& vch)
209 return strprintf("%d", CBigNum(vch).getint());
214 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
217 BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
221 str += ValueString(vch);
233 /** Serialized script, used inside transaction inputs and outputs */
234 class CScript : public std::vector<unsigned char>
237 CScript& push_int64(int64 n)
239 if (n == -1 || (n >= 1 && n <= 16))
241 push_back(n + (OP_1 - 1));
246 *this << bn.getvch();
251 CScript& push_uint64(uint64 n)
253 if (n >= 1 && n <= 16)
255 push_back(n + (OP_1 - 1));
260 *this << bn.getvch();
267 CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
268 CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
270 CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
273 CScript& operator+=(const CScript& b)
275 insert(end(), b.begin(), b.end());
279 friend CScript operator+(const CScript& a, const CScript& b)
287 //explicit CScript(char b) is not portable. Use 'signed char' or 'unsigned char'.
288 explicit CScript(signed char b) { operator<<(b); }
289 explicit CScript(short b) { operator<<(b); }
290 explicit CScript(int b) { operator<<(b); }
291 explicit CScript(long b) { operator<<(b); }
292 explicit CScript(int64 b) { operator<<(b); }
293 explicit CScript(unsigned char b) { operator<<(b); }
294 explicit CScript(unsigned int b) { operator<<(b); }
295 explicit CScript(unsigned short b) { operator<<(b); }
296 explicit CScript(unsigned long b) { operator<<(b); }
297 explicit CScript(uint64 b) { operator<<(b); }
299 explicit CScript(opcodetype b) { operator<<(b); }
300 explicit CScript(const uint256& b) { operator<<(b); }
301 explicit CScript(const CBigNum& b) { operator<<(b); }
302 explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
305 //CScript& operator<<(char b) is not portable. Use 'signed char' or 'unsigned char'.
306 CScript& operator<<(signed char b) { return push_int64(b); }
307 CScript& operator<<(short b) { return push_int64(b); }
308 CScript& operator<<(int b) { return push_int64(b); }
309 CScript& operator<<(long b) { return push_int64(b); }
310 CScript& operator<<(int64 b) { return push_int64(b); }
311 CScript& operator<<(unsigned char b) { return push_uint64(b); }
312 CScript& operator<<(unsigned int b) { return push_uint64(b); }
313 CScript& operator<<(unsigned short b) { return push_uint64(b); }
314 CScript& operator<<(unsigned long b) { return push_uint64(b); }
315 CScript& operator<<(uint64 b) { return push_uint64(b); }
317 CScript& operator<<(opcodetype opcode)
319 if (opcode < 0 || opcode > 0xff)
320 throw std::runtime_error("CScript::operator<<() : invalid opcode");
321 insert(end(), (unsigned char)opcode);
325 CScript& operator<<(const uint160& b)
327 insert(end(), sizeof(b));
328 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
332 CScript& operator<<(const uint256& b)
334 insert(end(), sizeof(b));
335 insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
339 CScript& operator<<(const CPubKey& key)
341 std::vector<unsigned char> vchKey = key.Raw();
342 return (*this) << vchKey;
345 CScript& operator<<(const CBigNum& b)
351 CScript& operator<<(const std::vector<unsigned char>& b)
353 if (b.size() < OP_PUSHDATA1)
355 insert(end(), (unsigned char)b.size());
357 else if (b.size() <= 0xff)
359 insert(end(), OP_PUSHDATA1);
360 insert(end(), (unsigned char)b.size());
362 else if (b.size() <= 0xffff)
364 insert(end(), OP_PUSHDATA2);
365 unsigned short nSize = b.size();
366 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
370 insert(end(), OP_PUSHDATA4);
371 unsigned int nSize = b.size();
372 insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
374 insert(end(), b.begin(), b.end());
378 CScript& operator<<(const CScript& b)
380 // I'm not sure if this should push the script or concatenate scripts.
381 // If there's ever a use for pushing a script onto a script, delete this member fn
382 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
387 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
389 // Wrapper so it can be called with either iterator or const_iterator
390 const_iterator pc2 = pc;
391 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
392 pc = begin() + (pc2 - begin());
396 bool GetOp(iterator& pc, opcodetype& opcodeRet)
398 const_iterator pc2 = pc;
399 bool fRet = GetOp2(pc2, opcodeRet, NULL);
400 pc = begin() + (pc2 - begin());
404 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
406 return GetOp2(pc, opcodeRet, &vchRet);
409 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
411 return GetOp2(pc, opcodeRet, NULL);
414 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
416 opcodeRet = OP_INVALIDOPCODE;
425 unsigned int opcode = *pc++;
428 if (opcode <= OP_PUSHDATA4)
431 if (opcode < OP_PUSHDATA1)
435 else if (opcode == OP_PUSHDATA1)
441 else if (opcode == OP_PUSHDATA2)
446 memcpy(&nSize, &pc[0], 2);
449 else if (opcode == OP_PUSHDATA4)
453 memcpy(&nSize, &pc[0], 4);
456 if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
459 pvchRet->assign(pc, pc + nSize);
463 opcodeRet = (opcodetype)opcode;
467 // Encode/decode small integers:
468 static int DecodeOP_N(opcodetype opcode)
472 assert(opcode >= OP_1 && opcode <= OP_16);
473 return (int)opcode - (int)(OP_1 - 1);
475 static opcodetype EncodeOP_N(int n)
477 assert(n >= 0 && n <= 16);
480 return (opcodetype)(OP_1+n-1);
483 int FindAndDelete(const CScript& b)
488 iterator pc = begin();
492 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
494 erase(pc, pc + b.size());
498 while (GetOp(pc, opcode));
501 int Find(opcodetype op) const
505 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
511 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
512 // as 20 sigops. With pay-to-script-hash, that changed:
513 // CHECKMULTISIGs serialized in scriptSigs are
514 // counted more accurately, assuming they are of the form
515 // ... OP_N CHECKMULTISIG ...
516 unsigned int GetSigOpCount(bool fAccurate) const;
518 // Accurately count sigOps, including sigOps in
519 // pay-to-script-hash transactions:
520 unsigned int GetSigOpCount(const CScript& scriptSig) const;
522 bool IsPayToScriptHash() const;
524 // Called by CTransaction::IsStandard
525 bool IsPushOnly() const
527 const_iterator pc = begin();
531 if (!GetOp(pc, opcode))
540 void SetDestination(const CTxDestination& address);
541 void SetMultisig(int nRequired, const std::vector<CKey>& keys);
544 void PrintHex() const
546 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
549 std::string ToString() const
553 std::vector<unsigned char> vch;
554 const_iterator pc = begin();
559 if (!GetOp(pc, opcode, vch))
564 if (0 <= opcode && opcode <= OP_PUSHDATA4)
565 str += ValueString(vch);
567 str += GetOpName(opcode);
574 printf("%s\n", ToString().c_str());
577 CScriptID GetID() const
579 return CScriptID(Hash160(*this));
583 /** Compact serializer for scripts.
585 * It detects common cases and encodes them much more efficiently.
586 * 3 special cases are defined:
587 * * Pay to pubkey hash (encoded as 21 bytes)
588 * * Pay to script hash (encoded as 21 bytes)
589 * * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
591 * Other scripts up to 121 bytes require 1 byte + script length. Above
592 * that, scripts up to 16505 bytes require 2 bytes + script length.
594 class CScriptCompressor
597 // make this static for now (there are only 6 special scripts defined)
598 // this can potentially be extended together with a new nVersion for
599 // transactions, in which case this value becomes dependent on nVersion
600 // and nHeight of the enclosing transaction.
601 static const unsigned int nSpecialScripts = 6;
605 // These check for scripts for which a special case with a shorter encoding is defined.
606 // They are implemented separately from the CScript test, as these test for exact byte
607 // sequence correspondences, and are more strict. For example, IsToPubKey also verifies
608 // whether the public key is valid (as invalid ones cannot be represented in compressed
610 bool IsToKeyID(CKeyID &hash) const;
611 bool IsToScriptID(CScriptID &hash) const;
612 bool IsToPubKey(std::vector<unsigned char> &pubkey) const;
614 bool Compress(std::vector<unsigned char> &out) const;
615 unsigned int GetSpecialSize(unsigned int nSize) const;
616 bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
618 CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
620 unsigned int GetSerializeSize(int nType, int nVersion) const {
621 std::vector<unsigned char> compr;
624 unsigned int nSize = script.size() + nSpecialScripts;
625 return script.size() + VARINT(nSize).GetSerializeSize(nType, nVersion);
628 template<typename Stream>
629 void Serialize(Stream &s, int nType, int nVersion) const {
630 std::vector<unsigned char> compr;
631 if (Compress(compr)) {
632 s << CFlatData(&compr[0], &compr[compr.size()]);
635 unsigned int nSize = script.size() + nSpecialScripts;
637 s << CFlatData(&script[0], &script[script.size()]);
640 template<typename Stream>
641 void Unserialize(Stream &s, int nType, int nVersion) {
644 if (nSize < nSpecialScripts) {
645 std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
646 s >> REF(CFlatData(&vch[0], &vch[vch.size()]));
647 Decompress(nSize, vch);
650 nSize -= nSpecialScripts;
651 script.resize(nSize);
652 s >> REF(CFlatData(&script[0], &script[script.size()]));
656 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey);
657 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig);
659 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, bool fStrictEncodings, int nHashType);
660 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
661 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
662 bool IsStandard(const CScript& scriptPubKey);
663 bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
664 bool IsMine(const CKeyStore& keystore, const CTxDestination &dest);
665 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
666 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
667 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
668 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
669 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
670 bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType);
671 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType);
673 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
674 // combine them intelligently and return the result.
675 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);