Add -enforcecanonical and -confchange options, rename IsConfirmed() to IsTrusted().
[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 class CCoins;
18 class CTransaction;
19
20 typedef std::vector<unsigned char> valtype;
21
22 /** Signature hash types/flags */
23 enum
24 {
25     SIGHASH_ALL = 1,
26     SIGHASH_NONE = 2,
27     SIGHASH_SINGLE = 3,
28     SIGHASH_ANYONECANPAY = 0x80,
29 };
30
31
32 enum txnouttype
33 {
34     TX_NONSTANDARD,
35     // 'standard' transaction types:
36     TX_PUBKEY,
37     TX_PUBKEYHASH,
38     TX_SCRIPTHASH,
39     TX_MULTISIG,
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_SMALLINTEGER = 0xfa,
197     OP_PUBKEYS = 0xfb,
198     OP_PUBKEYHASH = 0xfd,
199     OP_PUBKEY = 0xfe,
200
201     OP_INVALIDOPCODE = 0xff,
202 };
203
204 const char* GetOpName(opcodetype opcode);
205
206
207
208 inline std::string ValueString(const std::vector<unsigned char>& vch)
209 {
210     if (vch.size() <= 4)
211         return strprintf("%d", CBigNum(vch).getint());
212     else
213         return HexStr(vch);
214 }
215
216 inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
217 {
218     std::string str;
219     BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
220     {
221         if (!str.empty())
222             str += " ";
223         str += ValueString(vch);
224     }
225     return str;
226 }
227
228
229
230
231
232
233
234
235 /** Serialized script, used inside transaction inputs and outputs */
236 class CScript : public std::vector<unsigned char>
237 {
238 protected:
239     CScript& push_int64(int64 n)
240     {
241         if (n == -1 || (n >= 1 && n <= 16))
242         {
243             push_back(n + (OP_1 - 1));
244         }
245         else
246         {
247             CBigNum bn(n);
248             *this << bn.getvch();
249         }
250         return *this;
251     }
252
253     CScript& push_uint64(uint64 n)
254     {
255         if (n >= 1 && n <= 16)
256         {
257             push_back(n + (OP_1 - 1));
258         }
259         else
260         {
261             CBigNum bn(n);
262             *this << bn.getvch();
263         }
264         return *this;
265     }
266
267 public:
268     CScript() { }
269     CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
270     CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
271 #ifndef _MSC_VER
272     CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
273 #endif
274
275     CScript& operator+=(const CScript& b)
276     {
277         insert(end(), b.begin(), b.end());
278         return *this;
279     }
280
281     friend CScript operator+(const CScript& a, const CScript& b)
282     {
283         CScript ret = a;
284         ret += b;
285         return ret;
286     }
287
288
289     //explicit CScript(char b) is not portable.  Use 'signed char' or 'unsigned char'.
290     explicit CScript(signed char b)    { operator<<(b); }
291     explicit CScript(short b)          { operator<<(b); }
292     explicit CScript(int b)            { operator<<(b); }
293     explicit CScript(long b)           { operator<<(b); }
294     explicit CScript(int64 b)          { operator<<(b); }
295     explicit CScript(unsigned char b)  { operator<<(b); }
296     explicit CScript(unsigned int b)   { operator<<(b); }
297     explicit CScript(unsigned short b) { operator<<(b); }
298     explicit CScript(unsigned long b)  { operator<<(b); }
299     explicit CScript(uint64 b)         { operator<<(b); }
300
301     explicit CScript(opcodetype b)     { operator<<(b); }
302     explicit CScript(const uint256& b) { operator<<(b); }
303     explicit CScript(const CBigNum& b) { operator<<(b); }
304     explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
305
306
307     //CScript& operator<<(char b) is not portable.  Use 'signed char' or 'unsigned char'.
308     CScript& operator<<(signed char b)    { return push_int64(b); }
309     CScript& operator<<(short b)          { return push_int64(b); }
310     CScript& operator<<(int b)            { return push_int64(b); }
311     CScript& operator<<(long b)           { return push_int64(b); }
312     CScript& operator<<(int64 b)          { return push_int64(b); }
313     CScript& operator<<(unsigned char b)  { return push_uint64(b); }
314     CScript& operator<<(unsigned int b)   { return push_uint64(b); }
315     CScript& operator<<(unsigned short b) { return push_uint64(b); }
316     CScript& operator<<(unsigned long b)  { return push_uint64(b); }
317     CScript& operator<<(uint64 b)         { return push_uint64(b); }
318
319     CScript& operator<<(opcodetype opcode)
320     {
321         if (opcode < 0 || opcode > 0xff)
322             throw std::runtime_error("CScript::operator<<() : invalid opcode");
323         insert(end(), (unsigned char)opcode);
324         return *this;
325     }
326
327     CScript& operator<<(const uint160& b)
328     {
329         insert(end(), sizeof(b));
330         insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
331         return *this;
332     }
333
334     CScript& operator<<(const uint256& b)
335     {
336         insert(end(), sizeof(b));
337         insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
338         return *this;
339     }
340
341     CScript& operator<<(const CPubKey& key)
342     {
343         std::vector<unsigned char> vchKey = key.Raw();
344         return (*this) << vchKey;
345     }
346
347     CScript& operator<<(const CBigNum& b)
348     {
349         *this << b.getvch();
350         return *this;
351     }
352
353     CScript& operator<<(const std::vector<unsigned char>& b)
354     {
355         if (b.size() < OP_PUSHDATA1)
356         {
357             insert(end(), (unsigned char)b.size());
358         }
359         else if (b.size() <= 0xff)
360         {
361             insert(end(), OP_PUSHDATA1);
362             insert(end(), (unsigned char)b.size());
363         }
364         else if (b.size() <= 0xffff)
365         {
366             insert(end(), OP_PUSHDATA2);
367             unsigned short nSize = b.size();
368             insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
369         }
370         else
371         {
372             insert(end(), OP_PUSHDATA4);
373             unsigned int nSize = b.size();
374             insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
375         }
376         insert(end(), b.begin(), b.end());
377         return *this;
378     }
379
380     CScript& operator<<(const CScript& b)
381     {
382         // I'm not sure if this should push the script or concatenate scripts.
383         // If there's ever a use for pushing a script onto a script, delete this member fn
384         assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
385         return *this;
386     }
387
388
389     bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
390     {
391          // Wrapper so it can be called with either iterator or const_iterator
392          const_iterator pc2 = pc;
393          bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
394          pc = begin() + (pc2 - begin());
395          return fRet;
396     }
397
398     bool GetOp(iterator& pc, opcodetype& opcodeRet)
399     {
400          const_iterator pc2 = pc;
401          bool fRet = GetOp2(pc2, opcodeRet, NULL);
402          pc = begin() + (pc2 - begin());
403          return fRet;
404     }
405
406     bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
407     {
408         return GetOp2(pc, opcodeRet, &vchRet);
409     }
410
411     bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
412     {
413         return GetOp2(pc, opcodeRet, NULL);
414     }
415
416     bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
417     {
418         opcodeRet = OP_INVALIDOPCODE;
419         if (pvchRet)
420             pvchRet->clear();
421         if (pc >= end())
422             return false;
423
424         // Read instruction
425         if (end() - pc < 1)
426             return false;
427         unsigned int opcode = *pc++;
428
429         // Immediate operand
430         if (opcode <= OP_PUSHDATA4)
431         {
432             unsigned int nSize;
433             if (opcode < OP_PUSHDATA1)
434             {
435                 nSize = opcode;
436             }
437             else if (opcode == OP_PUSHDATA1)
438             {
439                 if (end() - pc < 1)
440                     return false;
441                 nSize = *pc++;
442             }
443             else if (opcode == OP_PUSHDATA2)
444             {
445                 if (end() - pc < 2)
446                     return false;
447                 nSize = 0;
448                 memcpy(&nSize, &pc[0], 2);
449                 pc += 2;
450             }
451             else if (opcode == OP_PUSHDATA4)
452             {
453                 if (end() - pc < 4)
454                     return false;
455                 memcpy(&nSize, &pc[0], 4);
456                 pc += 4;
457             }
458             if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
459                 return false;
460             if (pvchRet)
461                 pvchRet->assign(pc, pc + nSize);
462             pc += nSize;
463         }
464
465         opcodeRet = (opcodetype)opcode;
466         return true;
467     }
468
469     // Encode/decode small integers:
470     static int DecodeOP_N(opcodetype opcode)
471     {
472         if (opcode == OP_0)
473             return 0;
474         assert(opcode >= OP_1 && opcode <= OP_16);
475         return (int)opcode - (int)(OP_1 - 1);
476     }
477     static opcodetype EncodeOP_N(int n)
478     {
479         assert(n >= 0 && n <= 16);
480         if (n == 0)
481             return OP_0;
482         return (opcodetype)(OP_1+n-1);
483     }
484
485     int FindAndDelete(const CScript& b)
486     {
487         int nFound = 0;
488         if (b.empty())
489             return nFound;
490         iterator pc = begin();
491         opcodetype opcode;
492         do
493         {
494             while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
495             {
496                 erase(pc, pc + b.size());
497                 ++nFound;
498             }
499         }
500         while (GetOp(pc, opcode));
501         return nFound;
502     }
503     int Find(opcodetype op) const
504     {
505         int nFound = 0;
506         opcodetype opcode;
507         for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
508             if (opcode == op)
509                 ++nFound;
510         return nFound;
511     }
512
513     // Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
514     // as 20 sigops. With pay-to-script-hash, that changed:
515     // CHECKMULTISIGs serialized in scriptSigs are
516     // counted more accurately, assuming they are of the form
517     //  ... OP_N CHECKMULTISIG ...
518     unsigned int GetSigOpCount(bool fAccurate) const;
519
520     // Accurately count sigOps, including sigOps in
521     // pay-to-script-hash transactions:
522     unsigned int GetSigOpCount(const CScript& scriptSig) const;
523
524     bool IsPayToScriptHash() const;
525
526     // Called by CTransaction::IsStandard
527     bool IsPushOnly() const
528     {
529         const_iterator pc = begin();
530         while (pc < end())
531         {
532             opcodetype opcode;
533             if (!GetOp(pc, opcode))
534                 return false;
535             if (opcode > OP_16)
536                 return false;
537         }
538         return true;
539     }
540
541     // Called by CTransaction::IsStandard.
542     bool HasCanonicalPushes() const;
543
544     void SetDestination(const CTxDestination& address);
545     void SetMultisig(int nRequired, const std::vector<CKey>& keys);
546
547
548     void PrintHex() const
549     {
550         printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
551     }
552
553     std::string ToString() const
554     {
555         std::string str;
556         opcodetype opcode;
557         std::vector<unsigned char> vch;
558         const_iterator pc = begin();
559         while (pc < end())
560         {
561             if (!str.empty())
562                 str += " ";
563             if (!GetOp(pc, opcode, vch))
564             {
565                 str += "[error]";
566                 return str;
567             }
568             if (0 <= opcode && opcode <= OP_PUSHDATA4)
569                 str += ValueString(vch);
570             else
571                 str += GetOpName(opcode);
572         }
573         return str;
574     }
575
576     void print() const
577     {
578         printf("%s\n", ToString().c_str());
579     }
580
581     CScriptID GetID() const
582     {
583         return CScriptID(Hash160(*this));
584     }
585 };
586
587 /** Compact serializer for scripts.
588  *
589  *  It detects common cases and encodes them much more efficiently.
590  *  3 special cases are defined:
591  *  * Pay to pubkey hash (encoded as 21 bytes)
592  *  * Pay to script hash (encoded as 21 bytes)
593  *  * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
594  *
595  *  Other scripts up to 121 bytes require 1 byte + script length. Above
596  *  that, scripts up to 16505 bytes require 2 bytes + script length.
597  */
598 class CScriptCompressor
599 {
600 private:
601     // make this static for now (there are only 6 special scripts defined)
602     // this can potentially be extended together with a new nVersion for
603     // transactions, in which case this value becomes dependent on nVersion
604     // and nHeight of the enclosing transaction.
605     static const unsigned int nSpecialScripts = 6;
606
607     CScript &script;
608 protected:
609     // These check for scripts for which a special case with a shorter encoding is defined.
610     // They are implemented separately from the CScript test, as these test for exact byte
611     // sequence correspondences, and are more strict. For example, IsToPubKey also verifies
612     // whether the public key is valid (as invalid ones cannot be represented in compressed
613     // form).
614     bool IsToKeyID(CKeyID &hash) const;
615     bool IsToScriptID(CScriptID &hash) const;
616     bool IsToPubKey(std::vector<unsigned char> &pubkey) const;
617
618     bool Compress(std::vector<unsigned char> &out) const;
619     unsigned int GetSpecialSize(unsigned int nSize) const;
620     bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
621 public:
622     CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
623
624     unsigned int GetSerializeSize(int nType, int nVersion) const {
625         std::vector<unsigned char> compr;
626         if (Compress(compr))
627             return compr.size();
628         unsigned int nSize = script.size() + nSpecialScripts;
629         return script.size() + VARINT(nSize).GetSerializeSize(nType, nVersion);
630     }
631
632     template<typename Stream>
633     void Serialize(Stream &s, int nType, int nVersion) const {
634         std::vector<unsigned char> compr;
635         if (Compress(compr)) {
636             s << CFlatData(&compr[0], &compr[compr.size()]);
637             return;
638         }
639         unsigned int nSize = script.size() + nSpecialScripts;
640         s << VARINT(nSize);
641         s << CFlatData(&script[0], &script[script.size()]);
642     }
643
644     template<typename Stream>
645     void Unserialize(Stream &s, int nType, int nVersion) {
646         unsigned int nSize;
647         s >> VARINT(nSize);
648         if (nSize < nSpecialScripts) {
649             std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
650             s >> REF(CFlatData(&vch[0], &vch[vch.size()]));
651             Decompress(nSize, vch);
652             return;
653         }
654         nSize -= nSpecialScripts;
655         script.resize(nSize);
656         s >> REF(CFlatData(&script[0], &script[script.size()]));
657     }
658 };
659
660 bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey);
661 bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig);
662
663 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, bool fStrictEncodings, int nHashType);
664 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
665 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
666 bool IsStandard(const CScript& scriptPubKey);
667 bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
668 bool IsMine(const CKeyStore& keystore, const CTxDestination &dest);
669
670 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys);
671 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
672 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
673 bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
674 bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
675 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
676                   bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType);
677 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType);
678
679 // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
680 // combine them intelligently and return the result.
681 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);
682
683 #endif