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