Simplify OP_RETURN handling.
[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     SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = (1U << 9)
52
53 };
54
55 // Strict verification:
56 //
57 // * force DER encoding;
58 // * force low S;
59 // * ensure that CHECKMULTISIG dummy argument is null.
60 static const unsigned int STRICT_FORMAT_FLAGS = SCRIPT_VERIFY_STRICTENC | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_NULLDUMMY;
61
62 // Mandatory script verification flags that all new blocks must comply with for
63 // them to be valid. (but old blocks may not comply with) Currently just P2SH,
64 // but in the future other flags may be added, such as a soft-fork to enforce
65 // strict DER encoding.
66 //
67 // Failing one of these tests may trigger a DoS ban - see ConnectInputs() for
68 // details.
69 static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH;
70
71 // Standard script verification flags that standard transactions will comply
72 // with. However scripts violating these flags may still be present in valid
73 // blocks and we must accept those blocks.
74 static const unsigned int STRICT_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS | STRICT_FORMAT_FLAGS;
75
76 enum txnouttype
77 {
78     TX_NONSTANDARD,
79     // 'standard' transaction types:
80     TX_PUBKEY,
81     TX_PUBKEY_DROP,
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     OP_CHECKLOCKTIMEVERIFY = 0xb1,
131
132     // stack ops
133     OP_TOALTSTACK = 0x6b,
134     OP_FROMALTSTACK = 0x6c,
135     OP_2DROP = 0x6d,
136     OP_2DUP = 0x6e,
137     OP_3DUP = 0x6f,
138     OP_2OVER = 0x70,
139     OP_2ROT = 0x71,
140     OP_2SWAP = 0x72,
141     OP_IFDUP = 0x73,
142     OP_DEPTH = 0x74,
143     OP_DROP = 0x75,
144     OP_DUP = 0x76,
145     OP_NIP = 0x77,
146     OP_OVER = 0x78,
147     OP_PICK = 0x79,
148     OP_ROLL = 0x7a,
149     OP_ROT = 0x7b,
150     OP_SWAP = 0x7c,
151     OP_TUCK = 0x7d,
152
153     // splice ops
154     OP_CAT = 0x7e,
155     OP_SUBSTR = 0x7f,
156     OP_LEFT = 0x80,
157     OP_RIGHT = 0x81,
158     OP_SIZE = 0x82,
159
160     // bit logic
161     OP_INVERT = 0x83,
162     OP_AND = 0x84,
163     OP_OR = 0x85,
164     OP_XOR = 0x86,
165     OP_EQUAL = 0x87,
166     OP_EQUALVERIFY = 0x88,
167     OP_RESERVED1 = 0x89,
168     OP_RESERVED2 = 0x8a,
169
170     // numeric
171     OP_1ADD = 0x8b,
172     OP_1SUB = 0x8c,
173     OP_2MUL = 0x8d,
174     OP_2DIV = 0x8e,
175     OP_NEGATE = 0x8f,
176     OP_ABS = 0x90,
177     OP_NOT = 0x91,
178     OP_0NOTEQUAL = 0x92,
179
180     OP_ADD = 0x93,
181     OP_SUB = 0x94,
182     OP_MUL = 0x95,
183     OP_DIV = 0x96,
184     OP_MOD = 0x97,
185     OP_LSHIFT = 0x98,
186     OP_RSHIFT = 0x99,
187
188     OP_BOOLAND = 0x9a,
189     OP_BOOLOR = 0x9b,
190     OP_NUMEQUAL = 0x9c,
191     OP_NUMEQUALVERIFY = 0x9d,
192     OP_NUMNOTEQUAL = 0x9e,
193     OP_LESSTHAN = 0x9f,
194     OP_GREATERTHAN = 0xa0,
195     OP_LESSTHANOREQUAL = 0xa1,
196     OP_GREATERTHANOREQUAL = 0xa2,
197     OP_MIN = 0xa3,
198     OP_MAX = 0xa4,
199
200     OP_WITHIN = 0xa5,
201
202     // crypto
203     OP_RIPEMD160 = 0xa6,
204     OP_SHA1 = 0xa7,
205     OP_SHA256 = 0xa8,
206     OP_HASH160 = 0xa9,
207     OP_HASH256 = 0xaa,
208     OP_CODESEPARATOR = 0xab,
209     OP_CHECKSIG = 0xac,
210     OP_CHECKSIGVERIFY = 0xad,
211     OP_CHECKMULTISIG = 0xae,
212     OP_CHECKMULTISIGVERIFY = 0xaf,
213
214     // expansion
215     OP_NOP1 = 0xb0,
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 inline std::string ValueString(const std::vector<unsigned char>& vch)
240 {
241     if (vch.size() <= 4)
242         return strprintf("%d", CBigNum(vch).getint32());
243     else
244         return HexStr(vch);
245 }
246
247 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
248 {
249     std::string str;
250     BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
251     {
252         if (!str.empty())
253             str += " ";
254         str += ValueString(vch);
255     }
256     return str;
257 }
258
259 /** Serialized script, used inside transaction inputs and outputs */
260 class CScript : public std::vector<uint8_t>
261 {
262 protected:
263     CScript& push_int64(int64_t n)
264     {
265         if (n == -1 || (n >= 1 && n <= 16))
266         {
267             push_back((uint8_t)n + (OP_1 - 1));
268         }
269         else
270         {
271             CBigNum bn(n);
272             *this << bn.getvch();
273         }
274         return *this;
275     }
276
277     CScript& push_uint64(uint64_t n)
278     {
279         if (n >= 1 && n <= 16)
280         {
281             push_back((uint8_t)n + (OP_1 - 1));
282         }
283         else
284         {
285             CBigNum bn(n);
286             *this << bn.getvch();
287         }
288         return *this;
289     }
290
291 public:
292     CScript() { }
293     CScript(const CScript& b) : std::vector<uint8_t>(b.begin(), b.end()) { }
294     CScript(const_iterator pbegin, const_iterator pend) : std::vector<uint8_t>(pbegin, pend) { }
295 #ifndef _MSC_VER
296     CScript(const uint8_t* pbegin, const uint8_t* pend) : std::vector<uint8_t>(pbegin, pend) { }
297 #endif
298
299     CScript& operator+=(const CScript& b)
300     {
301         insert(end(), b.begin(), b.end());
302         return *this;
303     }
304
305     friend CScript operator+(const CScript& a, const CScript& b)
306     {
307         CScript ret = a;
308         ret += b;
309         return ret;
310     }
311
312     explicit CScript(int8_t  b) { operator<<(b); }
313     explicit CScript(int16_t b) { operator<<(b); }
314     explicit CScript(int32_t b) { operator<<(b); }
315     explicit CScript(int64_t b) { operator<<(b); }
316
317     explicit CScript(uint8_t  b) { operator<<(b); }
318     explicit CScript(uint16_t b) { operator<<(b); }
319     explicit CScript(uint32_t b) { operator<<(b); }
320     explicit CScript(uint64_t b) { operator<<(b); }
321
322     explicit CScript(opcodetype b)     { operator<<(b); }
323     explicit CScript(const uint256& b) { operator<<(b); }
324     explicit CScript(const CBigNum& b) { operator<<(b); }
325     explicit CScript(const std::vector<uint8_t>& b) { operator<<(b); }
326
327     CScript& operator<<(int8_t  b) { return push_int64(b); }
328     CScript& operator<<(int16_t b) { return push_int64(b); }
329     CScript& operator<<(int32_t b) { return push_int64(b); }
330     CScript& operator<<(int64_t b) { return push_int64(b); }
331
332     CScript& operator<<(uint8_t  b) { return push_uint64(b); }
333     CScript& operator<<(uint16_t b) { return push_uint64(b); }
334     CScript& operator<<(uint32_t b) { return push_uint64(b); }
335     CScript& operator<<(uint64_t b) { return push_uint64(b); }
336
337     CScript& operator<<(opcodetype opcode)
338     {
339         if (opcode < 0 || opcode > 0xff)
340             throw std::runtime_error("CScript::operator<<() : invalid opcode");
341         insert(end(), (uint8_t)opcode);
342         return *this;
343     }
344
345     CScript& operator<<(const uint160& b)
346     {
347         insert(end(), sizeof(b));
348         insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
349         return *this;
350     }
351
352     CScript& operator<<(const uint256& b)
353     {
354         insert(end(), sizeof(b));
355         insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
356         return *this;
357     }
358
359     CScript& operator<<(const CPubKey& key)
360     {
361         std::vector<uint8_t> vchKey = key.Raw();
362         return (*this) << vchKey;
363     }
364
365     CScript& operator<<(const CBigNum& b)
366     {
367         *this << b.getvch();
368         return *this;
369     }
370
371     CScript& operator<<(const std::vector<uint8_t>& b)
372     {
373         if (b.size() < OP_PUSHDATA1)
374         {
375             insert(end(), (uint8_t)b.size());
376         }
377         else if (b.size() <= 0xff)
378         {
379             insert(end(), OP_PUSHDATA1);
380             insert(end(), (uint8_t)b.size());
381         }
382         else if (b.size() <= 0xffff)
383         {
384             insert(end(), OP_PUSHDATA2);
385             uint16_t nSize = (uint16_t) b.size();
386             insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
387         }
388         else
389         {
390             insert(end(), OP_PUSHDATA4);
391             uint32_t nSize = (uint32_t) b.size();
392             insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
393         }
394         insert(end(), b.begin(), b.end());
395         return *this;
396     }
397
398     CScript& operator<<(const CScript& b)
399     {
400         // I'm not sure if this should push the script or concatenate scripts.
401         // If there's ever a use for pushing a script onto a script, delete this member fn
402         assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
403         return *this;
404     }
405
406
407     bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet)
408     {
409          // Wrapper so it can be called with either iterator or const_iterator
410          const_iterator pc2 = pc;
411          bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
412          pc = begin() + (pc2 - begin());
413          return fRet;
414     }
415
416     bool GetOp(iterator& pc, opcodetype& opcodeRet)
417     {
418          const_iterator pc2 = pc;
419          bool fRet = GetOp2(pc2, opcodeRet, NULL);
420          pc = begin() + (pc2 - begin());
421          return fRet;
422     }
423
424     bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet) const
425     {
426         return GetOp2(pc, opcodeRet, &vchRet);
427     }
428
429     bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
430     {
431         return GetOp2(pc, opcodeRet, NULL);
432     }
433
434     bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>* pvchRet) const
435     {
436         opcodeRet = OP_INVALIDOPCODE;
437         if (pvchRet)
438             pvchRet->clear();
439         if (pc >= end())
440             return false;
441
442         // Read instruction
443         if (end() - pc < 1)
444             return false;
445         uint32_t opcode = *pc++;
446
447         // Immediate operand
448         if (opcode <= OP_PUSHDATA4)
449         {
450             uint32_t nSize = OP_0;
451             if (opcode < OP_PUSHDATA1)
452             {
453                 nSize = opcode;
454             }
455             else if (opcode == OP_PUSHDATA1)
456             {
457                 if (end() - pc < 1)
458                     return false;
459                 nSize = *pc++;
460             }
461             else if (opcode == OP_PUSHDATA2)
462             {
463                 if (end() - pc < 2)
464                     return false;
465                 memcpy(&nSize, &pc[0], 2);
466                 pc += 2;
467             }
468             else if (opcode == OP_PUSHDATA4)
469             {
470                 if (end() - pc < 4)
471                     return false;
472                 memcpy(&nSize, &pc[0], 4);
473                 pc += 4;
474             }
475             if (end() - pc < 0 || (uint32_t)(end() - pc) < nSize)
476                 return false;
477             if (pvchRet)
478                 pvchRet->assign(pc, pc + nSize);
479             pc += nSize;
480         }
481
482         opcodeRet = (opcodetype)opcode;
483         return true;
484     }
485
486     // Encode/decode small integers:
487     static int DecodeOP_N(opcodetype opcode)
488     {
489         if (opcode == OP_0)
490             return 0;
491         assert(opcode >= OP_1 && opcode <= OP_16);
492         return (opcode - (OP_1 - 1));
493     }
494     static opcodetype EncodeOP_N(int n)
495     {
496         assert(n >= 0 && n <= 16);
497         if (n == 0)
498             return OP_0;
499         return (opcodetype)(OP_1+n-1);
500     }
501
502     int FindAndDelete(const CScript& b)
503     {
504         int nFound = 0;
505         if (b.empty())
506             return nFound;
507         iterator pc = begin();
508         opcodetype opcode;
509         do
510         {
511             while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
512             {
513                 erase(pc, pc + b.size());
514                 ++nFound;
515             }
516         }
517         while (GetOp(pc, opcode));
518         return nFound;
519     }
520     int Find(opcodetype op) const
521     {
522         int nFound = 0;
523         opcodetype opcode;
524         for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
525             if (opcode == op)
526                 ++nFound;
527         return nFound;
528     }
529
530     // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
531     // as 20 sigops. With pay-to-script-hash, that changed:
532     // CHECKMULTISIGs serialized in scriptSigs are
533     // counted more accurately, assuming they are of the form
534     //  ... OP_N CHECKMULTISIG ...
535     unsigned int GetSigOpCount(bool fAccurate) const;
536
537     // Accurately count sigOps, including sigOps in
538     // pay-to-script-hash transactions:
539     unsigned int GetSigOpCount(const CScript& scriptSig) const;
540
541     bool IsPayToScriptHash() const;
542
543     bool IsPushOnly(const_iterator pc) const
544     {
545         while (pc < end())
546         {
547             opcodetype opcode;
548             if (!GetOp(pc, opcode))
549                 return false;
550             if (opcode > OP_16)
551                 return false;
552         }
553         return true;
554     }
555
556     // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
557     bool IsPushOnly() const
558     {
559         return this->IsPushOnly(begin());
560     }
561
562     // Called by CTransaction::IsStandard.
563     bool HasCanonicalPushes() const;
564
565     void SetDestination(const CTxDestination& address);
566     void SetDestination(const CPubKey& R, CPubKey& pubKeyVariant);
567     void SetMultisig(int nRequired, const std::vector<CKey>& keys);
568
569
570     void PrintHex() const
571     {
572         printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
573     }
574
575     std::string ToString(bool fShort=false) const
576     {
577         std::string str;
578         opcodetype opcode;
579         std::vector<uint8_t> vch;
580         const_iterator pc = begin();
581         while (pc < end())
582         {
583             if (!str.empty())
584                 str += " ";
585             if (!GetOp(pc, opcode, vch))
586             {
587                 str += "[error]";
588                 return str;
589             }
590             if (0 <= opcode && opcode <= OP_PUSHDATA4)
591                 str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
592             else
593                 str += GetOpName(opcode);
594         }
595         return str;
596     }
597
598     void print() const
599     {
600         printf("%s\n", ToString().c_str());
601     }
602
603     CScriptID GetID() const
604     {
605         return CScriptID(Hash160(*this));
606     }
607 };
608
609 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey, unsigned int flags);
610 bool IsDERSignature(const valtype &vchSig, bool fWithHashType=false, bool fCheckLow=false);
611 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig, unsigned int flags);
612
613 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
614 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
615 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
616 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType);
617 isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
618 isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest);
619 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
620 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
621 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
622 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
623 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
624 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
625
626 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
627 // combine them intelligently and return the result.
628 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);
629
630 #endif