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