]> Git Repo - VerusCoin.git/blob - src/script.h
Merge branch 'loaderror' of git://github.com/sipa/bitcoin
[VerusCoin.git] / src / script.h
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
7
8 #include <string>
9 #include <vector>
10
11 #include <boost/foreach.hpp>
12 #include <boost/variant.hpp>
13
14 #include "keystore.h"
15 #include "bignum.h"
16
17 class CCoins;
18 class CTransaction;
19
20 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
21
22 /** Signature hash types/flags */
23 enum
24 {
25     SIGHASH_ALL = 1,
26     SIGHASH_NONE = 2,
27     SIGHASH_SINGLE = 3,
28     SIGHASH_ANYONECANPAY = 0x80,
29 };
30
31 /** Script verification flags */
32 enum
33 {
34     SCRIPT_VERIFY_NONE      = 0,
35     SCRIPT_VERIFY_P2SH      = (1U << 0),
36     SCRIPT_VERIFY_STRICTENC = (1U << 1),
37     SCRIPT_VERIFY_NOCACHE   = (1U << 2),
38 };
39
40 enum txnouttype
41 {
42     TX_NONSTANDARD,
43     // 'standard' transaction types:
44     TX_PUBKEY,
45     TX_PUBKEYHASH,
46     TX_SCRIPTHASH,
47     TX_MULTISIG,
48 };
49
50 class CNoDestination {
51 public:
52     friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
53     friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
54 };
55
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
61  */
62 typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
63
64 const char* GetTxnOutputType(txnouttype t);
65
66 /** Script opcodes */
67 enum opcodetype
68 {
69     // push value
70     OP_0 = 0x00,
71     OP_FALSE = OP_0,
72     OP_PUSHDATA1 = 0x4c,
73     OP_PUSHDATA2 = 0x4d,
74     OP_PUSHDATA4 = 0x4e,
75     OP_1NEGATE = 0x4f,
76     OP_RESERVED = 0x50,
77     OP_1 = 0x51,
78     OP_TRUE=OP_1,
79     OP_2 = 0x52,
80     OP_3 = 0x53,
81     OP_4 = 0x54,
82     OP_5 = 0x55,
83     OP_6 = 0x56,
84     OP_7 = 0x57,
85     OP_8 = 0x58,
86     OP_9 = 0x59,
87     OP_10 = 0x5a,
88     OP_11 = 0x5b,
89     OP_12 = 0x5c,
90     OP_13 = 0x5d,
91     OP_14 = 0x5e,
92     OP_15 = 0x5f,
93     OP_16 = 0x60,
94
95     // control
96     OP_NOP = 0x61,
97     OP_VER = 0x62,
98     OP_IF = 0x63,
99     OP_NOTIF = 0x64,
100     OP_VERIF = 0x65,
101     OP_VERNOTIF = 0x66,
102     OP_ELSE = 0x67,
103     OP_ENDIF = 0x68,
104     OP_VERIFY = 0x69,
105     OP_RETURN = 0x6a,
106
107     // stack ops
108     OP_TOALTSTACK = 0x6b,
109     OP_FROMALTSTACK = 0x6c,
110     OP_2DROP = 0x6d,
111     OP_2DUP = 0x6e,
112     OP_3DUP = 0x6f,
113     OP_2OVER = 0x70,
114     OP_2ROT = 0x71,
115     OP_2SWAP = 0x72,
116     OP_IFDUP = 0x73,
117     OP_DEPTH = 0x74,
118     OP_DROP = 0x75,
119     OP_DUP = 0x76,
120     OP_NIP = 0x77,
121     OP_OVER = 0x78,
122     OP_PICK = 0x79,
123     OP_ROLL = 0x7a,
124     OP_ROT = 0x7b,
125     OP_SWAP = 0x7c,
126     OP_TUCK = 0x7d,
127
128     // splice ops
129     OP_CAT = 0x7e,
130     OP_SUBSTR = 0x7f,
131     OP_LEFT = 0x80,
132     OP_RIGHT = 0x81,
133     OP_SIZE = 0x82,
134
135     // bit logic
136     OP_INVERT = 0x83,
137     OP_AND = 0x84,
138     OP_OR = 0x85,
139     OP_XOR = 0x86,
140     OP_EQUAL = 0x87,
141     OP_EQUALVERIFY = 0x88,
142     OP_RESERVED1 = 0x89,
143     OP_RESERVED2 = 0x8a,
144
145     // numeric
146     OP_1ADD = 0x8b,
147     OP_1SUB = 0x8c,
148     OP_2MUL = 0x8d,
149     OP_2DIV = 0x8e,
150     OP_NEGATE = 0x8f,
151     OP_ABS = 0x90,
152     OP_NOT = 0x91,
153     OP_0NOTEQUAL = 0x92,
154
155     OP_ADD = 0x93,
156     OP_SUB = 0x94,
157     OP_MUL = 0x95,
158     OP_DIV = 0x96,
159     OP_MOD = 0x97,
160     OP_LSHIFT = 0x98,
161     OP_RSHIFT = 0x99,
162
163     OP_BOOLAND = 0x9a,
164     OP_BOOLOR = 0x9b,
165     OP_NUMEQUAL = 0x9c,
166     OP_NUMEQUALVERIFY = 0x9d,
167     OP_NUMNOTEQUAL = 0x9e,
168     OP_LESSTHAN = 0x9f,
169     OP_GREATERTHAN = 0xa0,
170     OP_LESSTHANOREQUAL = 0xa1,
171     OP_GREATERTHANOREQUAL = 0xa2,
172     OP_MIN = 0xa3,
173     OP_MAX = 0xa4,
174
175     OP_WITHIN = 0xa5,
176
177     // crypto
178     OP_RIPEMD160 = 0xa6,
179     OP_SHA1 = 0xa7,
180     OP_SHA256 = 0xa8,
181     OP_HASH160 = 0xa9,
182     OP_HASH256 = 0xaa,
183     OP_CODESEPARATOR = 0xab,
184     OP_CHECKSIG = 0xac,
185     OP_CHECKSIGVERIFY = 0xad,
186     OP_CHECKMULTISIG = 0xae,
187     OP_CHECKMULTISIGVERIFY = 0xaf,
188
189     // expansion
190     OP_NOP1 = 0xb0,
191     OP_NOP2 = 0xb1,
192     OP_NOP3 = 0xb2,
193     OP_NOP4 = 0xb3,
194     OP_NOP5 = 0xb4,
195     OP_NOP6 = 0xb5,
196     OP_NOP7 = 0xb6,
197     OP_NOP8 = 0xb7,
198     OP_NOP9 = 0xb8,
199     OP_NOP10 = 0xb9,
200
201
202
203     // template matching params
204     OP_SMALLINTEGER = 0xfa,
205     OP_PUBKEYS = 0xfb,
206     OP_PUBKEYHASH = 0xfd,
207     OP_PUBKEY = 0xfe,
208
209     OP_INVALIDOPCODE = 0xff,
210 };
211
212 const char* GetOpName(opcodetype opcode);
213
214
215
216 inline std::string ValueString(const std::vector<unsigned char>& vch)
217 {
218     if (vch.size() <= 4)
219         return strprintf("%d", CBigNum(vch).getint());
220     else
221         return HexStr(vch);
222 }
223
224 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
225 {
226     std::string str;
227     BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
228     {
229         if (!str.empty())
230             str += " ";
231         str += ValueString(vch);
232     }
233     return str;
234 }
235
236
237
238
239
240
241
242
243 /** Serialized script, used inside transaction inputs and outputs */
244 class CScript : public std::vector<unsigned char>
245 {
246 protected:
247     CScript& push_int64(int64 n)
248     {
249         if (n == -1 || (n >= 1 && n <= 16))
250         {
251             push_back(n + (OP_1 - 1));
252         }
253         else
254         {
255             CBigNum bn(n);
256             *this << bn.getvch();
257         }
258         return *this;
259     }
260
261     CScript& push_uint64(uint64 n)
262     {
263         if (n >= 1 && n <= 16)
264         {
265             push_back(n + (OP_1 - 1));
266         }
267         else
268         {
269             CBigNum bn(n);
270             *this << bn.getvch();
271         }
272         return *this;
273     }
274
275 public:
276     CScript() { }
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) { }
279 #ifndef _MSC_VER
280     CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
281 #endif
282
283     CScript& operator+=(const CScript& b)
284     {
285         insert(end(), b.begin(), b.end());
286         return *this;
287     }
288
289     friend CScript operator+(const CScript& a, const CScript& b)
290     {
291         CScript ret = a;
292         ret += b;
293         return ret;
294     }
295
296
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); }
308
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); }
313
314
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); }
326
327     CScript& operator<<(opcodetype opcode)
328     {
329         if (opcode < 0 || opcode > 0xff)
330             throw std::runtime_error("CScript::operator<<() : invalid opcode");
331         insert(end(), (unsigned char)opcode);
332         return *this;
333     }
334
335     CScript& operator<<(const uint160& b)
336     {
337         insert(end(), sizeof(b));
338         insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
339         return *this;
340     }
341
342     CScript& operator<<(const uint256& b)
343     {
344         insert(end(), sizeof(b));
345         insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
346         return *this;
347     }
348
349     CScript& operator<<(const CPubKey& key)
350     {
351         std::vector<unsigned char> vchKey = key.Raw();
352         return (*this) << vchKey;
353     }
354
355     CScript& operator<<(const CBigNum& b)
356     {
357         *this << b.getvch();
358         return *this;
359     }
360
361     CScript& operator<<(const std::vector<unsigned char>& b)
362     {
363         if (b.size() < OP_PUSHDATA1)
364         {
365             insert(end(), (unsigned char)b.size());
366         }
367         else if (b.size() <= 0xff)
368         {
369             insert(end(), OP_PUSHDATA1);
370             insert(end(), (unsigned char)b.size());
371         }
372         else if (b.size() <= 0xffff)
373         {
374             insert(end(), OP_PUSHDATA2);
375             unsigned short nSize = b.size();
376             insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
377         }
378         else
379         {
380             insert(end(), OP_PUSHDATA4);
381             unsigned int nSize = b.size();
382             insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
383         }
384         insert(end(), b.begin(), b.end());
385         return *this;
386     }
387
388     CScript& operator<<(const CScript& b)
389     {
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!");
393         return *this;
394     }
395
396
397     bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
398     {
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());
403          return fRet;
404     }
405
406     bool GetOp(iterator& pc, opcodetype& opcodeRet)
407     {
408          const_iterator pc2 = pc;
409          bool fRet = GetOp2(pc2, opcodeRet, NULL);
410          pc = begin() + (pc2 - begin());
411          return fRet;
412     }
413
414     bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
415     {
416         return GetOp2(pc, opcodeRet, &vchRet);
417     }
418
419     bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
420     {
421         return GetOp2(pc, opcodeRet, NULL);
422     }
423
424     bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
425     {
426         opcodeRet = OP_INVALIDOPCODE;
427         if (pvchRet)
428             pvchRet->clear();
429         if (pc >= end())
430             return false;
431
432         // Read instruction
433         if (end() - pc < 1)
434             return false;
435         unsigned int opcode = *pc++;
436
437         // Immediate operand
438         if (opcode <= OP_PUSHDATA4)
439         {
440             unsigned int nSize = 0;
441             if (opcode < OP_PUSHDATA1)
442             {
443                 nSize = opcode;
444             }
445             else if (opcode == OP_PUSHDATA1)
446             {
447                 if (end() - pc < 1)
448                     return false;
449                 nSize = *pc++;
450             }
451             else if (opcode == OP_PUSHDATA2)
452             {
453                 if (end() - pc < 2)
454                     return false;
455                 nSize = 0;
456                 memcpy(&nSize, &pc[0], 2);
457                 pc += 2;
458             }
459             else if (opcode == OP_PUSHDATA4)
460             {
461                 if (end() - pc < 4)
462                     return false;
463                 memcpy(&nSize, &pc[0], 4);
464                 pc += 4;
465             }
466             if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
467                 return false;
468             if (pvchRet)
469                 pvchRet->assign(pc, pc + nSize);
470             pc += nSize;
471         }
472
473         opcodeRet = (opcodetype)opcode;
474         return true;
475     }
476
477     // Encode/decode small integers:
478     static int DecodeOP_N(opcodetype opcode)
479     {
480         if (opcode == OP_0)
481             return 0;
482         assert(opcode >= OP_1 && opcode <= OP_16);
483         return (int)opcode - (int)(OP_1 - 1);
484     }
485     static opcodetype EncodeOP_N(int n)
486     {
487         assert(n >= 0 && n <= 16);
488         if (n == 0)
489             return OP_0;
490         return (opcodetype)(OP_1+n-1);
491     }
492
493     int FindAndDelete(const CScript& b)
494     {
495         int nFound = 0;
496         if (b.empty())
497             return nFound;
498         iterator pc = begin();
499         opcodetype opcode;
500         do
501         {
502             while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
503             {
504                 erase(pc, pc + b.size());
505                 ++nFound;
506             }
507         }
508         while (GetOp(pc, opcode));
509         return nFound;
510     }
511     int Find(opcodetype op) const
512     {
513         int nFound = 0;
514         opcodetype opcode;
515         for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
516             if (opcode == op)
517                 ++nFound;
518         return nFound;
519     }
520
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;
527
528     // Accurately count sigOps, including sigOps in
529     // pay-to-script-hash transactions:
530     unsigned int GetSigOpCount(const CScript& scriptSig) const;
531
532     bool IsPayToScriptHash() const;
533
534     // Called by CTransaction::IsStandard
535     bool IsPushOnly() const
536     {
537         const_iterator pc = begin();
538         while (pc < end())
539         {
540             opcodetype opcode;
541             if (!GetOp(pc, opcode))
542                 return false;
543             if (opcode > OP_16)
544                 return false;
545         }
546         return true;
547     }
548
549
550     void SetDestination(const CTxDestination& address);
551     void SetMultisig(int nRequired, const std::vector<CKey>& keys);
552
553
554     void PrintHex() const
555     {
556         printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
557     }
558
559     std::string ToString() const
560     {
561         std::string str;
562         opcodetype opcode;
563         std::vector<unsigned char> vch;
564         const_iterator pc = begin();
565         while (pc < end())
566         {
567             if (!str.empty())
568                 str += " ";
569             if (!GetOp(pc, opcode, vch))
570             {
571                 str += "[error]";
572                 return str;
573             }
574             if (0 <= opcode && opcode <= OP_PUSHDATA4)
575                 str += ValueString(vch);
576             else
577                 str += GetOpName(opcode);
578         }
579         return str;
580     }
581
582     void print() const
583     {
584         printf("%s\n", ToString().c_str());
585     }
586
587     CScriptID GetID() const
588     {
589         return CScriptID(Hash160(*this));
590     }
591 };
592
593 /** Compact serializer for scripts.
594  *
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)
600  *
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.
603  */
604 class CScriptCompressor
605 {
606 private:
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;
612
613     CScript &script;
614 protected:
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
619     // form).
620     bool IsToKeyID(CKeyID &hash) const;
621     bool IsToScriptID(CScriptID &hash) const;
622     bool IsToPubKey(std::vector<unsigned char> &pubkey) const;
623
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);
627 public:
628     CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
629
630     unsigned int GetSerializeSize(int nType, int nVersion) const {
631         std::vector<unsigned char> compr;
632         if (Compress(compr))
633             return compr.size();
634         unsigned int nSize = script.size() + nSpecialScripts;
635         return script.size() + VARINT(nSize).GetSerializeSize(nType, nVersion);
636     }
637
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()]);
643             return;
644         }
645         unsigned int nSize = script.size() + nSpecialScripts;
646         s << VARINT(nSize);
647         s << CFlatData(&script[0], &script[script.size()]);
648     }
649
650     template<typename Stream>
651     void Unserialize(Stream &s, int nType, int nVersion) {
652         unsigned int nSize = 0;
653         s >> VARINT(nSize);
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);
658             return;
659         }
660         nSize -= nSpecialScripts;
661         script.resize(nSize);
662         s >> REF(CFlatData(&script[0], &script[script.size()]));
663     }
664 };
665
666 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey);
667 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig);
668
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);
680
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);
684
685 #endif
This page took 0.05748 seconds and 4 git commands to generate.