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