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