Use fixed data types for some basic structures
[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).getint32());
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     explicit CScript(int8_t  b) { operator<<(b); }
322     explicit CScript(int16_t b) { operator<<(b); }
323     explicit CScript(int32_t b) { operator<<(b); }
324     explicit CScript(int64_t b) { operator<<(b); }
325
326     explicit CScript(uint8_t  b) { operator<<(b); }
327     explicit CScript(uint16_t b) { operator<<(b); }
328     explicit CScript(uint32_t b) { operator<<(b); }
329     explicit CScript(uint64_t 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<<(int8_t  b) { return push_int64(b); }
338     CScript& operator<<(int16_t b) { return push_int64(b); }
339     CScript& operator<<(int32_t b) { return push_int64(b); }
340     CScript& operator<<(int64_t b) { return push_int64(b); }
341
342     CScript& operator<<(uint8_t  b) { return push_uint64(b); }
343     CScript& operator<<(uint16_t b) { return push_uint64(b); }
344     CScript& operator<<(uint32_t b) { return push_uint64(b); }
345     CScript& operator<<(uint64_t b) { return push_uint64(b); }
346
347     CScript& operator<<(opcodetype opcode)
348     {
349         if (opcode < 0 || opcode > 0xff)
350             throw std::runtime_error("CScript::operator<<() : invalid opcode");
351         insert(end(), (unsigned char)opcode);
352         return *this;
353     }
354
355     CScript& operator<<(const uint160& b)
356     {
357         insert(end(), sizeof(b));
358         insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
359         return *this;
360     }
361
362     CScript& operator<<(const uint256& b)
363     {
364         insert(end(), sizeof(b));
365         insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
366         return *this;
367     }
368
369     CScript& operator<<(const CPubKey& key)
370     {
371         std::vector<unsigned char> vchKey = key.Raw();
372         return (*this) << vchKey;
373     }
374
375     CScript& operator<<(const CBigNum& b)
376     {
377         *this << b.getvch();
378         return *this;
379     }
380
381     CScript& operator<<(const std::vector<uint8_t>& b)
382     {
383         if (b.size() < OP_PUSHDATA1)
384         {
385             insert(end(), (uint8_t)b.size());
386         }
387         else if (b.size() <= 0xff)
388         {
389             insert(end(), OP_PUSHDATA1);
390             insert(end(), (uint8_t)b.size());
391         }
392         else if (b.size() <= 0xffff)
393         {
394             insert(end(), OP_PUSHDATA2);
395             uint16_t nSize = b.size();
396             insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
397         }
398         else
399         {
400             insert(end(), OP_PUSHDATA4);
401             uint32_t nSize = b.size();
402             insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
403         }
404         insert(end(), b.begin(), b.end());
405         return *this;
406     }
407
408     CScript& operator<<(const CScript& b)
409     {
410         // I'm not sure if this should push the script or concatenate scripts.
411         // If there's ever a use for pushing a script onto a script, delete this member fn
412         assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
413         return *this;
414     }
415
416
417     bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
418     {
419          // Wrapper so it can be called with either iterator or const_iterator
420          const_iterator pc2 = pc;
421          bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
422          pc = begin() + (pc2 - begin());
423          return fRet;
424     }
425
426     bool GetOp(iterator& pc, opcodetype& opcodeRet)
427     {
428          const_iterator pc2 = pc;
429          bool fRet = GetOp2(pc2, opcodeRet, NULL);
430          pc = begin() + (pc2 - begin());
431          return fRet;
432     }
433
434     bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
435     {
436         return GetOp2(pc, opcodeRet, &vchRet);
437     }
438
439     bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
440     {
441         return GetOp2(pc, opcodeRet, NULL);
442     }
443
444     bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
445     {
446         opcodeRet = OP_INVALIDOPCODE;
447         if (pvchRet)
448             pvchRet->clear();
449         if (pc >= end())
450             return false;
451
452         // Read instruction
453         if (end() - pc < 1)
454             return false;
455         unsigned int opcode = *pc++;
456
457         // Immediate operand
458         if (opcode <= OP_PUSHDATA4)
459         {
460             unsigned int nSize;
461             if (opcode < OP_PUSHDATA1)
462             {
463                 nSize = opcode;
464             }
465             else if (opcode == OP_PUSHDATA1)
466             {
467                 if (end() - pc < 1)
468                     return false;
469                 nSize = *pc++;
470             }
471             else if (opcode == OP_PUSHDATA2)
472             {
473                 if (end() - pc < 2)
474                     return false;
475                 nSize = 0;
476                 memcpy(&nSize, &pc[0], 2);
477                 pc += 2;
478             }
479             else if (opcode == OP_PUSHDATA4)
480             {
481                 if (end() - pc < 4)
482                     return false;
483                 memcpy(&nSize, &pc[0], 4);
484                 pc += 4;
485             }
486             if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
487                 return false;
488             if (pvchRet)
489                 pvchRet->assign(pc, pc + nSize);
490             pc += nSize;
491         }
492
493         opcodeRet = (opcodetype)opcode;
494         return true;
495     }
496
497     // Encode/decode small integers:
498     static int DecodeOP_N(opcodetype opcode)
499     {
500         if (opcode == OP_0)
501             return 0;
502         assert(opcode >= OP_1 && opcode <= OP_16);
503         return (int)opcode - (int)(OP_1 - 1);
504     }
505     static opcodetype EncodeOP_N(int n)
506     {
507         assert(n >= 0 && n <= 16);
508         if (n == 0)
509             return OP_0;
510         return (opcodetype)(OP_1+n-1);
511     }
512
513     int FindAndDelete(const CScript& b)
514     {
515         int nFound = 0;
516         if (b.empty())
517             return nFound;
518         iterator pc = begin();
519         opcodetype opcode;
520         do
521         {
522             while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
523             {
524                 erase(pc, pc + b.size());
525                 ++nFound;
526             }
527         }
528         while (GetOp(pc, opcode));
529         return nFound;
530     }
531     int Find(opcodetype op) const
532     {
533         int nFound = 0;
534         opcodetype opcode;
535         for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
536             if (opcode == op)
537                 ++nFound;
538         return nFound;
539     }
540
541     // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
542     // as 20 sigops. With pay-to-script-hash, that changed:
543     // CHECKMULTISIGs serialized in scriptSigs are
544     // counted more accurately, assuming they are of the form
545     //  ... OP_N CHECKMULTISIG ...
546     unsigned int GetSigOpCount(bool fAccurate) const;
547
548     // Accurately count sigOps, including sigOps in
549     // pay-to-script-hash transactions:
550     unsigned int GetSigOpCount(const CScript& scriptSig) const;
551
552     bool IsPayToScriptHash() const;
553
554     // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
555     bool IsPushOnly() const
556     {
557         const_iterator pc = begin();
558         while (pc < end())
559         {
560             opcodetype opcode;
561             if (!GetOp(pc, opcode))
562                 return false;
563             if (opcode > OP_16)
564                 return false;
565         }
566         return true;
567     }
568
569     // Called by CTransaction::IsStandard.
570     bool HasCanonicalPushes() const;
571
572     void SetDestination(const CTxDestination& address);
573     void SetMultisig(int nRequired, const std::vector<CKey>& keys);
574
575
576     void PrintHex() const
577     {
578         printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
579     }
580
581     std::string ToString(bool fShort=false) const
582     {
583         std::string str;
584         opcodetype opcode;
585         std::vector<unsigned char> vch;
586         const_iterator pc = begin();
587         while (pc < end())
588         {
589             if (!str.empty())
590                 str += " ";
591             if (!GetOp(pc, opcode, vch))
592             {
593                 str += "[error]";
594                 return str;
595             }
596             if (0 <= opcode && opcode <= OP_PUSHDATA4)
597                 str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
598             else
599                 str += GetOpName(opcode);
600         }
601         return str;
602     }
603
604     void print() const
605     {
606         printf("%s\n", ToString().c_str());
607     }
608
609     CScriptID GetID() const
610     {
611         return CScriptID(Hash160(*this));
612     }
613 };
614
615 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey, unsigned int flags);
616 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig, unsigned int flags);
617
618
619 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
620 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
621 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
622 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
623 isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
624 isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest);
625 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
626 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
627 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
628 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
629 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
630 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
631
632 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
633 // combine them intelligently and return the result.
634 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);
635
636 #endif