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