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