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<uint8_t> valtype;
20 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
22 /** IsMine() return codes */
28 MINE_ALL = MINE_WATCH_ONLY | MINE_SPENDABLE
31 typedef uint8_t isminefilter;
33 /** Signature hash types/flags */
39 SIGHASH_ANYONECANPAY = 0x80
42 /** Script verification flags */
45 SCRIPT_VERIFY_NONE = 0,
46 SCRIPT_VERIFY_P2SH = (1U << 0), // evaluate P2SH (BIP16) subscripts
47 SCRIPT_VERIFY_STRICTENC = (1U << 1), // enforce strict conformance to DER and SEC2 for signatures and pubkeys
48 SCRIPT_VERIFY_LOW_S = (1U << 2), // enforce low S values in signatures (depends on STRICTENC)
49 SCRIPT_VERIFY_NOCACHE = (1U << 3), // do not store results in signature cache (but do query it)
50 SCRIPT_VERIFY_NULLDUMMY = (1U << 4) // verify dummy stack item consumed by CHECKMULTISIG is of zero-length
53 // Strict verification:
55 // * force DER encoding;
57 // * ensure that CHECKMULTISIG dummy argument is null.
58 static const unsigned int STRICT_FORMAT_FLAGS = SCRIPT_VERIFY_STRICTENC | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_NULLDUMMY;
60 // Mandatory script verification flags that all new blocks must comply with for
61 // them to be valid. (but old blocks may not comply with) Currently just P2SH,
62 // but in the future other flags may be added, such as a soft-fork to enforce
63 // strict DER encoding.
65 // Failing one of these tests may trigger a DoS ban - see ConnectInputs() for
67 static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH;
69 // Standard script verification flags that standard transactions will comply
70 // with. However scripts violating these flags may still be present in valid
71 // blocks and we must accept those blocks.
72 static const unsigned int STRICT_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS | STRICT_FORMAT_FLAGS;
77 // 'standard' transaction types:
86 const char* GetTxnOutputType(txnouttype t);
130 OP_TOALTSTACK = 0x6b,
131 OP_FROMALTSTACK = 0x6c,
163 OP_EQUALVERIFY = 0x88,
188 OP_NUMEQUALVERIFY = 0x9d,
189 OP_NUMNOTEQUAL = 0x9e,
191 OP_GREATERTHAN = 0xa0,
192 OP_LESSTHANOREQUAL = 0xa1,
193 OP_GREATERTHANOREQUAL = 0xa2,
205 OP_CODESEPARATOR = 0xab,
207 OP_CHECKSIGVERIFY = 0xad,
208 OP_CHECKMULTISIG = 0xae,
209 OP_CHECKMULTISIGVERIFY = 0xaf,
225 // template matching params
227 OP_SMALLINTEGER = 0xfa,
229 OP_PUBKEYHASH = 0xfd,
232 OP_INVALIDOPCODE = 0xff
235 const char* GetOpName(opcodetype opcode);
237 inline std::string ValueString(const std::vector<unsigned char>& vch)
240 return strprintf("%d", CBigNum(vch).getint32());
245 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
248 BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
252 str += ValueString(vch);
257 /** Serialized script, used inside transaction inputs and outputs */
258 class CScript : public std::vector<uint8_t>
261 CScript& push_int64(int64_t n)
263 if (n == -1 || (n >= 1 && n <= 16))
265 push_back((uint8_t)n + (OP_1 - 1));
270 *this << bn.getvch();
275 CScript& push_uint64(uint64_t n)
277 if (n >= 1 && n <= 16)
279 push_back((uint8_t)n + (OP_1 - 1));
284 *this << bn.getvch();
291 CScript(const CScript& b) : std::vector<uint8_t>(b.begin(), b.end()) { }
292 CScript(const_iterator pbegin, const_iterator pend) : std::vector<uint8_t>(pbegin, pend) { }
294 CScript(const uint8_t* pbegin, const uint8_t* pend) : std::vector<uint8_t>(pbegin, pend) { }
297 CScript& operator+=(const CScript& b)
299 insert(end(), b.begin(), b.end());
303 friend CScript operator+(const CScript& a, const CScript& b)
310 explicit CScript(int8_t b) { operator<<(b); }
311 explicit CScript(int16_t b) { operator<<(b); }
312 explicit CScript(int32_t b) { operator<<(b); }
313 explicit CScript(int64_t b) { operator<<(b); }
315 explicit CScript(uint8_t b) { operator<<(b); }
316 explicit CScript(uint16_t b) { operator<<(b); }
317 explicit CScript(uint32_t b) { operator<<(b); }
318 explicit CScript(uint64_t b) { operator<<(b); }
320 explicit CScript(opcodetype b) { operator<<(b); }
321 explicit CScript(const uint256& b) { operator<<(b); }
322 explicit CScript(const CBigNum& b) { operator<<(b); }
323 explicit CScript(const std::vector<uint8_t>& b) { operator<<(b); }
325 CScript& operator<<(int8_t b) { return push_int64(b); }
326 CScript& operator<<(int16_t b) { return push_int64(b); }
327 CScript& operator<<(int32_t b) { return push_int64(b); }
328 CScript& operator<<(int64_t b) { return push_int64(b); }
330 CScript& operator<<(uint8_t b) { return push_uint64(b); }
331 CScript& operator<<(uint16_t b) { return push_uint64(b); }
332 CScript& operator<<(uint32_t b) { return push_uint64(b); }
333 CScript& operator<<(uint64_t b) { return push_uint64(b); }
335 CScript& operator<<(opcodetype opcode)
337 if (opcode < 0 || opcode > 0xff)
338 throw std::runtime_error("CScript::operator<<() : invalid opcode");
339 insert(end(), (uint8_t)opcode);
343 CScript& operator<<(const uint160& b)
345 insert(end(), sizeof(b));
346 insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
350 CScript& operator<<(const uint256& b)
352 insert(end(), sizeof(b));
353 insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
357 CScript& operator<<(const CPubKey& key)
359 std::vector<uint8_t> vchKey = key.Raw();
360 return (*this) << vchKey;
363 CScript& operator<<(const CBigNum& b)
369 CScript& operator<<(const std::vector<uint8_t>& b)
371 if (b.size() < OP_PUSHDATA1)
373 insert(end(), (uint8_t)b.size());
375 else if (b.size() <= 0xff)
377 insert(end(), OP_PUSHDATA1);
378 insert(end(), (uint8_t)b.size());
380 else if (b.size() <= 0xffff)
382 insert(end(), OP_PUSHDATA2);
383 uint16_t nSize = (uint16_t) b.size();
384 insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
388 insert(end(), OP_PUSHDATA4);
389 uint32_t nSize = (uint32_t) b.size();
390 insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
392 insert(end(), b.begin(), b.end());
396 CScript& operator<<(const CScript& b)
398 // I'm not sure if this should push the script or concatenate scripts.
399 // If there's ever a use for pushing a script onto a script, delete this member fn
400 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
405 bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet)
407 // Wrapper so it can be called with either iterator or const_iterator
408 const_iterator pc2 = pc;
409 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
410 pc = begin() + (pc2 - begin());
414 bool GetOp(iterator& pc, opcodetype& opcodeRet)
416 const_iterator pc2 = pc;
417 bool fRet = GetOp2(pc2, opcodeRet, NULL);
418 pc = begin() + (pc2 - begin());
422 bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet) const
424 return GetOp2(pc, opcodeRet, &vchRet);
427 bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
429 return GetOp2(pc, opcodeRet, NULL);
432 bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>* pvchRet) const
434 opcodeRet = OP_INVALIDOPCODE;
443 uint32_t opcode = *pc++;
446 if (opcode <= OP_PUSHDATA4)
448 uint32_t nSize = OP_0;
449 if (opcode < OP_PUSHDATA1)
453 else if (opcode == OP_PUSHDATA1)
459 else if (opcode == OP_PUSHDATA2)
463 memcpy(&nSize, &pc[0], 2);
466 else if (opcode == OP_PUSHDATA4)
470 memcpy(&nSize, &pc[0], 4);
473 if (end() - pc < 0 || (uint32_t)(end() - pc) < nSize)
476 pvchRet->assign(pc, pc + nSize);
480 opcodeRet = (opcodetype)opcode;
484 // Encode/decode small integers:
485 static int DecodeOP_N(opcodetype opcode)
489 assert(opcode >= OP_1 && opcode <= OP_16);
490 return (opcode - (OP_1 - 1));
492 static opcodetype EncodeOP_N(int n)
494 assert(n >= 0 && n <= 16);
497 return (opcodetype)(OP_1+n-1);
500 int FindAndDelete(const CScript& b)
505 iterator pc = begin();
509 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
511 erase(pc, pc + b.size());
515 while (GetOp(pc, opcode));
518 int Find(opcodetype op) const
522 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
528 // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
529 // as 20 sigops. With pay-to-script-hash, that changed:
530 // CHECKMULTISIGs serialized in scriptSigs are
531 // counted more accurately, assuming they are of the form
532 // ... OP_N CHECKMULTISIG ...
533 unsigned int GetSigOpCount(bool fAccurate) const;
535 // Accurately count sigOps, including sigOps in
536 // pay-to-script-hash transactions:
537 unsigned int GetSigOpCount(const CScript& scriptSig) const;
539 bool IsPayToScriptHash() const;
541 // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
542 bool IsPushOnly() const
544 const_iterator pc = begin();
548 if (!GetOp(pc, opcode))
556 // Called by CTransaction::IsStandard.
557 bool HasCanonicalPushes() const;
559 void SetDestination(const CTxDestination& address);
560 void SetDestination(const CPubKey& R, CPubKey& pubKeyVariant);
561 void SetMultisig(int nRequired, const std::vector<CKey>& keys);
564 void PrintHex() const
566 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
569 std::string ToString(bool fShort=false) const
573 std::vector<uint8_t> vch;
574 const_iterator pc = begin();
579 if (!GetOp(pc, opcode, vch))
584 if (0 <= opcode && opcode <= OP_PUSHDATA4)
585 str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
587 str += GetOpName(opcode);
594 printf("%s\n", ToString().c_str());
597 CScriptID GetID() const
599 return CScriptID(Hash160(*this));
603 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey, unsigned int flags);
604 bool IsDERSignature(const valtype &vchSig, bool fWithHashType=false, bool fCheckLow=false);
605 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig, unsigned int flags);
607 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
608 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
609 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
610 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
611 isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
612 isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest);
613 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
614 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
615 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
616 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
617 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
618 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
620 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
621 // combine them intelligently and return the result.
622 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);