Merge pull request #2060 from sipa/parallel
[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 /** Signature hash types/flags */
21 enum
22 {
23     SIGHASH_ALL = 1,
24     SIGHASH_NONE = 2,
25     SIGHASH_SINGLE = 3,
26     SIGHASH_ANYONECANPAY = 0x80,
27 };
28
29 /** Script verification flags */
30 enum
31 {
32     SCRIPT_VERIFY_NONE      = 0,
33     SCRIPT_VERIFY_P2SH      = (1U << 0),
34     SCRIPT_VERIFY_STRICTENC = (1U << 1),
35     SCRIPT_VERIFY_NOCACHE   = (1U << 2),
36 };
37
38 enum txnouttype
39 {
40     TX_NONSTANDARD,
41     // 'standard' transaction types:
42     TX_PUBKEY,
43     TX_PUBKEYHASH,
44     TX_SCRIPTHASH,
45     TX_MULTISIG,
46 };
47
48 class CNoDestination {
49 public:
50     friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
51     friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
52 };
53
54 /** A txout script template with a specific destination. It is either:
55  *  * CNoDestination: no destination set
56  *  * CKeyID: TX_PUBKEYHASH destination
57  *  * CScriptID: TX_SCRIPTHASH destination
58  *  A CTxDestination is the internal data type encoded in a CBitcoinAddress
59  */
60 typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
61
62 const char* GetTxnOutputType(txnouttype t);
63
64 /** Script opcodes */
65 enum opcodetype
66 {
67     // push value
68     OP_0 = 0x00,
69     OP_FALSE = OP_0,
70     OP_PUSHDATA1 = 0x4c,
71     OP_PUSHDATA2 = 0x4d,
72     OP_PUSHDATA4 = 0x4e,
73     OP_1NEGATE = 0x4f,
74     OP_RESERVED = 0x50,
75     OP_1 = 0x51,
76     OP_TRUE=OP_1,
77     OP_2 = 0x52,
78     OP_3 = 0x53,
79     OP_4 = 0x54,
80     OP_5 = 0x55,
81     OP_6 = 0x56,
82     OP_7 = 0x57,
83     OP_8 = 0x58,
84     OP_9 = 0x59,
85     OP_10 = 0x5a,
86     OP_11 = 0x5b,
87     OP_12 = 0x5c,
88     OP_13 = 0x5d,
89     OP_14 = 0x5e,
90     OP_15 = 0x5f,
91     OP_16 = 0x60,
92
93     // control
94     OP_NOP = 0x61,
95     OP_VER = 0x62,
96     OP_IF = 0x63,
97     OP_NOTIF = 0x64,
98     OP_VERIF = 0x65,
99     OP_VERNOTIF = 0x66,
100     OP_ELSE = 0x67,
101     OP_ENDIF = 0x68,
102     OP_VERIFY = 0x69,
103     OP_RETURN = 0x6a,
104
105     // stack ops
106     OP_TOALTSTACK = 0x6b,
107     OP_FROMALTSTACK = 0x6c,
108     OP_2DROP = 0x6d,
109     OP_2DUP = 0x6e,
110     OP_3DUP = 0x6f,
111     OP_2OVER = 0x70,
112     OP_2ROT = 0x71,
113     OP_2SWAP = 0x72,
114     OP_IFDUP = 0x73,
115     OP_DEPTH = 0x74,
116     OP_DROP = 0x75,
117     OP_DUP = 0x76,
118     OP_NIP = 0x77,
119     OP_OVER = 0x78,
120     OP_PICK = 0x79,
121     OP_ROLL = 0x7a,
122     OP_ROT = 0x7b,
123     OP_SWAP = 0x7c,
124     OP_TUCK = 0x7d,
125
126     // splice ops
127     OP_CAT = 0x7e,
128     OP_SUBSTR = 0x7f,
129     OP_LEFT = 0x80,
130     OP_RIGHT = 0x81,
131     OP_SIZE = 0x82,
132
133     // bit logic
134     OP_INVERT = 0x83,
135     OP_AND = 0x84,
136     OP_OR = 0x85,
137     OP_XOR = 0x86,
138     OP_EQUAL = 0x87,
139     OP_EQUALVERIFY = 0x88,
140     OP_RESERVED1 = 0x89,
141     OP_RESERVED2 = 0x8a,
142
143     // numeric
144     OP_1ADD = 0x8b,
145     OP_1SUB = 0x8c,
146     OP_2MUL = 0x8d,
147     OP_2DIV = 0x8e,
148     OP_NEGATE = 0x8f,
149     OP_ABS = 0x90,
150     OP_NOT = 0x91,
151     OP_0NOTEQUAL = 0x92,
152
153     OP_ADD = 0x93,
154     OP_SUB = 0x94,
155     OP_MUL = 0x95,
156     OP_DIV = 0x96,
157     OP_MOD = 0x97,
158     OP_LSHIFT = 0x98,
159     OP_RSHIFT = 0x99,
160
161     OP_BOOLAND = 0x9a,
162     OP_BOOLOR = 0x9b,
163     OP_NUMEQUAL = 0x9c,
164     OP_NUMEQUALVERIFY = 0x9d,
165     OP_NUMNOTEQUAL = 0x9e,
166     OP_LESSTHAN = 0x9f,
167     OP_GREATERTHAN = 0xa0,
168     OP_LESSTHANOREQUAL = 0xa1,
169     OP_GREATERTHANOREQUAL = 0xa2,
170     OP_MIN = 0xa3,
171     OP_MAX = 0xa4,
172
173     OP_WITHIN = 0xa5,
174
175     // crypto
176     OP_RIPEMD160 = 0xa6,
177     OP_SHA1 = 0xa7,
178     OP_SHA256 = 0xa8,
179     OP_HASH160 = 0xa9,
180     OP_HASH256 = 0xaa,
181     OP_CODESEPARATOR = 0xab,
182     OP_CHECKSIG = 0xac,
183     OP_CHECKSIGVERIFY = 0xad,
184     OP_CHECKMULTISIG = 0xae,
185     OP_CHECKMULTISIGVERIFY = 0xaf,
186
187     // expansion
188     OP_NOP1 = 0xb0,
189     OP_NOP2 = 0xb1,
190     OP_NOP3 = 0xb2,
191     OP_NOP4 = 0xb3,
192     OP_NOP5 = 0xb4,
193     OP_NOP6 = 0xb5,
194     OP_NOP7 = 0xb6,
195     OP_NOP8 = 0xb7,
196     OP_NOP9 = 0xb8,
197     OP_NOP10 = 0xb9,
198
199
200
201     // template matching params
202     OP_SMALLINTEGER = 0xfa,
203     OP_PUBKEYS = 0xfb,
204     OP_PUBKEYHASH = 0xfd,
205     OP_PUBKEY = 0xfe,
206
207     OP_INVALIDOPCODE = 0xff,
208 };
209
210 const char* GetOpName(opcodetype opcode);
211
212
213
214 inline std::string ValueString(const std::vector<unsigned char>& vch)
215 {
216     if (vch.size() <= 4)
217         return strprintf("%d", CBigNum(vch).getint());
218     else
219         return HexStr(vch);
220 }
221
222 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
223 {
224     std::string str;
225     BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
226     {
227         if (!str.empty())
228             str += " ";
229         str += ValueString(vch);
230     }
231     return str;
232 }
233
234
235
236
237
238
239
240
241 /** Serialized script, used inside transaction inputs and outputs */
242 class CScript : public std::vector<unsigned char>
243 {
244 protected:
245     CScript& push_int64(int64 n)
246     {
247         if (n == -1 || (n >= 1 && n <= 16))
248         {
249             push_back(n + (OP_1 - 1));
250         }
251         else
252         {
253             CBigNum bn(n);
254             *this << bn.getvch();
255         }
256         return *this;
257     }
258
259     CScript& push_uint64(uint64 n)
260     {
261         if (n >= 1 && n <= 16)
262         {
263             push_back(n + (OP_1 - 1));
264         }
265         else
266         {
267             CBigNum bn(n);
268             *this << bn.getvch();
269         }
270         return *this;
271     }
272
273 public:
274     CScript() { }
275     CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
276     CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
277 #ifndef _MSC_VER
278     CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
279 #endif
280
281     CScript& operator+=(const CScript& b)
282     {
283         insert(end(), b.begin(), b.end());
284         return *this;
285     }
286
287     friend CScript operator+(const CScript& a, const CScript& b)
288     {
289         CScript ret = a;
290         ret += b;
291         return ret;
292     }
293
294
295     //explicit CScript(char b) is not portable.  Use 'signed char' or 'unsigned char'.
296     explicit CScript(signed char b)    { operator<<(b); }
297     explicit CScript(short b)          { operator<<(b); }
298     explicit CScript(int b)            { operator<<(b); }
299     explicit CScript(long b)           { operator<<(b); }
300     explicit CScript(int64 b)          { operator<<(b); }
301     explicit CScript(unsigned char b)  { operator<<(b); }
302     explicit CScript(unsigned int b)   { operator<<(b); }
303     explicit CScript(unsigned short b) { operator<<(b); }
304     explicit CScript(unsigned long b)  { operator<<(b); }
305     explicit CScript(uint64 b)         { operator<<(b); }
306
307     explicit CScript(opcodetype b)     { operator<<(b); }
308     explicit CScript(const uint256& b) { operator<<(b); }
309     explicit CScript(const CBigNum& b) { operator<<(b); }
310     explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
311
312
313     //CScript& operator<<(char b) is not portable.  Use 'signed char' or 'unsigned char'.
314     CScript& operator<<(signed char b)    { return push_int64(b); }
315     CScript& operator<<(short b)          { return push_int64(b); }
316     CScript& operator<<(int b)            { return push_int64(b); }
317     CScript& operator<<(long b)           { return push_int64(b); }
318     CScript& operator<<(int64 b)          { return push_int64(b); }
319     CScript& operator<<(unsigned char b)  { return push_uint64(b); }
320     CScript& operator<<(unsigned int b)   { return push_uint64(b); }
321     CScript& operator<<(unsigned short b) { return push_uint64(b); }
322     CScript& operator<<(unsigned long b)  { return push_uint64(b); }
323     CScript& operator<<(uint64 b)         { return push_uint64(b); }
324
325     CScript& operator<<(opcodetype opcode)
326     {
327         if (opcode < 0 || opcode > 0xff)
328             throw std::runtime_error("CScript::operator<<() : invalid opcode");
329         insert(end(), (unsigned char)opcode);
330         return *this;
331     }
332
333     CScript& operator<<(const uint160& b)
334     {
335         insert(end(), sizeof(b));
336         insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
337         return *this;
338     }
339
340     CScript& operator<<(const uint256& b)
341     {
342         insert(end(), sizeof(b));
343         insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
344         return *this;
345     }
346
347     CScript& operator<<(const CPubKey& key)
348     {
349         std::vector<unsigned char> vchKey = key.Raw();
350         return (*this) << vchKey;
351     }
352
353     CScript& operator<<(const CBigNum& b)
354     {
355         *this << b.getvch();
356         return *this;
357     }
358
359     CScript& operator<<(const std::vector<unsigned char>& b)
360     {
361         if (b.size() < OP_PUSHDATA1)
362         {
363             insert(end(), (unsigned char)b.size());
364         }
365         else if (b.size() <= 0xff)
366         {
367             insert(end(), OP_PUSHDATA1);
368             insert(end(), (unsigned char)b.size());
369         }
370         else if (b.size() <= 0xffff)
371         {
372             insert(end(), OP_PUSHDATA2);
373             unsigned short nSize = b.size();
374             insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
375         }
376         else
377         {
378             insert(end(), OP_PUSHDATA4);
379             unsigned int nSize = b.size();
380             insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
381         }
382         insert(end(), b.begin(), b.end());
383         return *this;
384     }
385
386     CScript& operator<<(const CScript& b)
387     {
388         // I'm not sure if this should push the script or concatenate scripts.
389         // If there's ever a use for pushing a script onto a script, delete this member fn
390         assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
391         return *this;
392     }
393
394
395     bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
396     {
397          // Wrapper so it can be called with either iterator or const_iterator
398          const_iterator pc2 = pc;
399          bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
400          pc = begin() + (pc2 - begin());
401          return fRet;
402     }
403
404     bool GetOp(iterator& pc, opcodetype& opcodeRet)
405     {
406          const_iterator pc2 = pc;
407          bool fRet = GetOp2(pc2, opcodeRet, NULL);
408          pc = begin() + (pc2 - begin());
409          return fRet;
410     }
411
412     bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
413     {
414         return GetOp2(pc, opcodeRet, &vchRet);
415     }
416
417     bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
418     {
419         return GetOp2(pc, opcodeRet, NULL);
420     }
421
422     bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
423     {
424         opcodeRet = OP_INVALIDOPCODE;
425         if (pvchRet)
426             pvchRet->clear();
427         if (pc >= end())
428             return false;
429
430         // Read instruction
431         if (end() - pc < 1)
432             return false;
433         unsigned int opcode = *pc++;
434
435         // Immediate operand
436         if (opcode <= OP_PUSHDATA4)
437         {
438             unsigned int nSize = 0;
439             if (opcode < OP_PUSHDATA1)
440             {
441                 nSize = opcode;
442             }
443             else if (opcode == OP_PUSHDATA1)
444             {
445                 if (end() - pc < 1)
446                     return false;
447                 nSize = *pc++;
448             }
449             else if (opcode == OP_PUSHDATA2)
450             {
451                 if (end() - pc < 2)
452                     return false;
453                 nSize = 0;
454                 memcpy(&nSize, &pc[0], 2);
455                 pc += 2;
456             }
457             else if (opcode == OP_PUSHDATA4)
458             {
459                 if (end() - pc < 4)
460                     return false;
461                 memcpy(&nSize, &pc[0], 4);
462                 pc += 4;
463             }
464             if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
465                 return false;
466             if (pvchRet)
467                 pvchRet->assign(pc, pc + nSize);
468             pc += nSize;
469         }
470
471         opcodeRet = (opcodetype)opcode;
472         return true;
473     }
474
475     // Encode/decode small integers:
476     static int DecodeOP_N(opcodetype opcode)
477     {
478         if (opcode == OP_0)
479             return 0;
480         assert(opcode >= OP_1 && opcode <= OP_16);
481         return (int)opcode - (int)(OP_1 - 1);
482     }
483     static opcodetype EncodeOP_N(int n)
484     {
485         assert(n >= 0 && n <= 16);
486         if (n == 0)
487             return OP_0;
488         return (opcodetype)(OP_1+n-1);
489     }
490
491     int FindAndDelete(const CScript& b)
492     {
493         int nFound = 0;
494         if (b.empty())
495             return nFound;
496         iterator pc = begin();
497         opcodetype opcode;
498         do
499         {
500             while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
501             {
502                 erase(pc, pc + b.size());
503                 ++nFound;
504             }
505         }
506         while (GetOp(pc, opcode));
507         return nFound;
508     }
509     int Find(opcodetype op) const
510     {
511         int nFound = 0;
512         opcodetype opcode;
513         for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
514             if (opcode == op)
515                 ++nFound;
516         return nFound;
517     }
518
519     // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
520     // as 20 sigops. With pay-to-script-hash, that changed:
521     // CHECKMULTISIGs serialized in scriptSigs are
522     // counted more accurately, assuming they are of the form
523     //  ... OP_N CHECKMULTISIG ...
524     unsigned int GetSigOpCount(bool fAccurate) const;
525
526     // Accurately count sigOps, including sigOps in
527     // pay-to-script-hash transactions:
528     unsigned int GetSigOpCount(const CScript& scriptSig) const;
529
530     bool IsPayToScriptHash() const;
531
532     // Called by CTransaction::IsStandard
533     bool IsPushOnly() const
534     {
535         const_iterator pc = begin();
536         while (pc < end())
537         {
538             opcodetype opcode;
539             if (!GetOp(pc, opcode))
540                 return false;
541             if (opcode > OP_16)
542                 return false;
543         }
544         return true;
545     }
546
547
548     void SetDestination(const CTxDestination& address);
549     void SetMultisig(int nRequired, const std::vector<CKey>& keys);
550
551
552     void PrintHex() const
553     {
554         printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
555     }
556
557     std::string ToString() const
558     {
559         std::string str;
560         opcodetype opcode;
561         std::vector<unsigned char> vch;
562         const_iterator pc = begin();
563         while (pc < end())
564         {
565             if (!str.empty())
566                 str += " ";
567             if (!GetOp(pc, opcode, vch))
568             {
569                 str += "[error]";
570                 return str;
571             }
572             if (0 <= opcode && opcode <= OP_PUSHDATA4)
573                 str += ValueString(vch);
574             else
575                 str += GetOpName(opcode);
576         }
577         return str;
578     }
579
580     void print() const
581     {
582         printf("%s\n", ToString().c_str());
583     }
584
585     CScriptID GetID() const
586     {
587         return CScriptID(Hash160(*this));
588     }
589 };
590
591 /** Compact serializer for scripts.
592  *
593  *  It detects common cases and encodes them much more efficiently.
594  *  3 special cases are defined:
595  *  * Pay to pubkey hash (encoded as 21 bytes)
596  *  * Pay to script hash (encoded as 21 bytes)
597  *  * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
598  *
599  *  Other scripts up to 121 bytes require 1 byte + script length. Above
600  *  that, scripts up to 16505 bytes require 2 bytes + script length.
601  */
602 class CScriptCompressor
603 {
604 private:
605     // make this static for now (there are only 6 special scripts defined)
606     // this can potentially be extended together with a new nVersion for
607     // transactions, in which case this value becomes dependent on nVersion
608     // and nHeight of the enclosing transaction.
609     static const unsigned int nSpecialScripts = 6;
610
611     CScript &script;
612 protected:
613     // These check for scripts for which a special case with a shorter encoding is defined.
614     // They are implemented separately from the CScript test, as these test for exact byte
615     // sequence correspondences, and are more strict. For example, IsToPubKey also verifies
616     // whether the public key is valid (as invalid ones cannot be represented in compressed
617     // form).
618     bool IsToKeyID(CKeyID &hash) const;
619     bool IsToScriptID(CScriptID &hash) const;
620     bool IsToPubKey(std::vector<unsigned char> &pubkey) const;
621
622     bool Compress(std::vector<unsigned char> &out) const;
623     unsigned int GetSpecialSize(unsigned int nSize) const;
624     bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
625 public:
626     CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
627
628     unsigned int GetSerializeSize(int nType, int nVersion) const {
629         std::vector<unsigned char> compr;
630         if (Compress(compr))
631             return compr.size();
632         unsigned int nSize = script.size() + nSpecialScripts;
633         return script.size() + VARINT(nSize).GetSerializeSize(nType, nVersion);
634     }
635
636     template<typename Stream>
637     void Serialize(Stream &s, int nType, int nVersion) const {
638         std::vector<unsigned char> compr;
639         if (Compress(compr)) {
640             s << CFlatData(&compr[0], &compr[compr.size()]);
641             return;
642         }
643         unsigned int nSize = script.size() + nSpecialScripts;
644         s << VARINT(nSize);
645         s << CFlatData(&script[0], &script[script.size()]);
646     }
647
648     template<typename Stream>
649     void Unserialize(Stream &s, int nType, int nVersion) {
650         unsigned int nSize = 0;
651         s >> VARINT(nSize);
652         if (nSize < nSpecialScripts) {
653             std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
654             s >> REF(CFlatData(&vch[0], &vch[vch.size()]));
655             Decompress(nSize, vch);
656             return;
657         }
658         nSize -= nSpecialScripts;
659         script.resize(nSize);
660         s >> REF(CFlatData(&script[0], &script[script.size()]));
661     }
662 };
663
664 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey);
665 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig);
666
667 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, 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);
671 bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
672 bool IsMine(const CKeyStore& keystore, const CTxDestination &dest);
673 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
674 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
675 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
676 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
677 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
678
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);
682
683 #endif
This page took 0.06353 seconds and 4 git commands to generate.