Move signature verification functions to CPubKey.
[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     CPubKey pubkey(vchPubKey);
1288     if (!pubkey.IsValid())
1289         return false;
1290
1291     // Hash type is one byte tacked on to the end of the signature
1292     if (vchSig.empty())
1293         return false;
1294     if (nHashType == 0)
1295         nHashType = vchSig.back();
1296     else if (nHashType != vchSig.back())
1297         return false;
1298     vchSig.pop_back();
1299
1300     uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1301
1302     if (signatureCache.Get(sighash, vchSig, pubkey))
1303         return true;
1304
1305     if (!pubkey.Verify(sighash, vchSig))
1306         return false;
1307
1308     if (!(flags & SCRIPT_VERIFY_NOCACHE))
1309         signatureCache.Set(sighash, vchSig, pubkey);
1310
1311     return true;
1312 }
1313
1314
1315 //
1316 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1317 //
1318 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1319 {
1320     // Templates
1321     static map<txnouttype, CScript> mTemplates;
1322     if (mTemplates.empty())
1323     {
1324         // Standard tx, sender provides pubkey, receiver adds signature
1325         mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1326
1327         // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1328         mTemplates.insert(make_pair(TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG));
1329
1330         // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1331         mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1332
1333         // Sender provides N pubkeys, receivers provides M signatures
1334         mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1335
1336         // Empty, provably prunable, data-carrying output
1337         mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1338     }
1339
1340     vSolutionsRet.clear();
1341
1342     // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1343     // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1344     if (scriptPubKey.IsPayToScriptHash())
1345     {
1346         typeRet = TX_SCRIPTHASH;
1347         vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1348         vSolutionsRet.push_back(hashBytes);
1349         return true;
1350     }
1351
1352     // Provably prunable, data-carrying output
1353     //
1354     // So long as script passes the IsUnspendable() test and all but the first
1355     // byte passes the IsPushOnly() test we don't care what exactly is in the
1356     // script.
1357     if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1358         typeRet = TX_NULL_DATA;
1359         return true;
1360     }
1361
1362     // Scan templates
1363     const CScript& script1 = scriptPubKey;
1364     BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1365     {
1366         const CScript& script2 = tplate.second;
1367         vSolutionsRet.clear();
1368
1369         opcodetype opcode1, opcode2;
1370         vector<unsigned char> vch1, vch2;
1371
1372         // Compare
1373         CScript::const_iterator pc1 = script1.begin();
1374         CScript::const_iterator pc2 = script2.begin();
1375         for ( ; ; )
1376         {
1377             if (pc1 == script1.end() && pc2 == script2.end())
1378             {
1379                 // Found a match
1380                 typeRet = tplate.first;
1381                 if (typeRet == TX_MULTISIG)
1382                 {
1383                     // Additional checks for TX_MULTISIG:
1384                     unsigned char m = vSolutionsRet.front()[0];
1385                     unsigned char n = vSolutionsRet.back()[0];
1386                     if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1387                         return false;
1388                 }
1389                 return true;
1390             }
1391             if (!script1.GetOp(pc1, opcode1, vch1))
1392                 break;
1393             if (!script2.GetOp(pc2, opcode2, vch2))
1394                 break;
1395
1396             // Template matching opcodes:
1397             if (opcode2 == OP_PUBKEYS)
1398             {
1399                 while (vch1.size() >= 33 && vch1.size() <= 120)
1400                 {
1401                     vSolutionsRet.push_back(vch1);
1402                     if (!script1.GetOp(pc1, opcode1, vch1))
1403                         break;
1404                 }
1405                 if (!script2.GetOp(pc2, opcode2, vch2))
1406                     break;
1407                 // Normal situation is to fall through
1408                 // to other if/else statements
1409             }
1410
1411             if (opcode2 == OP_PUBKEY)
1412             {
1413                 if (vch1.size() < 33 || vch1.size() > 120)
1414                     break;
1415                 vSolutionsRet.push_back(vch1);
1416             }
1417             else if (opcode2 == OP_PUBKEYHASH)
1418             {
1419                 if (vch1.size() != sizeof(uint160))
1420                     break;
1421                 vSolutionsRet.push_back(vch1);
1422             }
1423             else if (opcode2 == OP_SMALLINTEGER)
1424             {   // Single-byte small integer pushed onto vSolutions
1425                 if (opcode1 == OP_0 ||
1426                     (opcode1 >= OP_1 && opcode1 <= OP_16))
1427                 {
1428                     char n = (char)CScript::DecodeOP_N(opcode1);
1429                     vSolutionsRet.push_back(valtype(1, n));
1430                 }
1431                 else
1432                     break;
1433             }
1434             else if (opcode2 == OP_INTEGER)
1435             {   // Up to four-byte integer pushed onto vSolutions
1436                 try
1437                 {
1438                     CBigNum bnVal = CastToBigNum(vch1);
1439                     if (bnVal <= 16)
1440                         break; // It's better to use OP_0 ... OP_16 for small integers.
1441                     vSolutionsRet.push_back(vch1);
1442                 }
1443                 catch(...)
1444                 {
1445                     break;
1446                 }
1447             }
1448             else if (opcode2 == OP_SMALLDATA)
1449             {
1450                 // small pushdata, <= 1024 bytes
1451                 if (vch1.size() > 1024)
1452                     break;
1453             }
1454             else if (opcode1 != opcode2 || vch1 != vch2)
1455             {
1456                 // Others must match exactly
1457                 break;
1458             }
1459         }
1460     }
1461
1462     vSolutionsRet.clear();
1463     typeRet = TX_NONSTANDARD;
1464     return false;
1465 }
1466
1467
1468 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1469 {
1470     CKey key;
1471     if (!keystore.GetKey(address, key))
1472         return false;
1473
1474     vector<unsigned char> vchSig;
1475     if (!key.Sign(hash, vchSig))
1476         return false;
1477     vchSig.push_back((unsigned char)nHashType);
1478     scriptSigRet << vchSig;
1479
1480     return true;
1481 }
1482
1483 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1484 {
1485     CKey key;
1486     if (!keystore.CreatePrivKey(pubKey, R, key))
1487         return false;
1488
1489     vector<unsigned char> vchSig;
1490     if (!key.Sign(hash, vchSig))
1491         return false;
1492     vchSig.push_back((unsigned char)nHashType);
1493     scriptSigRet << vchSig;
1494
1495     return true;
1496 }
1497
1498 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1499 {
1500     int nSigned = 0;
1501     int nRequired = multisigdata.front()[0];
1502     for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1503     {
1504         const valtype& pubkey = multisigdata[i];
1505         CKeyID keyID = CPubKey(pubkey).GetID();
1506         if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1507             ++nSigned;
1508     }
1509     return nSigned==nRequired;
1510 }
1511
1512 //
1513 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1514 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1515 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1516 // Returns false if scriptPubKey could not be completely satisfied.
1517 //
1518 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1519                   CScript& scriptSigRet, txnouttype& whichTypeRet)
1520 {
1521     scriptSigRet.clear();
1522
1523     vector<valtype> vSolutions;
1524     if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1525         return false;
1526
1527     CKeyID keyID;
1528     switch (whichTypeRet)
1529     {
1530     case TX_NONSTANDARD:
1531     case TX_NULL_DATA:
1532         return false;
1533     case TX_PUBKEY:
1534         keyID = CPubKey(vSolutions[0]).GetID();
1535         return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1536     case TX_PUBKEY_DROP:
1537         {
1538             CPubKey key = CPubKey(vSolutions[0]);
1539             CPubKey R = CPubKey(vSolutions[1]);
1540             return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1541         }
1542     case TX_PUBKEYHASH:
1543         keyID = CKeyID(uint160(vSolutions[0]));
1544         if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1545             return false;
1546         else
1547         {
1548             CPubKey vch;
1549             keystore.GetPubKey(keyID, vch);
1550             scriptSigRet << vch;
1551         }
1552         return true;
1553     case TX_SCRIPTHASH:
1554         return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1555
1556     case TX_MULTISIG:
1557         scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1558         return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1559     }
1560     return false;
1561 }
1562
1563 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1564 {
1565     switch (t)
1566     {
1567     case TX_NONSTANDARD:
1568         return -1;
1569     case TX_NULL_DATA:
1570         return 1;
1571     case TX_PUBKEY:
1572     case TX_PUBKEY_DROP:
1573         return 1;
1574     case TX_PUBKEYHASH:
1575         return 2;
1576     case TX_MULTISIG:
1577         if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1578             return -1;
1579         return vSolutions[0][0] + 1;
1580     case TX_SCRIPTHASH:
1581         return 1; // doesn't include args needed by the script
1582     }
1583     return -1;
1584 }
1585
1586 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1587 {
1588     vector<valtype> vSolutions;
1589     if (!Solver(scriptPubKey, whichType, vSolutions))
1590         return false;
1591
1592     if (whichType == TX_MULTISIG)
1593     {
1594         unsigned char m = vSolutions.front()[0];
1595         unsigned char n = vSolutions.back()[0];
1596         // Support up to x-of-3 multisig txns as standard
1597         if (n < 1 || n > 3)
1598             return false;
1599         if (m < 1 || m > n)
1600             return false;
1601     }
1602
1603     return whichType != TX_NONSTANDARD;
1604 }
1605
1606
1607 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1608 {
1609     unsigned int nResult = 0;
1610     BOOST_FOREACH(const valtype& pubkey, pubkeys)
1611     {
1612         CKeyID keyID = CPubKey(pubkey).GetID();
1613         if (keystore.HaveKey(keyID))
1614             ++nResult;
1615     }
1616     return nResult;
1617 }
1618
1619
1620 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1621 {
1622 private:
1623     const CKeyStore *keystore;
1624 public:
1625     CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1626     bool operator()(const CNoDestination &dest) const { return false; }
1627     bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1628     bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1629 };
1630
1631 /*
1632 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1633 {
1634     CScript script;
1635     script.SetDestination(dest);
1636     return IsMine(keystore, script);
1637 }*/
1638
1639 isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
1640 {
1641     CScript script;
1642     script.SetAddress(dest);
1643     return IsMine(keystore, script);
1644 }
1645
1646 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1647 {
1648     vector<valtype> vSolutions;
1649     txnouttype whichType;
1650     if (!Solver(scriptPubKey, whichType, vSolutions)) {
1651         if (keystore.HaveWatchOnly(scriptPubKey))
1652             return MINE_WATCH_ONLY;
1653         return MINE_NO;
1654     }
1655
1656     CKeyID keyID;
1657     switch (whichType)
1658     {
1659     case TX_NONSTANDARD:
1660     case TX_NULL_DATA:
1661         break;
1662     case TX_PUBKEY:
1663         keyID = CPubKey(vSolutions[0]).GetID();
1664         if (keystore.HaveKey(keyID))
1665             return MINE_SPENDABLE;
1666         break;
1667     case TX_PUBKEY_DROP:
1668         {
1669             CPubKey key = CPubKey(vSolutions[0]);
1670             CPubKey R = CPubKey(vSolutions[1]);
1671             if (keystore.CheckOwnership(key, R))
1672                 return MINE_SPENDABLE;
1673         }
1674         break;
1675     case TX_PUBKEYHASH:
1676         keyID = CKeyID(uint160(vSolutions[0]));
1677         if (keystore.HaveKey(keyID))
1678             return MINE_SPENDABLE;
1679         break;
1680     case TX_SCRIPTHASH:
1681     {
1682         CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1683         CScript subscript;
1684         if (keystore.GetCScript(scriptID, subscript)) {
1685             isminetype ret = IsMine(keystore, subscript);
1686             if (ret == MINE_SPENDABLE)
1687                 return ret;
1688         }
1689         break;
1690     }
1691     case TX_MULTISIG:
1692     {
1693         // Only consider transactions "mine" if we own ALL the
1694         // keys involved. multi-signature transactions that are
1695         // partially owned (somebody else has a key that can spend
1696         // them) enable spend-out-from-under-you attacks, especially
1697         // in shared-wallet situations.
1698         vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1699         if (HaveKeys(keys, keystore) == keys.size())
1700             return MINE_SPENDABLE;
1701         break;
1702     }
1703     }
1704
1705     if (keystore.HaveWatchOnly(scriptPubKey))
1706         return MINE_WATCH_ONLY;
1707     return MINE_NO;
1708 }
1709
1710 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1711 {
1712     vector<valtype> vSolutions;
1713     txnouttype whichType;
1714     if (!Solver(scriptPubKey, whichType, vSolutions))
1715         return false;
1716
1717     if (whichType == TX_PUBKEY)
1718     {
1719         addressRet = CPubKey(vSolutions[0]).GetID();
1720         return true;
1721     }
1722     else if (whichType == TX_PUBKEYHASH)
1723     {
1724         addressRet = CKeyID(uint160(vSolutions[0]));
1725         return true;
1726     }
1727     else if (whichType == TX_SCRIPTHASH)
1728     {
1729         addressRet = CScriptID(uint160(vSolutions[0]));
1730         return true;
1731     }
1732     // Multisig txns have more than one address...
1733     return false;
1734 }
1735
1736 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1737 {
1738     vector<valtype> vSolutions;
1739     txnouttype whichType;
1740     if (!Solver(scriptPubKey, whichType, vSolutions))
1741         return false;
1742
1743     if (whichType == TX_PUBKEY)
1744     {
1745         addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
1746         return true;
1747     }
1748     if (whichType == TX_PUBKEY_DROP)
1749     {
1750         // Pay-to-Pubkey-R
1751         CMalleableKeyView view;
1752         if (!keystore.CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
1753             return false;
1754
1755         addressRet = CBitcoinAddress(view.GetMalleablePubKey());
1756         return true;
1757     }
1758     else if (whichType == TX_PUBKEYHASH)
1759     {
1760         addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
1761         return true;
1762     }
1763     else if (whichType == TX_SCRIPTHASH)
1764     {
1765         addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
1766         return true;
1767     }
1768     // Multisig txns have more than one address...
1769     return false;
1770 }
1771
1772 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1773 private:
1774     const CKeyStore &keystore;
1775     CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1776     std::vector<CKeyID> &vKeys;
1777
1778 public:
1779     CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1780
1781     void Process(const CScript &script) {
1782         txnouttype type;
1783         std::vector<CTxDestination> vDest;
1784         int nRequired;
1785         if (ExtractDestinations(script, type, vDest, nRequired)) {
1786             BOOST_FOREACH(const CTxDestination &dest, vDest)
1787                 boost::apply_visitor(*this, dest);
1788         }
1789     }
1790
1791     void operator()(const CKeyID &keyId) {
1792         if (keystore.HaveKey(keyId))
1793             vKeys.push_back(keyId);
1794     }
1795
1796     void operator()(const CScriptID &scriptId) {
1797         CScript script;
1798         if (keystore.GetCScript(scriptId, script))
1799             Process(script);
1800     }
1801
1802     void operator()(const CNoDestination &none) {}
1803 };
1804
1805
1806 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1807     CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1808 }
1809
1810 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1811 {
1812     addressRet.clear();
1813     typeRet = TX_NONSTANDARD;
1814     vector<valtype> vSolutions;
1815     if (!Solver(scriptPubKey, typeRet, vSolutions))
1816         return false;
1817     if (typeRet == TX_NULL_DATA)
1818     {
1819         nRequiredRet = 0;
1820         return true;
1821     }
1822
1823     if (typeRet == TX_MULTISIG)
1824     {
1825         nRequiredRet = vSolutions.front()[0];
1826         for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1827         {
1828             CTxDestination address = CPubKey(vSolutions[i]).GetID();
1829             addressRet.push_back(address);
1830         }
1831     }
1832     else
1833     {
1834         nRequiredRet = 1;
1835         if (typeRet == TX_PUBKEY_DROP)
1836             return true;
1837         CTxDestination address;
1838         if (!ExtractDestination(scriptPubKey, address))
1839            return false;
1840         addressRet.push_back(address);
1841     }
1842
1843     return true;
1844 }
1845
1846 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1847                   unsigned int flags, int nHashType)
1848 {
1849     vector<vector<unsigned char> > stack, stackCopy;
1850     if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1851         return false;
1852     if (flags & SCRIPT_VERIFY_P2SH)
1853         stackCopy = stack;
1854     if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1855         return false;
1856     if (stack.empty())
1857         return false;
1858
1859     if (CastToBool(stack.back()) == false)
1860         return false;
1861
1862     // Additional validation for spend-to-script-hash transactions:
1863     if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1864     {
1865         if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1866             return false;            // or validation fails
1867
1868         // stackCopy cannot be empty here, because if it was the
1869         // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
1870         // an empty stack and the EvalScript above would return false.
1871         assert(!stackCopy.empty());
1872
1873         const valtype& pubKeySerialized = stackCopy.back();
1874         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1875         popstack(stackCopy);
1876
1877         if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1878             return false;
1879         if (stackCopy.empty())
1880             return false;
1881         return CastToBool(stackCopy.back());
1882     }
1883
1884     return true;
1885 }
1886
1887 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1888 {
1889     assert(nIn < txTo.vin.size());
1890     CTxIn& txin = txTo.vin[nIn];
1891
1892     // Leave out the signature from the hash, since a signature can't sign itself.
1893     // The checksig op will also drop the signatures from its hash.
1894     uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1895
1896     txnouttype whichType;
1897     if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1898         return false;
1899
1900     if (whichType == TX_SCRIPTHASH)
1901     {
1902         // Solver returns the subscript that need to be evaluated;
1903         // the final scriptSig is the signatures from that
1904         // and then the serialized subscript:
1905         CScript subscript = txin.scriptSig;
1906
1907         // Recompute txn hash using subscript in place of scriptPubKey:
1908         uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1909
1910         txnouttype subType;
1911         bool fSolved =
1912             Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1913         // Append serialized subscript whether or not it is completely signed:
1914         txin.scriptSig << static_cast<valtype>(subscript);
1915         if (!fSolved) return false;
1916     }
1917
1918     // Test solution
1919     return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1920 }
1921
1922 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1923 {
1924     assert(nIn < txTo.vin.size());
1925     CTxIn& txin = txTo.vin[nIn];
1926     assert(txin.prevout.n < txFrom.vout.size());
1927     assert(txin.prevout.hash == txFrom.GetHash());
1928     const CTxOut& txout = txFrom.vout[txin.prevout.n];
1929
1930     return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1931 }
1932
1933 static CScript PushAll(const vector<valtype>& values)
1934 {
1935     CScript result;
1936     BOOST_FOREACH(const valtype& v, values)
1937         result << v;
1938     return result;
1939 }
1940
1941 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1942                                const vector<valtype>& vSolutions,
1943                                vector<valtype>& sigs1, vector<valtype>& sigs2)
1944 {
1945     // Combine all the signatures we've got:
1946     set<valtype> allsigs;
1947     BOOST_FOREACH(const valtype& v, sigs1)
1948     {
1949         if (!v.empty())
1950             allsigs.insert(v);
1951     }
1952     BOOST_FOREACH(const valtype& v, sigs2)
1953     {
1954         if (!v.empty())
1955             allsigs.insert(v);
1956     }
1957
1958     // Build a map of pubkey -> signature by matching sigs to pubkeys:
1959     assert(vSolutions.size() > 1);
1960     unsigned int nSigsRequired = vSolutions.front()[0];
1961     unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1962     map<valtype, valtype> sigs;
1963     BOOST_FOREACH(const valtype& sig, allsigs)
1964     {
1965         for (unsigned int i = 0; i < nPubKeys; i++)
1966         {
1967             const valtype& pubkey = vSolutions[i+1];
1968             if (sigs.count(pubkey))
1969                 continue; // Already got a sig for this pubkey
1970
1971             if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1972             {
1973                 sigs[pubkey] = sig;
1974                 break;
1975             }
1976         }
1977     }
1978     // Now build a merged CScript:
1979     unsigned int nSigsHave = 0;
1980     CScript result; result << OP_0; // pop-one-too-many workaround
1981     for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1982     {
1983         if (sigs.count(vSolutions[i+1]))
1984         {
1985             result << sigs[vSolutions[i+1]];
1986             ++nSigsHave;
1987         }
1988     }
1989     // Fill any missing with OP_0:
1990     for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1991         result << OP_0;
1992
1993     return result;
1994 }
1995
1996 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1997                                  const txnouttype txType, const vector<valtype>& vSolutions,
1998                                  vector<valtype>& sigs1, vector<valtype>& sigs2)
1999 {
2000     switch (txType)
2001     {
2002     case TX_NONSTANDARD:
2003     case TX_NULL_DATA:
2004         // Don't know anything about this, assume bigger one is correct:
2005         if (sigs1.size() >= sigs2.size())
2006             return PushAll(sigs1);
2007         return PushAll(sigs2);
2008     case TX_PUBKEY:
2009     case TX_PUBKEY_DROP:
2010     case TX_PUBKEYHASH:
2011         // Signatures are bigger than placeholders or empty scripts:
2012         if (sigs1.empty() || sigs1[0].empty())
2013             return PushAll(sigs2);
2014         return PushAll(sigs1);
2015     case TX_SCRIPTHASH:
2016         if (sigs1.empty() || sigs1.back().empty())
2017             return PushAll(sigs2);
2018         else if (sigs2.empty() || sigs2.back().empty())
2019             return PushAll(sigs1);
2020         else
2021         {
2022             // Recur to combine:
2023             valtype spk = sigs1.back();
2024             CScript pubKey2(spk.begin(), spk.end());
2025
2026             txnouttype txType2;
2027             vector<vector<unsigned char> > vSolutions2;
2028             Solver(pubKey2, txType2, vSolutions2);
2029             sigs1.pop_back();
2030             sigs2.pop_back();
2031             CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
2032             result << spk;
2033             return result;
2034         }
2035     case TX_MULTISIG:
2036         return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
2037     }
2038
2039     return CScript();
2040 }
2041
2042 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
2043                           const CScript& scriptSig1, const CScript& scriptSig2)
2044 {
2045     txnouttype txType;
2046     vector<vector<unsigned char> > vSolutions;
2047     Solver(scriptPubKey, txType, vSolutions);
2048
2049     vector<valtype> stack1;
2050     EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2051     vector<valtype> stack2;
2052     EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2053
2054     return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
2055 }
2056
2057 unsigned int CScript::GetSigOpCount(bool fAccurate) const
2058 {
2059     unsigned int n = 0;
2060     const_iterator pc = begin();
2061     opcodetype lastOpcode = OP_INVALIDOPCODE;
2062     while (pc < end())
2063     {
2064         opcodetype opcode;
2065         if (!GetOp(pc, opcode))
2066             break;
2067         if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
2068             n++;
2069         else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
2070         {
2071             if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
2072                 n += DecodeOP_N(lastOpcode);
2073             else
2074                 n += 20;
2075         }
2076         lastOpcode = opcode;
2077     }
2078     return n;
2079 }
2080
2081 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
2082 {
2083     if (!IsPayToScriptHash())
2084         return GetSigOpCount(true);
2085
2086     // This is a pay-to-script-hash scriptPubKey;
2087     // get the last item that the scriptSig
2088     // pushes onto the stack:
2089     const_iterator pc = scriptSig.begin();
2090     vector<unsigned char> data;
2091     while (pc < scriptSig.end())
2092     {
2093         opcodetype opcode;
2094         if (!scriptSig.GetOp(pc, opcode, data))
2095             return 0;
2096         if (opcode > OP_16)
2097             return 0;
2098     }
2099
2100     /// ... and return its opcount:
2101     CScript subscript(data.begin(), data.end());
2102     return subscript.GetSigOpCount(true);
2103 }
2104
2105 bool CScript::IsPayToScriptHash() const
2106 {
2107     // Extra-fast test for pay-to-script-hash CScripts:
2108     return (this->size() == 23 &&
2109             this->at(0) == OP_HASH160 &&
2110             this->at(1) == 0x14 &&
2111             this->at(22) == OP_EQUAL);
2112 }
2113
2114 bool CScript::HasCanonicalPushes() const
2115 {
2116     const_iterator pc = begin();
2117     while (pc < end())
2118     {
2119         opcodetype opcode;
2120         std::vector<unsigned char> data;
2121         if (!GetOp(pc, opcode, data))
2122             return false;
2123         if (opcode > OP_16)
2124             continue;
2125         if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2126             // Could have used an OP_n code, rather than a 1-byte push.
2127             return false;
2128         if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2129             // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2130             return false;
2131         if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2132             // Could have used an OP_PUSHDATA1.
2133             return false;
2134         if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2135             // Could have used an OP_PUSHDATA2.
2136             return false;
2137     }
2138     return true;
2139 }
2140
2141 class CScriptVisitor : public boost::static_visitor<bool>
2142 {
2143 private:
2144     CScript *script;
2145 public:
2146     CScriptVisitor(CScript *scriptin) { script = scriptin; }
2147
2148     bool operator()(const CNoDestination &dest) const {
2149         script->clear();
2150         return false;
2151     }
2152
2153     bool operator()(const CKeyID &keyID) const {
2154         script->clear();
2155         *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2156         return true;
2157     }
2158
2159     bool operator()(const CScriptID &scriptID) const {
2160         script->clear();
2161         *script << OP_HASH160 << scriptID << OP_EQUAL;
2162         return true;
2163     }
2164 };
2165
2166 void CScript::SetDestination(const CTxDestination& dest)
2167 {
2168     boost::apply_visitor(CScriptVisitor(this), dest);
2169 }
2170
2171 void CScript::SetAddress(const CBitcoinAddress& dest)
2172 {
2173     this->clear();
2174     if (dest.IsScript())
2175         *this << OP_HASH160 << dest.GetData() << OP_EQUAL;
2176     else if (dest.IsPubKey())
2177         *this << OP_DUP << OP_HASH160 << dest.GetData() << OP_EQUALVERIFY << OP_CHECKSIG;
2178     else if (dest.IsPair()) {
2179         // Pubkey pair address, going to generate
2180         //   new one-time public key.
2181         CMalleablePubKey mpk;
2182         if (!mpk.setvch(dest.GetData()))
2183             return;
2184         CPubKey R, pubKeyVariant;
2185         mpk.GetVariant(R, pubKeyVariant);
2186         *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2187     }
2188 }
2189
2190 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
2191 {
2192     this->clear();
2193
2194     *this << EncodeOP_N(nRequired);
2195     BOOST_FOREACH(const CPubKey& key, keys)
2196         *this << key;
2197     *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;
2198 }