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