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