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