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