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