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