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