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