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