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