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