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