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