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