Relay OP_RETURN data TxOut as standard transaction type
[novacoin.git] / src / script.cpp
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 #include <boost/foreach.hpp>
6 #include <boost/tuple/tuple.hpp>
7
8 using namespace std;
9 using namespace boost;
10
11 #include "script.h"
12 #include "keystore.h"
13 #include "bignum.h"
14 #include "key.h"
15 #include "main.h"
16 #include "sync.h"
17 #include "util.h"
18
19 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
20
21
22
23 typedef vector<unsigned char> valtype;
24 static const valtype vchFalse(0);
25 static const valtype vchZero(0);
26 static const valtype vchTrue(1, 1);
27 static const CBigNum bnZero(0);
28 static const CBigNum bnOne(1);
29 static const CBigNum bnFalse(0);
30 static const CBigNum bnTrue(1);
31 static const size_t nMaxNumSize = 4;
32
33
34 CBigNum CastToBigNum(const valtype& vch)
35 {
36     if (vch.size() > nMaxNumSize)
37         throw runtime_error("CastToBigNum() : overflow");
38     // Get rid of extra leading zeros
39     return CBigNum(CBigNum(vch).getvch());
40 }
41
42 bool CastToBool(const valtype& vch)
43 {
44     for (unsigned int i = 0; i < vch.size(); i++)
45     {
46         if (vch[i] != 0)
47         {
48             // Can be negative zero
49             if (i == vch.size()-1 && vch[i] == 0x80)
50                 return false;
51             return true;
52         }
53     }
54     return false;
55 }
56
57 //
58 // WARNING: This does not work as expected for signed integers; the sign-bit
59 // is left in place as the integer is zero-extended. The correct behavior
60 // would be to move the most significant bit of the last byte during the
61 // resize process. MakeSameSize() is currently only used by the disabled
62 // opcodes OP_AND, OP_OR, and OP_XOR.
63 //
64 void MakeSameSize(valtype& vch1, valtype& vch2)
65 {
66     // Lengthen the shorter one
67     if (vch1.size() < vch2.size())
68         // PATCH:
69         // +unsigned char msb = vch1[vch1.size()-1];
70         // +vch1[vch1.size()-1] &= 0x7f;
71         //  vch1.resize(vch2.size(), 0);
72         // +vch1[vch1.size()-1] = msb;
73         vch1.resize(vch2.size(), 0);
74     if (vch2.size() < vch1.size())
75         // PATCH:
76         // +unsigned char msb = vch2[vch2.size()-1];
77         // +vch2[vch2.size()-1] &= 0x7f;
78         //  vch2.resize(vch1.size(), 0);
79         // +vch2[vch2.size()-1] = msb;
80         vch2.resize(vch1.size(), 0);
81 }
82
83
84
85 //
86 // Script is a stack machine (like Forth) that evaluates a predicate
87 // returning a bool indicating valid or not.  There are no loops.
88 //
89 #define stacktop(i)  (stack.at(stack.size()+(i)))
90 #define altstacktop(i)  (altstack.at(altstack.size()+(i)))
91 static inline void popstack(vector<valtype>& stack)
92 {
93     if (stack.empty())
94         throw runtime_error("popstack() : stack empty");
95     stack.pop_back();
96 }
97
98
99 const char* GetTxnOutputType(txnouttype t)
100 {
101     switch (t)
102     {
103     case TX_NONSTANDARD: return "nonstandard";
104     case TX_PUBKEY: return "pubkey";
105     case TX_PUBKEYHASH: return "pubkeyhash";
106     case TX_SCRIPTHASH: return "scripthash";
107     case TX_MULTISIG: return "multisig";
108     case TX_NULL_DATA: return "nulldata";
109     }
110     return NULL;
111 }
112
113
114 const char* GetOpName(opcodetype opcode)
115 {
116     switch (opcode)
117     {
118     // push value
119     case OP_0                      : return "0";
120     case OP_PUSHDATA1              : return "OP_PUSHDATA1";
121     case OP_PUSHDATA2              : return "OP_PUSHDATA2";
122     case OP_PUSHDATA4              : return "OP_PUSHDATA4";
123     case OP_1NEGATE                : return "-1";
124     case OP_RESERVED               : return "OP_RESERVED";
125     case OP_1                      : return "1";
126     case OP_2                      : return "2";
127     case OP_3                      : return "3";
128     case OP_4                      : return "4";
129     case OP_5                      : return "5";
130     case OP_6                      : return "6";
131     case OP_7                      : return "7";
132     case OP_8                      : return "8";
133     case OP_9                      : return "9";
134     case OP_10                     : return "10";
135     case OP_11                     : return "11";
136     case OP_12                     : return "12";
137     case OP_13                     : return "13";
138     case OP_14                     : return "14";
139     case OP_15                     : return "15";
140     case OP_16                     : return "16";
141
142     // control
143     case OP_NOP                    : return "OP_NOP";
144     case OP_VER                    : return "OP_VER";
145     case OP_IF                     : return "OP_IF";
146     case OP_NOTIF                  : return "OP_NOTIF";
147     case OP_VERIF                  : return "OP_VERIF";
148     case OP_VERNOTIF               : return "OP_VERNOTIF";
149     case OP_ELSE                   : return "OP_ELSE";
150     case OP_ENDIF                  : return "OP_ENDIF";
151     case OP_VERIFY                 : return "OP_VERIFY";
152     case OP_RETURN                 : return "OP_RETURN";
153
154     // stack ops
155     case OP_TOALTSTACK             : return "OP_TOALTSTACK";
156     case OP_FROMALTSTACK           : return "OP_FROMALTSTACK";
157     case OP_2DROP                  : return "OP_2DROP";
158     case OP_2DUP                   : return "OP_2DUP";
159     case OP_3DUP                   : return "OP_3DUP";
160     case OP_2OVER                  : return "OP_2OVER";
161     case OP_2ROT                   : return "OP_2ROT";
162     case OP_2SWAP                  : return "OP_2SWAP";
163     case OP_IFDUP                  : return "OP_IFDUP";
164     case OP_DEPTH                  : return "OP_DEPTH";
165     case OP_DROP                   : return "OP_DROP";
166     case OP_DUP                    : return "OP_DUP";
167     case OP_NIP                    : return "OP_NIP";
168     case OP_OVER                   : return "OP_OVER";
169     case OP_PICK                   : return "OP_PICK";
170     case OP_ROLL                   : return "OP_ROLL";
171     case OP_ROT                    : return "OP_ROT";
172     case OP_SWAP                   : return "OP_SWAP";
173     case OP_TUCK                   : return "OP_TUCK";
174
175     // splice ops
176     case OP_CAT                    : return "OP_CAT";
177     case OP_SUBSTR                 : return "OP_SUBSTR";
178     case OP_LEFT                   : return "OP_LEFT";
179     case OP_RIGHT                  : return "OP_RIGHT";
180     case OP_SIZE                   : return "OP_SIZE";
181
182     // bit logic
183     case OP_INVERT                 : return "OP_INVERT";
184     case OP_AND                    : return "OP_AND";
185     case OP_OR                     : return "OP_OR";
186     case OP_XOR                    : return "OP_XOR";
187     case OP_EQUAL                  : return "OP_EQUAL";
188     case OP_EQUALVERIFY            : return "OP_EQUALVERIFY";
189     case OP_RESERVED1              : return "OP_RESERVED1";
190     case OP_RESERVED2              : return "OP_RESERVED2";
191
192     // numeric
193     case OP_1ADD                   : return "OP_1ADD";
194     case OP_1SUB                   : return "OP_1SUB";
195     case OP_2MUL                   : return "OP_2MUL";
196     case OP_2DIV                   : return "OP_2DIV";
197     case OP_NEGATE                 : return "OP_NEGATE";
198     case OP_ABS                    : return "OP_ABS";
199     case OP_NOT                    : return "OP_NOT";
200     case OP_0NOTEQUAL              : return "OP_0NOTEQUAL";
201     case OP_ADD                    : return "OP_ADD";
202     case OP_SUB                    : return "OP_SUB";
203     case OP_MUL                    : return "OP_MUL";
204     case OP_DIV                    : return "OP_DIV";
205     case OP_MOD                    : return "OP_MOD";
206     case OP_LSHIFT                 : return "OP_LSHIFT";
207     case OP_RSHIFT                 : return "OP_RSHIFT";
208     case OP_BOOLAND                : return "OP_BOOLAND";
209     case OP_BOOLOR                 : return "OP_BOOLOR";
210     case OP_NUMEQUAL               : return "OP_NUMEQUAL";
211     case OP_NUMEQUALVERIFY         : return "OP_NUMEQUALVERIFY";
212     case OP_NUMNOTEQUAL            : return "OP_NUMNOTEQUAL";
213     case OP_LESSTHAN               : return "OP_LESSTHAN";
214     case OP_GREATERTHAN            : return "OP_GREATERTHAN";
215     case OP_LESSTHANOREQUAL        : return "OP_LESSTHANOREQUAL";
216     case OP_GREATERTHANOREQUAL     : return "OP_GREATERTHANOREQUAL";
217     case OP_MIN                    : return "OP_MIN";
218     case OP_MAX                    : return "OP_MAX";
219     case OP_WITHIN                 : return "OP_WITHIN";
220
221     // crypto
222     case OP_RIPEMD160              : return "OP_RIPEMD160";
223     case OP_SHA1                   : return "OP_SHA1";
224     case OP_SHA256                 : return "OP_SHA256";
225     case OP_HASH160                : return "OP_HASH160";
226     case OP_HASH256                : return "OP_HASH256";
227     case OP_CODESEPARATOR          : return "OP_CODESEPARATOR";
228     case OP_CHECKSIG               : return "OP_CHECKSIG";
229     case OP_CHECKSIGVERIFY         : return "OP_CHECKSIGVERIFY";
230     case OP_CHECKMULTISIG          : return "OP_CHECKMULTISIG";
231     case OP_CHECKMULTISIGVERIFY    : return "OP_CHECKMULTISIGVERIFY";
232
233     // expanson
234     case OP_NOP1                   : return "OP_NOP1";
235     case OP_NOP2                   : return "OP_NOP2";
236     case OP_NOP3                   : return "OP_NOP3";
237     case OP_NOP4                   : return "OP_NOP4";
238     case OP_NOP5                   : return "OP_NOP5";
239     case OP_NOP6                   : return "OP_NOP6";
240     case OP_NOP7                   : return "OP_NOP7";
241     case OP_NOP8                   : return "OP_NOP8";
242     case OP_NOP9                   : return "OP_NOP9";
243     case OP_NOP10                  : return "OP_NOP10";
244
245
246
247     // template matching params
248     case OP_PUBKEYHASH             : return "OP_PUBKEYHASH";
249     case OP_PUBKEY                 : return "OP_PUBKEY";
250     case OP_SMALLDATA              : return "OP_SMALLDATA";
251
252     case OP_INVALIDOPCODE          : return "OP_INVALIDOPCODE";
253     default:
254         return "OP_UNKNOWN";
255     }
256 }
257
258 bool IsCanonicalPubKey(const valtype &vchPubKey) {
259     if (vchPubKey.size() < 33)
260         return error("Non-canonical public key: too short");
261     if (vchPubKey[0] == 0x04) {
262         if (vchPubKey.size() != 65)
263             return error("Non-canonical public key: invalid length for uncompressed key");
264     } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
265         if (vchPubKey.size() != 33)
266             return error("Non-canonical public key: invalid length for compressed key");
267     } else {
268         return error("Non-canonical public key: compressed nor uncompressed");
269     }
270     return true;
271 }
272
273 bool IsCanonicalSignature(const valtype &vchSig) {
274     // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
275     // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
276     // Where R and S are not negative (their first byte has its highest bit not set), and not
277     // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
278     // in which case a single 0 byte is necessary and even required).
279     if (vchSig.size() < 9)
280         return error("Non-canonical signature: too short");
281     if (vchSig.size() > 73)
282         return error("Non-canonical signature: too long");
283     if (vchSig[vchSig.size() - 1] & 0x7C)
284         return error("Non-canonical signature: unknown hashtype byte");
285     if (vchSig[0] != 0x30)
286         return error("Non-canonical signature: wrong type");
287     if (vchSig[1] != vchSig.size()-3)
288         return error("Non-canonical signature: wrong length marker");
289     unsigned int nLenR = vchSig[3];
290     if (5 + nLenR >= vchSig.size())
291         return error("Non-canonical signature: S length misplaced");
292     unsigned int nLenS = vchSig[5+nLenR];
293     if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
294         return error("Non-canonical signature: R+S length mismatch");
295
296     const unsigned char *R = &vchSig[4];
297     if (R[-2] != 0x02)
298         return error("Non-canonical signature: R value type mismatch");
299     if (nLenR == 0)
300         return error("Non-canonical signature: R length is zero");
301     if (R[0] & 0x80)
302         return error("Non-canonical signature: R value negative");
303     if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
304         return error("Non-canonical signature: R value excessively padded");
305
306     const unsigned char *S = &vchSig[6+nLenR];
307     if (S[-2] != 0x02)
308         return error("Non-canonical signature: S value type mismatch");
309     if (nLenS == 0)
310         return error("Non-canonical signature: S length is zero");
311     if (S[0] & 0x80)
312         return error("Non-canonical signature: S value negative");
313     if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
314         return error("Non-canonical signature: S value excessively padded");
315
316     return true;
317 }
318
319 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, bool fStrictEncodings, int nHashType)
320 {
321     CAutoBN_CTX pctx;
322     CScript::const_iterator pc = script.begin();
323     CScript::const_iterator pend = script.end();
324     CScript::const_iterator pbegincodehash = script.begin();
325     opcodetype opcode;
326     valtype vchPushValue;
327     vector<bool> vfExec;
328     vector<valtype> altstack;
329     if (script.size() > 10000)
330         return false;
331     int nOpCount = 0;
332
333
334     try
335     {
336         while (pc < pend)
337         {
338             bool fExec = !count(vfExec.begin(), vfExec.end(), false);
339
340             //
341             // Read instruction
342             //
343             if (!script.GetOp(pc, opcode, vchPushValue))
344                 return false;
345             if (vchPushValue.size() > 520)
346                 return false;
347             if (opcode > OP_16 && ++nOpCount > 201)
348                 return false;
349
350             if (opcode == OP_CAT ||
351                 opcode == OP_SUBSTR ||
352                 opcode == OP_LEFT ||
353                 opcode == OP_RIGHT ||
354                 opcode == OP_INVERT ||
355                 opcode == OP_AND ||
356                 opcode == OP_OR ||
357                 opcode == OP_XOR ||
358                 opcode == OP_2MUL ||
359                 opcode == OP_2DIV ||
360                 opcode == OP_MUL ||
361                 opcode == OP_DIV ||
362                 opcode == OP_MOD ||
363                 opcode == OP_LSHIFT ||
364                 opcode == OP_RSHIFT)
365                 return false;
366
367             if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
368                 stack.push_back(vchPushValue);
369             else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
370             switch (opcode)
371             {
372                 //
373                 // Push value
374                 //
375                 case OP_1NEGATE:
376                 case OP_1:
377                 case OP_2:
378                 case OP_3:
379                 case OP_4:
380                 case OP_5:
381                 case OP_6:
382                 case OP_7:
383                 case OP_8:
384                 case OP_9:
385                 case OP_10:
386                 case OP_11:
387                 case OP_12:
388                 case OP_13:
389                 case OP_14:
390                 case OP_15:
391                 case OP_16:
392                 {
393                     // ( -- value)
394                     CBigNum bn((int)opcode - (int)(OP_1 - 1));
395                     stack.push_back(bn.getvch());
396                 }
397                 break;
398
399
400                 //
401                 // Control
402                 //
403                 case OP_NOP:
404                 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
405                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
406                 break;
407
408                 case OP_IF:
409                 case OP_NOTIF:
410                 {
411                     // <expression> if [statements] [else [statements]] endif
412                     bool fValue = false;
413                     if (fExec)
414                     {
415                         if (stack.size() < 1)
416                             return false;
417                         valtype& vch = stacktop(-1);
418                         fValue = CastToBool(vch);
419                         if (opcode == OP_NOTIF)
420                             fValue = !fValue;
421                         popstack(stack);
422                     }
423                     vfExec.push_back(fValue);
424                 }
425                 break;
426
427                 case OP_ELSE:
428                 {
429                     if (vfExec.empty())
430                         return false;
431                     vfExec.back() = !vfExec.back();
432                 }
433                 break;
434
435                 case OP_ENDIF:
436                 {
437                     if (vfExec.empty())
438                         return false;
439                     vfExec.pop_back();
440                 }
441                 break;
442
443                 case OP_VERIFY:
444                 {
445                     // (true -- ) or
446                     // (false -- false) and return
447                     if (stack.size() < 1)
448                         return false;
449                     bool fValue = CastToBool(stacktop(-1));
450                     if (fValue)
451                         popstack(stack);
452                     else
453                         return false;
454                 }
455                 break;
456
457                 case OP_RETURN:
458                 {
459                     return false;
460                 }
461                 break;
462
463
464                 //
465                 // Stack ops
466                 //
467                 case OP_TOALTSTACK:
468                 {
469                     if (stack.size() < 1)
470                         return false;
471                     altstack.push_back(stacktop(-1));
472                     popstack(stack);
473                 }
474                 break;
475
476                 case OP_FROMALTSTACK:
477                 {
478                     if (altstack.size() < 1)
479                         return false;
480                     stack.push_back(altstacktop(-1));
481                     popstack(altstack);
482                 }
483                 break;
484
485                 case OP_2DROP:
486                 {
487                     // (x1 x2 -- )
488                     if (stack.size() < 2)
489                         return false;
490                     popstack(stack);
491                     popstack(stack);
492                 }
493                 break;
494
495                 case OP_2DUP:
496                 {
497                     // (x1 x2 -- x1 x2 x1 x2)
498                     if (stack.size() < 2)
499                         return false;
500                     valtype vch1 = stacktop(-2);
501                     valtype vch2 = stacktop(-1);
502                     stack.push_back(vch1);
503                     stack.push_back(vch2);
504                 }
505                 break;
506
507                 case OP_3DUP:
508                 {
509                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
510                     if (stack.size() < 3)
511                         return false;
512                     valtype vch1 = stacktop(-3);
513                     valtype vch2 = stacktop(-2);
514                     valtype vch3 = stacktop(-1);
515                     stack.push_back(vch1);
516                     stack.push_back(vch2);
517                     stack.push_back(vch3);
518                 }
519                 break;
520
521                 case OP_2OVER:
522                 {
523                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
524                     if (stack.size() < 4)
525                         return false;
526                     valtype vch1 = stacktop(-4);
527                     valtype vch2 = stacktop(-3);
528                     stack.push_back(vch1);
529                     stack.push_back(vch2);
530                 }
531                 break;
532
533                 case OP_2ROT:
534                 {
535                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
536                     if (stack.size() < 6)
537                         return false;
538                     valtype vch1 = stacktop(-6);
539                     valtype vch2 = stacktop(-5);
540                     stack.erase(stack.end()-6, stack.end()-4);
541                     stack.push_back(vch1);
542                     stack.push_back(vch2);
543                 }
544                 break;
545
546                 case OP_2SWAP:
547                 {
548                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
549                     if (stack.size() < 4)
550                         return false;
551                     swap(stacktop(-4), stacktop(-2));
552                     swap(stacktop(-3), stacktop(-1));
553                 }
554                 break;
555
556                 case OP_IFDUP:
557                 {
558                     // (x - 0 | x x)
559                     if (stack.size() < 1)
560                         return false;
561                     valtype vch = stacktop(-1);
562                     if (CastToBool(vch))
563                         stack.push_back(vch);
564                 }
565                 break;
566
567                 case OP_DEPTH:
568                 {
569                     // -- stacksize
570                     CBigNum bn(stack.size());
571                     stack.push_back(bn.getvch());
572                 }
573                 break;
574
575                 case OP_DROP:
576                 {
577                     // (x -- )
578                     if (stack.size() < 1)
579                         return false;
580                     popstack(stack);
581                 }
582                 break;
583
584                 case OP_DUP:
585                 {
586                     // (x -- x x)
587                     if (stack.size() < 1)
588                         return false;
589                     valtype vch = stacktop(-1);
590                     stack.push_back(vch);
591                 }
592                 break;
593
594                 case OP_NIP:
595                 {
596                     // (x1 x2 -- x2)
597                     if (stack.size() < 2)
598                         return false;
599                     stack.erase(stack.end() - 2);
600                 }
601                 break;
602
603                 case OP_OVER:
604                 {
605                     // (x1 x2 -- x1 x2 x1)
606                     if (stack.size() < 2)
607                         return false;
608                     valtype vch = stacktop(-2);
609                     stack.push_back(vch);
610                 }
611                 break;
612
613                 case OP_PICK:
614                 case OP_ROLL:
615                 {
616                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
617                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
618                     if (stack.size() < 2)
619                         return false;
620                     int n = CastToBigNum(stacktop(-1)).getint();
621                     popstack(stack);
622                     if (n < 0 || n >= (int)stack.size())
623                         return false;
624                     valtype vch = stacktop(-n-1);
625                     if (opcode == OP_ROLL)
626                         stack.erase(stack.end()-n-1);
627                     stack.push_back(vch);
628                 }
629                 break;
630
631                 case OP_ROT:
632                 {
633                     // (x1 x2 x3 -- x2 x3 x1)
634                     //  x2 x1 x3  after first swap
635                     //  x2 x3 x1  after second swap
636                     if (stack.size() < 3)
637                         return false;
638                     swap(stacktop(-3), stacktop(-2));
639                     swap(stacktop(-2), stacktop(-1));
640                 }
641                 break;
642
643                 case OP_SWAP:
644                 {
645                     // (x1 x2 -- x2 x1)
646                     if (stack.size() < 2)
647                         return false;
648                     swap(stacktop(-2), stacktop(-1));
649                 }
650                 break;
651
652                 case OP_TUCK:
653                 {
654                     // (x1 x2 -- x2 x1 x2)
655                     if (stack.size() < 2)
656                         return false;
657                     valtype vch = stacktop(-1);
658                     stack.insert(stack.end()-2, vch);
659                 }
660                 break;
661
662
663                 //
664                 // Splice ops
665                 //
666                 case OP_CAT:
667                 {
668                     // (x1 x2 -- out)
669                     if (stack.size() < 2)
670                         return false;
671                     valtype& vch1 = stacktop(-2);
672                     valtype& vch2 = stacktop(-1);
673                     vch1.insert(vch1.end(), vch2.begin(), vch2.end());
674                     popstack(stack);
675                     if (stacktop(-1).size() > 520)
676                         return false;
677                 }
678                 break;
679
680                 case OP_SUBSTR:
681                 {
682                     // (in begin size -- out)
683                     if (stack.size() < 3)
684                         return false;
685                     valtype& vch = stacktop(-3);
686                     int nBegin = CastToBigNum(stacktop(-2)).getint();
687                     int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
688                     if (nBegin < 0 || nEnd < nBegin)
689                         return false;
690                     if (nBegin > (int)vch.size())
691                         nBegin = vch.size();
692                     if (nEnd > (int)vch.size())
693                         nEnd = vch.size();
694                     vch.erase(vch.begin() + nEnd, vch.end());
695                     vch.erase(vch.begin(), vch.begin() + nBegin);
696                     popstack(stack);
697                     popstack(stack);
698                 }
699                 break;
700
701                 case OP_LEFT:
702                 case OP_RIGHT:
703                 {
704                     // (in size -- out)
705                     if (stack.size() < 2)
706                         return false;
707                     valtype& vch = stacktop(-2);
708                     int nSize = CastToBigNum(stacktop(-1)).getint();
709                     if (nSize < 0)
710                         return false;
711                     if (nSize > (int)vch.size())
712                         nSize = vch.size();
713                     if (opcode == OP_LEFT)
714                         vch.erase(vch.begin() + nSize, vch.end());
715                     else
716                         vch.erase(vch.begin(), vch.end() - nSize);
717                     popstack(stack);
718                 }
719                 break;
720
721                 case OP_SIZE:
722                 {
723                     // (in -- in size)
724                     if (stack.size() < 1)
725                         return false;
726                     CBigNum bn(stacktop(-1).size());
727                     stack.push_back(bn.getvch());
728                 }
729                 break;
730
731
732                 //
733                 // Bitwise logic
734                 //
735                 case OP_INVERT:
736                 {
737                     // (in - out)
738                     if (stack.size() < 1)
739                         return false;
740                     valtype& vch = stacktop(-1);
741                     for (unsigned int i = 0; i < vch.size(); i++)
742                         vch[i] = ~vch[i];
743                 }
744                 break;
745
746                 //
747                 // WARNING: These disabled opcodes exhibit unexpected behavior
748                 // when used on signed integers due to a bug in MakeSameSize()
749                 // [see definition of MakeSameSize() above].
750                 //
751                 case OP_AND:
752                 case OP_OR:
753                 case OP_XOR:
754                 {
755                     // (x1 x2 - out)
756                     if (stack.size() < 2)
757                         return false;
758                     valtype& vch1 = stacktop(-2);
759                     valtype& vch2 = stacktop(-1);
760                     MakeSameSize(vch1, vch2); // <-- NOT SAFE FOR SIGNED VALUES
761                     if (opcode == OP_AND)
762                     {
763                         for (unsigned int i = 0; i < vch1.size(); i++)
764                             vch1[i] &= vch2[i];
765                     }
766                     else if (opcode == OP_OR)
767                     {
768                         for (unsigned int i = 0; i < vch1.size(); i++)
769                             vch1[i] |= vch2[i];
770                     }
771                     else if (opcode == OP_XOR)
772                     {
773                         for (unsigned int i = 0; i < vch1.size(); i++)
774                             vch1[i] ^= vch2[i];
775                     }
776                     popstack(stack);
777                 }
778                 break;
779
780                 case OP_EQUAL:
781                 case OP_EQUALVERIFY:
782                 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
783                 {
784                     // (x1 x2 - bool)
785                     if (stack.size() < 2)
786                         return false;
787                     valtype& vch1 = stacktop(-2);
788                     valtype& vch2 = stacktop(-1);
789                     bool fEqual = (vch1 == vch2);
790                     // OP_NOTEQUAL is disabled because it would be too easy to say
791                     // something like n != 1 and have some wiseguy pass in 1 with extra
792                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
793                     //if (opcode == OP_NOTEQUAL)
794                     //    fEqual = !fEqual;
795                     popstack(stack);
796                     popstack(stack);
797                     stack.push_back(fEqual ? vchTrue : vchFalse);
798                     if (opcode == OP_EQUALVERIFY)
799                     {
800                         if (fEqual)
801                             popstack(stack);
802                         else
803                             return false;
804                     }
805                 }
806                 break;
807
808
809                 //
810                 // Numeric
811                 //
812                 case OP_1ADD:
813                 case OP_1SUB:
814                 case OP_2MUL:
815                 case OP_2DIV:
816                 case OP_NEGATE:
817                 case OP_ABS:
818                 case OP_NOT:
819                 case OP_0NOTEQUAL:
820                 {
821                     // (in -- out)
822                     if (stack.size() < 1)
823                         return false;
824                     CBigNum bn = CastToBigNum(stacktop(-1));
825                     switch (opcode)
826                     {
827                     case OP_1ADD:       bn += bnOne; break;
828                     case OP_1SUB:       bn -= bnOne; break;
829                     case OP_2MUL:       bn <<= 1; break;
830                     case OP_2DIV:       bn >>= 1; break;
831                     case OP_NEGATE:     bn = -bn; break;
832                     case OP_ABS:        if (bn < bnZero) bn = -bn; break;
833                     case OP_NOT:        bn = (bn == bnZero); break;
834                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
835                     default:            assert(!"invalid opcode"); break;
836                     }
837                     popstack(stack);
838                     stack.push_back(bn.getvch());
839                 }
840                 break;
841
842                 case OP_ADD:
843                 case OP_SUB:
844                 case OP_MUL:
845                 case OP_DIV:
846                 case OP_MOD:
847                 case OP_LSHIFT:
848                 case OP_RSHIFT:
849                 case OP_BOOLAND:
850                 case OP_BOOLOR:
851                 case OP_NUMEQUAL:
852                 case OP_NUMEQUALVERIFY:
853                 case OP_NUMNOTEQUAL:
854                 case OP_LESSTHAN:
855                 case OP_GREATERTHAN:
856                 case OP_LESSTHANOREQUAL:
857                 case OP_GREATERTHANOREQUAL:
858                 case OP_MIN:
859                 case OP_MAX:
860                 {
861                     // (x1 x2 -- out)
862                     if (stack.size() < 2)
863                         return false;
864                     CBigNum bn1 = CastToBigNum(stacktop(-2));
865                     CBigNum bn2 = CastToBigNum(stacktop(-1));
866                     CBigNum bn;
867                     switch (opcode)
868                     {
869                     case OP_ADD:
870                         bn = bn1 + bn2;
871                         break;
872
873                     case OP_SUB:
874                         bn = bn1 - bn2;
875                         break;
876
877                     case OP_MUL:
878                         if (!BN_mul(&bn, &bn1, &bn2, pctx))
879                             return false;
880                         break;
881
882                     case OP_DIV:
883                         if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
884                             return false;
885                         break;
886
887                     case OP_MOD:
888                         if (!BN_mod(&bn, &bn1, &bn2, pctx))
889                             return false;
890                         break;
891
892                     case OP_LSHIFT:
893                         if (bn2 < bnZero || bn2 > CBigNum(2048))
894                             return false;
895                         bn = bn1 << bn2.getulong();
896                         break;
897
898                     case OP_RSHIFT:
899                         if (bn2 < bnZero || bn2 > CBigNum(2048))
900                             return false;
901                         bn = bn1 >> bn2.getulong();
902                         break;
903
904                     case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
905                     case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
906                     case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
907                     case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
908                     case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
909                     case OP_LESSTHAN:            bn = (bn1 < bn2); break;
910                     case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
911                     case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
912                     case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
913                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
914                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
915                     default:                     assert(!"invalid opcode"); break;
916                     }
917                     popstack(stack);
918                     popstack(stack);
919                     stack.push_back(bn.getvch());
920
921                     if (opcode == OP_NUMEQUALVERIFY)
922                     {
923                         if (CastToBool(stacktop(-1)))
924                             popstack(stack);
925                         else
926                             return false;
927                     }
928                 }
929                 break;
930
931                 case OP_WITHIN:
932                 {
933                     // (x min max -- out)
934                     if (stack.size() < 3)
935                         return false;
936                     CBigNum bn1 = CastToBigNum(stacktop(-3));
937                     CBigNum bn2 = CastToBigNum(stacktop(-2));
938                     CBigNum bn3 = CastToBigNum(stacktop(-1));
939                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
940                     popstack(stack);
941                     popstack(stack);
942                     popstack(stack);
943                     stack.push_back(fValue ? vchTrue : vchFalse);
944                 }
945                 break;
946
947
948                 //
949                 // Crypto
950                 //
951                 case OP_RIPEMD160:
952                 case OP_SHA1:
953                 case OP_SHA256:
954                 case OP_HASH160:
955                 case OP_HASH256:
956                 {
957                     // (in -- hash)
958                     if (stack.size() < 1)
959                         return false;
960                     valtype& vch = stacktop(-1);
961                     valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
962                     if (opcode == OP_RIPEMD160)
963                         RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
964                     else if (opcode == OP_SHA1)
965                         SHA1(&vch[0], vch.size(), &vchHash[0]);
966                     else if (opcode == OP_SHA256)
967                         SHA256(&vch[0], vch.size(), &vchHash[0]);
968                     else if (opcode == OP_HASH160)
969                     {
970                         uint160 hash160 = Hash160(vch);
971                         memcpy(&vchHash[0], &hash160, sizeof(hash160));
972                     }
973                     else if (opcode == OP_HASH256)
974                     {
975                         uint256 hash = Hash(vch.begin(), vch.end());
976                         memcpy(&vchHash[0], &hash, sizeof(hash));
977                     }
978                     popstack(stack);
979                     stack.push_back(vchHash);
980                 }
981                 break;
982
983                 case OP_CODESEPARATOR:
984                 {
985                     // Hash starts after the code separator
986                     pbegincodehash = pc;
987                 }
988                 break;
989
990                 case OP_CHECKSIG:
991                 case OP_CHECKSIGVERIFY:
992                 {
993                     // (sig pubkey -- bool)
994                     if (stack.size() < 2)
995                         return false;
996
997                     valtype& vchSig    = stacktop(-2);
998                     valtype& vchPubKey = stacktop(-1);
999
1000                     ////// debug print
1001                     //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1002                     //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1003
1004                     // Subset of script starting at the most recent codeseparator
1005                     CScript scriptCode(pbegincodehash, pend);
1006
1007                     // Drop the signature, since there's no way for a signature to sign itself
1008                     scriptCode.FindAndDelete(CScript(vchSig));
1009
1010                     bool fSuccess = (!fStrictEncodings || (IsCanonicalSignature(vchSig) && IsCanonicalPubKey(vchPubKey)));
1011                     if (fSuccess)
1012                         fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
1013
1014                     popstack(stack);
1015                     popstack(stack);
1016                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1017                     if (opcode == OP_CHECKSIGVERIFY)
1018                     {
1019                         if (fSuccess)
1020                             popstack(stack);
1021                         else
1022                             return false;
1023                     }
1024                 }
1025                 break;
1026
1027                 case OP_CHECKMULTISIG:
1028                 case OP_CHECKMULTISIGVERIFY:
1029                 {
1030                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1031
1032                     int i = 1;
1033                     if ((int)stack.size() < i)
1034                         return false;
1035
1036                     int nKeysCount = CastToBigNum(stacktop(-i)).getint();
1037                     if (nKeysCount < 0 || nKeysCount > 20)
1038                         return false;
1039                     nOpCount += nKeysCount;
1040                     if (nOpCount > 201)
1041                         return false;
1042                     int ikey = ++i;
1043                     i += nKeysCount;
1044                     if ((int)stack.size() < i)
1045                         return false;
1046
1047                     int nSigsCount = CastToBigNum(stacktop(-i)).getint();
1048                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
1049                         return false;
1050                     int isig = ++i;
1051                     i += nSigsCount;
1052                     if ((int)stack.size() < i)
1053                         return false;
1054
1055                     // Subset of script starting at the most recent codeseparator
1056                     CScript scriptCode(pbegincodehash, pend);
1057
1058                     // Drop the signatures, since there's no way for a signature to sign itself
1059                     for (int k = 0; k < nSigsCount; k++)
1060                     {
1061                         valtype& vchSig = stacktop(-isig-k);
1062                         scriptCode.FindAndDelete(CScript(vchSig));
1063                     }
1064
1065                     bool fSuccess = true;
1066                     while (fSuccess && nSigsCount > 0)
1067                     {
1068                         valtype& vchSig    = stacktop(-isig);
1069                         valtype& vchPubKey = stacktop(-ikey);
1070
1071                         // Check signature
1072                         bool fOk = (!fStrictEncodings || (IsCanonicalSignature(vchSig) && IsCanonicalPubKey(vchPubKey)));
1073                         if (fOk)
1074                             fOk = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
1075
1076                         if (fOk) {
1077                             isig++;
1078                             nSigsCount--;
1079                         }
1080                         ikey++;
1081                         nKeysCount--;
1082
1083                         // If there are more signatures left than keys left,
1084                         // then too many signatures have failed
1085                         if (nSigsCount > nKeysCount)
1086                             fSuccess = false;
1087                     }
1088
1089                     while (i-- > 0)
1090                         popstack(stack);
1091                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1092
1093                     if (opcode == OP_CHECKMULTISIGVERIFY)
1094                     {
1095                         if (fSuccess)
1096                             popstack(stack);
1097                         else
1098                             return false;
1099                     }
1100                 }
1101                 break;
1102
1103                 default:
1104                     return false;
1105             }
1106
1107             // Size limits
1108             if (stack.size() + altstack.size() > 1000)
1109                 return false;
1110         }
1111     }
1112     catch (...)
1113     {
1114         return false;
1115     }
1116
1117
1118     if (!vfExec.empty())
1119         return false;
1120
1121     return true;
1122 }
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1133 {
1134     if (nIn >= txTo.vin.size())
1135     {
1136         printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1137         return 1;
1138     }
1139     CTransaction txTmp(txTo);
1140
1141     // In case concatenating two scripts ends up with two codeseparators,
1142     // or an extra one at the end, this prevents all those possible incompatibilities.
1143     scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1144
1145     // Blank out other inputs' signatures
1146     for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1147         txTmp.vin[i].scriptSig = CScript();
1148     txTmp.vin[nIn].scriptSig = scriptCode;
1149
1150     // Blank out some of the outputs
1151     if ((nHashType & 0x1f) == SIGHASH_NONE)
1152     {
1153         // Wildcard payee
1154         txTmp.vout.clear();
1155
1156         // Let the others update at will
1157         for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1158             if (i != nIn)
1159                 txTmp.vin[i].nSequence = 0;
1160     }
1161     else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1162     {
1163         // Only lock-in the txout payee at same index as txin
1164         unsigned int nOut = nIn;
1165         if (nOut >= txTmp.vout.size())
1166         {
1167             printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1168             return 1;
1169         }
1170         txTmp.vout.resize(nOut+1);
1171         for (unsigned int i = 0; i < nOut; i++)
1172             txTmp.vout[i].SetNull();
1173
1174         // Let the others update at will
1175         for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1176             if (i != nIn)
1177                 txTmp.vin[i].nSequence = 0;
1178     }
1179
1180     // Blank out other inputs completely, not recommended for open transactions
1181     if (nHashType & SIGHASH_ANYONECANPAY)
1182     {
1183         txTmp.vin[0] = txTmp.vin[nIn];
1184         txTmp.vin.resize(1);
1185     }
1186
1187     // Serialize and hash
1188     CDataStream ss(SER_GETHASH, 0);
1189     ss.reserve(10000);
1190     ss << txTmp << nHashType;
1191     return Hash(ss.begin(), ss.end());
1192 }
1193
1194
1195 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1196 // twice for every transaction (once when accepted into memory pool, and
1197 // again when accepted into the block chain)
1198
1199 class CSignatureCache
1200 {
1201 private:
1202      // sigdata_type is (signature hash, signature, public key):
1203     typedef boost::tuple<uint256, std::vector<unsigned char>, std::vector<unsigned char> > sigdata_type;
1204     std::set< sigdata_type> setValid;
1205     CCriticalSection cs_sigcache;
1206
1207 public:
1208     bool
1209     Get(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1210     {
1211         LOCK(cs_sigcache);
1212
1213         sigdata_type k(hash, vchSig, pubKey);
1214         std::set<sigdata_type>::iterator mi = setValid.find(k);
1215         if (mi != setValid.end())
1216             return true;
1217         return false;
1218     }
1219
1220     void Set(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1221     {
1222         // DoS prevention: limit cache size to less than 10MB
1223         // (~200 bytes per cache entry times 50,000 entries)
1224         // Since there are a maximum of 20,000 signature operations per block
1225         // 50,000 is a reasonable default.
1226         int64 nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1227         if (nMaxCacheSize <= 0) return;
1228
1229         LOCK(cs_sigcache);
1230
1231         while (static_cast<int64>(setValid.size()) > nMaxCacheSize)
1232         {
1233             // Evict a random entry. Random because that helps
1234             // foil would-be DoS attackers who might try to pre-generate
1235             // and re-use a set of valid signatures just-slightly-greater
1236             // than our cache size.
1237             uint256 randomHash = GetRandHash();
1238             std::vector<unsigned char> unused;
1239             std::set<sigdata_type>::iterator it =
1240                 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1241             if (it == setValid.end())
1242                 it = setValid.begin();
1243             setValid.erase(*it);
1244         }
1245
1246         sigdata_type k(hash, vchSig, pubKey);
1247         setValid.insert(k);
1248     }
1249 };
1250
1251 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
1252               const CTransaction& txTo, unsigned int nIn, int nHashType)
1253 {
1254     static CSignatureCache signatureCache;
1255
1256     // Hash type is one byte tacked on to the end of the signature
1257     if (vchSig.empty())
1258         return false;
1259     if (nHashType == 0)
1260         nHashType = vchSig.back();
1261     else if (nHashType != vchSig.back())
1262         return false;
1263     vchSig.pop_back();
1264
1265     uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1266
1267     if (signatureCache.Get(sighash, vchSig, vchPubKey))
1268         return true;
1269
1270     CKey key;
1271     if (!key.SetPubKey(vchPubKey))
1272         return false;
1273
1274     if (!key.Verify(sighash, vchSig))
1275         return false;
1276
1277     signatureCache.Set(sighash, vchSig, vchPubKey);
1278     return true;
1279 }
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289 //
1290 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1291 //
1292 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1293 {
1294     // Templates
1295     static map<txnouttype, CScript> mTemplates;
1296     if (mTemplates.empty())
1297     {
1298         // Standard tx, sender provides pubkey, receiver adds signature
1299         mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1300
1301         // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1302         mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1303
1304         // Sender provides N pubkeys, receivers provides M signatures
1305         mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1306
1307         // Empty, provably prunable, data-carrying output
1308         mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1309     }
1310
1311     // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1312     // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1313     if (scriptPubKey.IsPayToScriptHash())
1314     {
1315         typeRet = TX_SCRIPTHASH;
1316         vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1317         vSolutionsRet.push_back(hashBytes);
1318         return true;
1319     }
1320
1321     // Scan templates
1322     const CScript& script1 = scriptPubKey;
1323     BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1324     {
1325         const CScript& script2 = tplate.second;
1326         vSolutionsRet.clear();
1327
1328         opcodetype opcode1, opcode2;
1329         vector<unsigned char> vch1, vch2;
1330
1331         // Compare
1332         CScript::const_iterator pc1 = script1.begin();
1333         CScript::const_iterator pc2 = script2.begin();
1334         while (true)
1335         {
1336             if (pc1 == script1.end() && pc2 == script2.end())
1337             {
1338                 // Found a match
1339                 typeRet = tplate.first;
1340                 if (typeRet == TX_MULTISIG)
1341                 {
1342                     // Additional checks for TX_MULTISIG:
1343                     unsigned char m = vSolutionsRet.front()[0];
1344                     unsigned char n = vSolutionsRet.back()[0];
1345                     if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1346                         return false;
1347                 }
1348                 return true;
1349             }
1350             if (!script1.GetOp(pc1, opcode1, vch1))
1351                 break;
1352             if (!script2.GetOp(pc2, opcode2, vch2))
1353                 break;
1354
1355             // Template matching opcodes:
1356             if (opcode2 == OP_PUBKEYS)
1357             {
1358                 while (vch1.size() >= 33 && vch1.size() <= 120)
1359                 {
1360                     vSolutionsRet.push_back(vch1);
1361                     if (!script1.GetOp(pc1, opcode1, vch1))
1362                         break;
1363                 }
1364                 if (!script2.GetOp(pc2, opcode2, vch2))
1365                     break;
1366                 // Normal situation is to fall through
1367                 // to other if/else statements
1368             }
1369
1370             if (opcode2 == OP_PUBKEY)
1371             {
1372                 if (vch1.size() < 33 || vch1.size() > 120)
1373                     break;
1374                 vSolutionsRet.push_back(vch1);
1375             }
1376             else if (opcode2 == OP_PUBKEYHASH)
1377             {
1378                 if (vch1.size() != sizeof(uint160))
1379                     break;
1380                 vSolutionsRet.push_back(vch1);
1381             }
1382             else if (opcode2 == OP_SMALLINTEGER)
1383             {   // Single-byte small integer pushed onto vSolutions
1384                 if (opcode1 == OP_0 ||
1385                     (opcode1 >= OP_1 && opcode1 <= OP_16))
1386                 {
1387                     char n = (char)CScript::DecodeOP_N(opcode1);
1388                     vSolutionsRet.push_back(valtype(1, n));
1389                 }
1390                 else
1391                     break;
1392             }
1393             else if (opcode2 == OP_SMALLDATA)
1394             {
1395                 // small pushdata, <= 80 bytes
1396                 if (vch1.size() > 80)
1397                     break;
1398             }
1399             else if (opcode1 != opcode2 || vch1 != vch2)
1400             {
1401                 // Others must match exactly
1402                 break;
1403             }
1404         }
1405     }
1406
1407     vSolutionsRet.clear();
1408     typeRet = TX_NONSTANDARD;
1409     return false;
1410 }
1411
1412
1413 bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1414 {
1415     CKey key;
1416     if (!keystore.GetKey(address, key))
1417         return false;
1418
1419     vector<unsigned char> vchSig;
1420     if (!key.Sign(hash, vchSig))
1421         return false;
1422     vchSig.push_back((unsigned char)nHashType);
1423     scriptSigRet << vchSig;
1424
1425     return true;
1426 }
1427
1428 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1429 {
1430     int nSigned = 0;
1431     int nRequired = multisigdata.front()[0];
1432     for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1433     {
1434         const valtype& pubkey = multisigdata[i];
1435         CKeyID keyID = CPubKey(pubkey).GetID();
1436         if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1437             ++nSigned;
1438     }
1439     return nSigned==nRequired;
1440 }
1441
1442 //
1443 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1444 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1445 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1446 // Returns false if scriptPubKey could not be completely satisfied.
1447 //
1448 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1449                   CScript& scriptSigRet, txnouttype& whichTypeRet)
1450 {
1451     scriptSigRet.clear();
1452
1453     vector<valtype> vSolutions;
1454     if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1455         return false;
1456
1457     CKeyID keyID;
1458     switch (whichTypeRet)
1459     {
1460     case TX_NONSTANDARD:
1461     case TX_NULL_DATA:
1462         return false;
1463     case TX_PUBKEY:
1464         keyID = CPubKey(vSolutions[0]).GetID();
1465         return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1466     case TX_PUBKEYHASH:
1467         keyID = CKeyID(uint160(vSolutions[0]));
1468         if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1469             return false;
1470         else
1471         {
1472             CPubKey vch;
1473             keystore.GetPubKey(keyID, vch);
1474             scriptSigRet << vch;
1475         }
1476         return true;
1477     case TX_SCRIPTHASH:
1478         return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1479
1480     case TX_MULTISIG:
1481         scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1482         return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1483     }
1484     return false;
1485 }
1486
1487 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1488 {
1489     switch (t)
1490     {
1491     case TX_NONSTANDARD:
1492         return -1;
1493     case TX_NULL_DATA:
1494         return 1;
1495     case TX_PUBKEY:
1496         return 1;
1497     case TX_PUBKEYHASH:
1498         return 2;
1499     case TX_MULTISIG:
1500         if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1501             return -1;
1502         return vSolutions[0][0] + 1;
1503     case TX_SCRIPTHASH:
1504         return 1; // doesn't include args needed by the script
1505     }
1506     return -1;
1507 }
1508
1509 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1510 {
1511     vector<valtype> vSolutions;
1512     if (!Solver(scriptPubKey, whichType, vSolutions))
1513         return false;
1514
1515     if (whichType == TX_MULTISIG)
1516     {
1517         unsigned char m = vSolutions.front()[0];
1518         unsigned char n = vSolutions.back()[0];
1519         // Support up to x-of-3 multisig txns as standard
1520         if (n < 1 || n > 3)
1521             return false;
1522         if (m < 1 || m > n)
1523             return false;
1524     }
1525
1526     return whichType != TX_NONSTANDARD;
1527 }
1528
1529
1530 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1531 {
1532     unsigned int nResult = 0;
1533     BOOST_FOREACH(const valtype& pubkey, pubkeys)
1534     {
1535         CKeyID keyID = CPubKey(pubkey).GetID();
1536         if (keystore.HaveKey(keyID))
1537             ++nResult;
1538     }
1539     return nResult;
1540 }
1541
1542
1543 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1544 {
1545 private:
1546     const CKeyStore *keystore;
1547 public:
1548     CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1549     bool operator()(const CNoDestination &dest) const { return false; }
1550     bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1551     bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1552 };
1553
1554 bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
1555 {
1556     return boost::apply_visitor(CKeyStoreIsMineVisitor(&keystore), dest);
1557 }
1558
1559 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1560 {
1561     vector<valtype> vSolutions;
1562     txnouttype whichType;
1563     if (!Solver(scriptPubKey, whichType, vSolutions))
1564         return false;
1565
1566     CKeyID keyID;
1567     switch (whichType)
1568     {
1569     case TX_NONSTANDARD:
1570     case TX_NULL_DATA:
1571         return false;
1572     case TX_PUBKEY:
1573         keyID = CPubKey(vSolutions[0]).GetID();
1574         return keystore.HaveKey(keyID);
1575     case TX_PUBKEYHASH:
1576         keyID = CKeyID(uint160(vSolutions[0]));
1577         return keystore.HaveKey(keyID);
1578     case TX_SCRIPTHASH:
1579     {
1580         CScript subscript;
1581         if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
1582             return false;
1583         return IsMine(keystore, subscript);
1584     }
1585     case TX_MULTISIG:
1586     {
1587         // Only consider transactions "mine" if we own ALL the
1588         // keys involved. multi-signature transactions that are
1589         // partially owned (somebody else has a key that can spend
1590         // them) enable spend-out-from-under-you attacks, especially
1591         // in shared-wallet situations.
1592         vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1593         return HaveKeys(keys, keystore) == keys.size();
1594     }
1595     }
1596     return false;
1597 }
1598
1599 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1600 private:
1601     const CKeyStore &keystore;
1602     std::vector<CKeyID> &vKeys;
1603
1604 public:
1605     CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1606
1607     void Process(const CScript &script) {
1608         txnouttype type;
1609         std::vector<CTxDestination> vDest;
1610         int nRequired;
1611         if (ExtractDestinations(script, type, vDest, nRequired)) {
1612             BOOST_FOREACH(const CTxDestination &dest, vDest)
1613                 boost::apply_visitor(*this, dest);
1614         }
1615     }
1616
1617     void operator()(const CKeyID &keyId) {
1618         if (keystore.HaveKey(keyId))
1619             vKeys.push_back(keyId);
1620     }
1621
1622     void operator()(const CScriptID &scriptId) {
1623         CScript script;
1624         if (keystore.GetCScript(scriptId, script))
1625             Process(script);
1626     }
1627
1628     void operator()(const CNoDestination &none) {}
1629 };
1630
1631
1632 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1633     CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1634 }
1635
1636 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1637 {
1638     vector<valtype> vSolutions;
1639     txnouttype whichType;
1640     if (!Solver(scriptPubKey, whichType, vSolutions))
1641         return false;
1642
1643     if (whichType == TX_PUBKEY)
1644     {
1645         addressRet = CPubKey(vSolutions[0]).GetID();
1646         return true;
1647     }
1648     else if (whichType == TX_PUBKEYHASH)
1649     {
1650         addressRet = CKeyID(uint160(vSolutions[0]));
1651         return true;
1652     }
1653     else if (whichType == TX_SCRIPTHASH)
1654     {
1655         addressRet = CScriptID(uint160(vSolutions[0]));
1656         return true;
1657     }
1658     // Multisig txns have more than one address...
1659     return false;
1660 }
1661
1662 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1663 {
1664     addressRet.clear();
1665     typeRet = TX_NONSTANDARD;
1666     vector<valtype> vSolutions;
1667     if (!Solver(scriptPubKey, typeRet, vSolutions))
1668         return false;
1669     if (typeRet == TX_NULL_DATA)
1670         return true;
1671
1672     if (typeRet == TX_MULTISIG)
1673     {
1674         nRequiredRet = vSolutions.front()[0];
1675         for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1676         {
1677             CTxDestination address = CPubKey(vSolutions[i]).GetID();
1678             addressRet.push_back(address);
1679         }
1680     }
1681     else
1682     {
1683         nRequiredRet = 1;
1684         CTxDestination address;
1685         if (!ExtractDestination(scriptPubKey, address))
1686            return false;
1687         addressRet.push_back(address);
1688     }
1689
1690     return true;
1691 }
1692
1693 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1694                   bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType)
1695 {
1696     vector<vector<unsigned char> > stack, stackCopy;
1697     if (!EvalScript(stack, scriptSig, txTo, nIn, fStrictEncodings, nHashType))
1698         return false;
1699     if (fValidatePayToScriptHash)
1700         stackCopy = stack;
1701     if (!EvalScript(stack, scriptPubKey, txTo, nIn, fStrictEncodings, nHashType))
1702         return false;
1703     if (stack.empty())
1704         return false;
1705
1706     if (CastToBool(stack.back()) == false)
1707         return false;
1708
1709     // Additional validation for spend-to-script-hash transactions:
1710     if (fValidatePayToScriptHash && scriptPubKey.IsPayToScriptHash())
1711     {
1712         if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1713             return false;            // or validation fails
1714
1715         const valtype& pubKeySerialized = stackCopy.back();
1716         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1717         popstack(stackCopy);
1718
1719         if (!EvalScript(stackCopy, pubKey2, txTo, nIn, fStrictEncodings, nHashType))
1720             return false;
1721         if (stackCopy.empty())
1722             return false;
1723         return CastToBool(stackCopy.back());
1724     }
1725
1726     return true;
1727 }
1728
1729
1730 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1731 {
1732     assert(nIn < txTo.vin.size());
1733     CTxIn& txin = txTo.vin[nIn];
1734
1735     // Leave out the signature from the hash, since a signature can't sign itself.
1736     // The checksig op will also drop the signatures from its hash.
1737     uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1738
1739     txnouttype whichType;
1740     if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1741         return false;
1742
1743     if (whichType == TX_SCRIPTHASH)
1744     {
1745         // Solver returns the subscript that need to be evaluated;
1746         // the final scriptSig is the signatures from that
1747         // and then the serialized subscript:
1748         CScript subscript = txin.scriptSig;
1749
1750         // Recompute txn hash using subscript in place of scriptPubKey:
1751         uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1752
1753         txnouttype subType;
1754         bool fSolved =
1755             Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1756         // Append serialized subscript whether or not it is completely signed:
1757         txin.scriptSig << static_cast<valtype>(subscript);
1758         if (!fSolved) return false;
1759     }
1760
1761     // Test solution
1762     return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, true, true, 0);
1763 }
1764
1765 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1766 {
1767     assert(nIn < txTo.vin.size());
1768     CTxIn& txin = txTo.vin[nIn];
1769     assert(txin.prevout.n < txFrom.vout.size());
1770     const CTxOut& txout = txFrom.vout[txin.prevout.n];
1771
1772     return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1773 }
1774
1775 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType)
1776 {
1777     assert(nIn < txTo.vin.size());
1778     const CTxIn& txin = txTo.vin[nIn];
1779     if (txin.prevout.n >= txFrom.vout.size())
1780         return false;
1781
1782     const CTxOut& txout = txFrom.vout[txin.prevout.n];
1783
1784     return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, fStrictEncodings, nHashType);
1785 }
1786
1787 static CScript PushAll(const vector<valtype>& values)
1788 {
1789     CScript result;
1790     BOOST_FOREACH(const valtype& v, values)
1791         result << v;
1792     return result;
1793 }
1794
1795 static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1796                                const vector<valtype>& vSolutions,
1797                                vector<valtype>& sigs1, vector<valtype>& sigs2)
1798 {
1799     // Combine all the signatures we've got:
1800     set<valtype> allsigs;
1801     BOOST_FOREACH(const valtype& v, sigs1)
1802     {
1803         if (!v.empty())
1804             allsigs.insert(v);
1805     }
1806     BOOST_FOREACH(const valtype& v, sigs2)
1807     {
1808         if (!v.empty())
1809             allsigs.insert(v);
1810     }
1811
1812     // Build a map of pubkey -> signature by matching sigs to pubkeys:
1813     assert(vSolutions.size() > 1);
1814     unsigned int nSigsRequired = vSolutions.front()[0];
1815     unsigned int nPubKeys = vSolutions.size()-2;
1816     map<valtype, valtype> sigs;
1817     BOOST_FOREACH(const valtype& sig, allsigs)
1818     {
1819         for (unsigned int i = 0; i < nPubKeys; i++)
1820         {
1821             const valtype& pubkey = vSolutions[i+1];
1822             if (sigs.count(pubkey))
1823                 continue; // Already got a sig for this pubkey
1824
1825             if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0))
1826             {
1827                 sigs[pubkey] = sig;
1828                 break;
1829             }
1830         }
1831     }
1832     // Now build a merged CScript:
1833     unsigned int nSigsHave = 0;
1834     CScript result; result << OP_0; // pop-one-too-many workaround
1835     for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1836     {
1837         if (sigs.count(vSolutions[i+1]))
1838         {
1839             result << sigs[vSolutions[i+1]];
1840             ++nSigsHave;
1841         }
1842     }
1843     // Fill any missing with OP_0:
1844     for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1845         result << OP_0;
1846
1847     return result;
1848 }
1849
1850 static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1851                                  const txnouttype txType, const vector<valtype>& vSolutions,
1852                                  vector<valtype>& sigs1, vector<valtype>& sigs2)
1853 {
1854     switch (txType)
1855     {
1856     case TX_NONSTANDARD:
1857     case TX_NULL_DATA:
1858         // Don't know anything about this, assume bigger one is correct:
1859         if (sigs1.size() >= sigs2.size())
1860             return PushAll(sigs1);
1861         return PushAll(sigs2);
1862     case TX_PUBKEY:
1863     case TX_PUBKEYHASH:
1864         // Signatures are bigger than placeholders or empty scripts:
1865         if (sigs1.empty() || sigs1[0].empty())
1866             return PushAll(sigs2);
1867         return PushAll(sigs1);
1868     case TX_SCRIPTHASH:
1869         if (sigs1.empty() || sigs1.back().empty())
1870             return PushAll(sigs2);
1871         else if (sigs2.empty() || sigs2.back().empty())
1872             return PushAll(sigs1);
1873         else
1874         {
1875             // Recur to combine:
1876             valtype spk = sigs1.back();
1877             CScript pubKey2(spk.begin(), spk.end());
1878
1879             txnouttype txType2;
1880             vector<vector<unsigned char> > vSolutions2;
1881             Solver(pubKey2, txType2, vSolutions2);
1882             sigs1.pop_back();
1883             sigs2.pop_back();
1884             CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1885             result << spk;
1886             return result;
1887         }
1888     case TX_MULTISIG:
1889         return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1890     }
1891
1892     return CScript();
1893 }
1894
1895 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1896                           const CScript& scriptSig1, const CScript& scriptSig2)
1897 {
1898     txnouttype txType;
1899     vector<vector<unsigned char> > vSolutions;
1900     Solver(scriptPubKey, txType, vSolutions);
1901
1902     vector<valtype> stack1;
1903     EvalScript(stack1, scriptSig1, CTransaction(), 0, true, 0);
1904     vector<valtype> stack2;
1905     EvalScript(stack2, scriptSig2, CTransaction(), 0, true, 0);
1906
1907     return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1908 }
1909
1910 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1911 {
1912     unsigned int n = 0;
1913     const_iterator pc = begin();
1914     opcodetype lastOpcode = OP_INVALIDOPCODE;
1915     while (pc < end())
1916     {
1917         opcodetype opcode;
1918         if (!GetOp(pc, opcode))
1919             break;
1920         if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1921             n++;
1922         else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1923         {
1924             if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1925                 n += DecodeOP_N(lastOpcode);
1926             else
1927                 n += 20;
1928         }
1929         lastOpcode = opcode;
1930     }
1931     return n;
1932 }
1933
1934 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1935 {
1936     if (!IsPayToScriptHash())
1937         return GetSigOpCount(true);
1938
1939     // This is a pay-to-script-hash scriptPubKey;
1940     // get the last item that the scriptSig
1941     // pushes onto the stack:
1942     const_iterator pc = scriptSig.begin();
1943     vector<unsigned char> data;
1944     while (pc < scriptSig.end())
1945     {
1946         opcodetype opcode;
1947         if (!scriptSig.GetOp(pc, opcode, data))
1948             return 0;
1949         if (opcode > OP_16)
1950             return 0;
1951     }
1952
1953     /// ... and return its opcount:
1954     CScript subscript(data.begin(), data.end());
1955     return subscript.GetSigOpCount(true);
1956 }
1957
1958 bool CScript::IsPayToScriptHash() const
1959 {
1960     // Extra-fast test for pay-to-script-hash CScripts:
1961     return (this->size() == 23 &&
1962             this->at(0) == OP_HASH160 &&
1963             this->at(1) == 0x14 &&
1964             this->at(22) == OP_EQUAL);
1965 }
1966
1967 bool CScript::HasCanonicalPushes() const
1968 {
1969     const_iterator pc = begin();
1970     while (pc < end())
1971     {
1972         opcodetype opcode;
1973         std::vector<unsigned char> data;
1974         if (!GetOp(pc, opcode, data))
1975             return false;
1976         if (opcode > OP_16)
1977             continue;
1978         if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
1979             // Could have used an OP_n code, rather than a 1-byte push.
1980             return false;
1981         if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
1982             // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
1983             return false;
1984         if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
1985             // Could have used an OP_PUSHDATA1.
1986             return false;
1987         if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
1988             // Could have used an OP_PUSHDATA2.
1989             return false;
1990     }
1991     return true;
1992 }
1993
1994 class CScriptVisitor : public boost::static_visitor<bool>
1995 {
1996 private:
1997     CScript *script;
1998 public:
1999     CScriptVisitor(CScript *scriptin) { script = scriptin; }
2000
2001     bool operator()(const CNoDestination &dest) const {
2002         script->clear();
2003         return false;
2004     }
2005
2006     bool operator()(const CKeyID &keyID) const {
2007         script->clear();
2008         *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2009         return true;
2010     }
2011
2012     bool operator()(const CScriptID &scriptID) const {
2013         script->clear();
2014         *script << OP_HASH160 << scriptID << OP_EQUAL;
2015         return true;
2016     }
2017 };
2018
2019 void CScript::SetDestination(const CTxDestination& dest)
2020 {
2021     boost::apply_visitor(CScriptVisitor(this), dest);
2022 }
2023
2024 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
2025 {
2026     this->clear();
2027
2028     *this << EncodeOP_N(nRequired);
2029     BOOST_FOREACH(const CKey& key, keys)
2030         *this << key.GetPubKey();
2031     *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
2032 }
2033
2034 bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
2035 {
2036     if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 
2037                             && script[2] == 20 && script[23] == OP_EQUALVERIFY
2038                             && script[24] == OP_CHECKSIG) {
2039         memcpy(&hash, &script[3], 20);
2040         return true;
2041     }
2042     return false;
2043 }
2044
2045 bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
2046 {
2047     if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
2048                             && script[22] == OP_EQUAL) {
2049         memcpy(&hash, &script[2], 20);
2050         return true;
2051     }
2052     return false;
2053 }
2054
2055 bool CScriptCompressor::IsToPubKey(std::vector<unsigned char> &pubkey) const
2056 {
2057     if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
2058                             && (script[1] == 0x02 || script[1] == 0x03)) {
2059         pubkey.resize(33);
2060         memcpy(&pubkey[0], &script[1], 33);
2061         return true;
2062     }
2063     if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG
2064                             && script[1] == 0x04) {
2065         pubkey.resize(65);
2066         memcpy(&pubkey[0], &script[1], 65);
2067         CKey key;
2068         return (key.SetPubKey(CPubKey(pubkey))); // SetPubKey fails if this is not a valid public key, a case that would not be compressible
2069     }
2070     return false;
2071 }
2072
2073 bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
2074 {
2075     CKeyID keyID;
2076     if (IsToKeyID(keyID)) {
2077         out.resize(21);
2078         out[0] = 0x00;
2079         memcpy(&out[1], &keyID, 20);
2080         return true;
2081     }
2082     CScriptID scriptID;
2083     if (IsToScriptID(scriptID)) {
2084         out.resize(21);
2085         out[0] = 0x01;
2086         memcpy(&out[1], &scriptID, 20);
2087         return true;
2088     }
2089     std::vector<unsigned char> pubkey;
2090     if (IsToPubKey(pubkey)) {
2091         out.resize(33);
2092         memcpy(&out[1], &pubkey[1], 32);
2093         if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
2094             out[0] = pubkey[0];
2095             return true;
2096         } else if (pubkey[0] == 0x04) {
2097             out[0] = 0x04 | (pubkey[64] & 0x01);
2098             return true;
2099         }
2100     }
2101     return false;
2102 }
2103
2104 unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
2105 {
2106     if (nSize == 0 || nSize == 1)
2107         return 20;
2108     if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
2109         return 32;
2110     return 0;
2111 }
2112
2113 bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
2114 {
2115     switch(nSize) {
2116     case 0x00:
2117         script.resize(25);
2118         script[0] = OP_DUP;
2119         script[1] = OP_HASH160;
2120         script[2] = 20;
2121         memcpy(&script[3], &in[0], 20);
2122         script[23] = OP_EQUALVERIFY;
2123         script[24] = OP_CHECKSIG;
2124         return true;
2125     case 0x01:
2126         script.resize(23);
2127         script[0] = OP_HASH160;
2128         script[1] = 20;
2129         memcpy(&script[2], &in[0], 20);
2130         script[22] = OP_EQUAL;
2131         return true;
2132     case 0x02:
2133     case 0x03:
2134         script.resize(35);
2135         script[0] = 33;
2136         script[1] = nSize;
2137         memcpy(&script[2], &in[0], 32);
2138         script[34] = OP_CHECKSIG;
2139         return true;
2140     case 0x04:
2141     case 0x05:
2142         std::vector<unsigned char> vch(33, 0x00);
2143         vch[0] = nSize - 2;
2144         memcpy(&vch[1], &in[0], 32);
2145         CKey key;
2146         if (!key.SetPubKey(CPubKey(vch)))
2147             return false;
2148         key.SetCompressedPubKey(false); // Decompress public key
2149         CPubKey pubkey = key.GetPubKey();
2150         script.resize(67);
2151         script[0] = 65;
2152         memcpy(&script[1], &pubkey.Raw()[0], 65);
2153         script[66] = OP_CHECKSIG;
2154         return true;
2155     }
2156     return false;
2157 }