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