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