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