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