1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
7 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
11 typedef vector<unsigned char> valtype;
12 static const valtype vchFalse(0);
13 static const valtype vchZero(0);
14 static const valtype vchTrue(1, 1);
15 static const CBigNum bnZero(0);
16 static const CBigNum bnOne(1);
17 static const CBigNum bnFalse(0);
18 static const CBigNum bnTrue(1);
19 static const size_t nMaxNumSize = 258;
22 bool CastToBool(const valtype& vch)
24 return (CBigNum(vch) != bnZero);
27 void MakeSameSize(valtype& vch1, valtype& vch2)
29 // Lengthen the shorter one
30 if (vch1.size() < vch2.size())
31 vch1.resize(vch2.size(), 0);
32 if (vch2.size() < vch1.size())
33 vch2.resize(vch1.size(), 0);
39 // Script is a stack machine (like Forth) that evaluates a predicate
40 // returning a bool indicating valid or not. There are no loops.
42 #define stacktop(i) (stack.at(stack.size()+(i)))
43 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
45 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
48 CScript::const_iterator pc = script.begin();
49 CScript::const_iterator pend = script.end();
50 CScript::const_iterator pbegincodehash = script.begin();
52 vector<valtype> altstack;
53 if (script.size() > 10000)
62 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
69 if (!script.GetOp(pc, opcode, vchPushValue))
71 if (vchPushValue.size() > 5000)
73 if (opcode > OP_16 && nOpCount++ > 200)
76 if (fExec && opcode <= OP_PUSHDATA4)
77 stack.push_back(vchPushValue);
78 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
103 CBigNum bn((int)opcode - (int)(OP_1 - 1));
104 stack.push_back(bn.getvch());
113 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
114 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
128 // <expression> if [statements] [else [statements]] endif
132 if (stack.size() < 1)
134 valtype& vch = stacktop(-1);
135 fValue = CastToBool(vch);
136 if (opcode == OP_NOTIF)
140 vfExec.push_back(fValue);
148 vfExec.back() = !vfExec.back();
163 // (false -- false) and return
164 if (stack.size() < 1)
166 bool fValue = CastToBool(stacktop(-1));
186 if (stack.size() < 1)
188 altstack.push_back(stacktop(-1));
193 case OP_FROMALTSTACK:
195 if (altstack.size() < 1)
197 stack.push_back(altstacktop(-1));
212 // (x1 x2 -- x1 x2 x1 x2)
213 if (stack.size() < 2)
215 valtype vch1 = stacktop(-2);
216 valtype vch2 = stacktop(-1);
217 stack.push_back(vch1);
218 stack.push_back(vch2);
224 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
225 if (stack.size() < 3)
227 valtype vch1 = stacktop(-3);
228 valtype vch2 = stacktop(-2);
229 valtype vch3 = stacktop(-1);
230 stack.push_back(vch1);
231 stack.push_back(vch2);
232 stack.push_back(vch3);
238 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
239 if (stack.size() < 4)
241 valtype vch1 = stacktop(-4);
242 valtype vch2 = stacktop(-3);
243 stack.push_back(vch1);
244 stack.push_back(vch2);
250 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
251 if (stack.size() < 6)
253 valtype vch1 = stacktop(-6);
254 valtype vch2 = stacktop(-5);
255 stack.erase(stack.end()-6, stack.end()-4);
256 stack.push_back(vch1);
257 stack.push_back(vch2);
263 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
264 if (stack.size() < 4)
266 swap(stacktop(-4), stacktop(-2));
267 swap(stacktop(-3), stacktop(-1));
274 if (stack.size() < 1)
276 valtype vch = stacktop(-1);
278 stack.push_back(vch);
285 CBigNum bn(stack.size());
286 stack.push_back(bn.getvch());
293 if (stack.size() < 1)
302 if (stack.size() < 1)
304 valtype vch = stacktop(-1);
305 stack.push_back(vch);
312 if (stack.size() < 2)
314 stack.erase(stack.end() - 2);
320 // (x1 x2 -- x1 x2 x1)
321 if (stack.size() < 2)
323 valtype vch = stacktop(-2);
324 stack.push_back(vch);
331 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
332 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
333 if (stack.size() < 2)
335 int n = CBigNum(stacktop(-1)).getint();
337 if (n < 0 || n >= stack.size())
339 valtype vch = stacktop(-n-1);
340 if (opcode == OP_ROLL)
341 stack.erase(stack.end()-n-1);
342 stack.push_back(vch);
348 // (x1 x2 x3 -- x2 x3 x1)
349 // x2 x1 x3 after first swap
350 // x2 x3 x1 after second swap
351 if (stack.size() < 3)
353 swap(stacktop(-3), stacktop(-2));
354 swap(stacktop(-2), stacktop(-1));
361 if (stack.size() < 2)
363 swap(stacktop(-2), stacktop(-1));
369 // (x1 x2 -- x2 x1 x2)
370 if (stack.size() < 2)
372 valtype vch = stacktop(-1);
373 stack.insert(stack.end()-2, vch);
384 if (stack.size() < 2)
386 valtype& vch1 = stacktop(-2);
387 valtype& vch2 = stacktop(-1);
388 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
390 if (stacktop(-1).size() > 5000)
397 // (in begin size -- out)
398 if (stack.size() < 3)
400 valtype& vch = stacktop(-3);
401 int nBegin = CBigNum(stacktop(-2)).getint();
402 int nEnd = nBegin + CBigNum(stacktop(-1)).getint();
403 if (nBegin < 0 || nEnd < nBegin)
405 if (nBegin > vch.size())
407 if (nEnd > vch.size())
409 vch.erase(vch.begin() + nEnd, vch.end());
410 vch.erase(vch.begin(), vch.begin() + nBegin);
420 if (stack.size() < 2)
422 valtype& vch = stacktop(-2);
423 int nSize = CBigNum(stacktop(-1)).getint();
426 if (nSize > vch.size())
428 if (opcode == OP_LEFT)
429 vch.erase(vch.begin() + nSize, vch.end());
431 vch.erase(vch.begin(), vch.end() - nSize);
439 if (stack.size() < 1)
441 CBigNum bn(stacktop(-1).size());
442 stack.push_back(bn.getvch());
453 if (stack.size() < 1)
455 valtype& vch = stacktop(-1);
456 for (int i = 0; i < vch.size(); i++)
466 if (stack.size() < 2)
468 valtype& vch1 = stacktop(-2);
469 valtype& vch2 = stacktop(-1);
470 MakeSameSize(vch1, vch2);
471 if (opcode == OP_AND)
473 for (int i = 0; i < vch1.size(); i++)
476 else if (opcode == OP_OR)
478 for (int i = 0; i < vch1.size(); i++)
481 else if (opcode == OP_XOR)
483 for (int i = 0; i < vch1.size(); i++)
492 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
495 if (stack.size() < 2)
497 valtype& vch1 = stacktop(-2);
498 valtype& vch2 = stacktop(-1);
499 bool fEqual = (vch1 == vch2);
500 // OP_NOTEQUAL is disabled because it would be too easy to say
501 // something like n != 1 and have some wiseguy pass in 1 with extra
502 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
503 //if (opcode == OP_NOTEQUAL)
507 stack.push_back(fEqual ? vchTrue : vchFalse);
508 if (opcode == OP_EQUALVERIFY)
532 if (stack.size() < 1)
534 if (stacktop(-1).size() > nMaxNumSize)
536 CBigNum bn(stacktop(-1));
539 case OP_1ADD: bn += bnOne; break;
540 case OP_1SUB: bn -= bnOne; break;
541 case OP_2MUL: bn <<= 1; break;
542 case OP_2DIV: bn >>= 1; break;
543 case OP_NEGATE: bn = -bn; break;
544 case OP_ABS: if (bn < bnZero) bn = -bn; break;
545 case OP_NOT: bn = (bn == bnZero); break;
546 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
549 stack.push_back(bn.getvch());
563 case OP_NUMEQUALVERIFY:
567 case OP_LESSTHANOREQUAL:
568 case OP_GREATERTHANOREQUAL:
573 if (stack.size() < 2)
575 if (stacktop(-2).size() > nMaxNumSize ||
576 stacktop(-1).size() > nMaxNumSize)
578 CBigNum bn1(stacktop(-2));
579 CBigNum bn2(stacktop(-1));
592 if (!BN_mul(&bn, &bn1, &bn2, pctx))
597 if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
602 if (!BN_mod(&bn, &bn1, &bn2, pctx))
607 if (bn2 < bnZero || bn2 > CBigNum(2048))
609 bn = bn1 << bn2.getulong();
613 if (bn2 < bnZero || bn2 > CBigNum(2048))
615 bn = bn1 >> bn2.getulong();
618 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
619 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
620 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
621 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
622 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
623 case OP_LESSTHAN: bn = (bn1 < bn2); break;
624 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
625 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
626 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
627 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
628 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
632 stack.push_back(bn.getvch());
634 if (opcode == OP_NUMEQUALVERIFY)
636 if (CastToBool(stacktop(-1)))
646 // (x min max -- out)
647 if (stack.size() < 3)
649 if (stacktop(-3).size() > nMaxNumSize ||
650 stacktop(-2).size() > nMaxNumSize ||
651 stacktop(-1).size() > nMaxNumSize)
653 CBigNum bn1(stacktop(-3));
654 CBigNum bn2(stacktop(-2));
655 CBigNum bn3(stacktop(-1));
656 bool fValue = (bn2 <= bn1 && bn1 < bn3);
660 stack.push_back(fValue ? vchTrue : vchFalse);
675 if (stack.size() < 1)
677 valtype& vch = stacktop(-1);
678 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
679 if (opcode == OP_RIPEMD160)
680 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
681 else if (opcode == OP_SHA1)
682 SHA1(&vch[0], vch.size(), &vchHash[0]);
683 else if (opcode == OP_SHA256)
684 SHA256(&vch[0], vch.size(), &vchHash[0]);
685 else if (opcode == OP_HASH160)
687 uint160 hash160 = Hash160(vch);
688 memcpy(&vchHash[0], &hash160, sizeof(hash160));
690 else if (opcode == OP_HASH256)
692 uint256 hash = Hash(vch.begin(), vch.end());
693 memcpy(&vchHash[0], &hash, sizeof(hash));
696 stack.push_back(vchHash);
700 case OP_CODESEPARATOR:
702 // Hash starts after the code separator
708 case OP_CHECKSIGVERIFY:
710 // (sig pubkey -- bool)
711 if (stack.size() < 2)
714 valtype& vchSig = stacktop(-2);
715 valtype& vchPubKey = stacktop(-1);
718 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
719 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
721 // Subset of script starting at the most recent codeseparator
722 CScript scriptCode(pbegincodehash, pend);
724 // Drop the signature, since there's no way for a signature to sign itself
725 scriptCode.FindAndDelete(CScript(vchSig));
727 bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
731 stack.push_back(fSuccess ? vchTrue : vchFalse);
732 if (opcode == OP_CHECKSIGVERIFY)
742 case OP_CHECKMULTISIG:
743 case OP_CHECKMULTISIGVERIFY:
745 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
748 if (stack.size() < i)
751 int nKeysCount = CBigNum(stacktop(-i)).getint();
756 if (stack.size() < i)
759 int nSigsCount = CBigNum(stacktop(-i)).getint();
760 if (nSigsCount < 0 || nSigsCount > nKeysCount)
764 if (stack.size() < i)
767 // Subset of script starting at the most recent codeseparator
768 CScript scriptCode(pbegincodehash, pend);
770 // Drop the signatures, since there's no way for a signature to sign itself
771 for (int k = 0; k < nSigsCount; k++)
773 valtype& vchSig = stacktop(-isig-k);
774 scriptCode.FindAndDelete(CScript(vchSig));
777 bool fSuccess = true;
778 while (fSuccess && nSigsCount > 0)
780 valtype& vchSig = stacktop(-isig);
781 valtype& vchPubKey = stacktop(-ikey);
784 if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
792 // If there are more signatures left than keys left,
793 // then too many signatures have failed
794 if (nSigsCount > nKeysCount)
800 stack.push_back(fSuccess ? vchTrue : vchFalse);
802 if (opcode == OP_CHECKMULTISIGVERIFY)
817 if (stack.size() + altstack.size() > 1000)
843 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
845 if (nIn >= txTo.vin.size())
847 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
850 CTransaction txTmp(txTo);
852 // In case concatenating two scripts ends up with two codeseparators,
853 // or an extra one at the end, this prevents all those possible incompatibilities.
854 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
856 // Blank out other inputs' signatures
857 for (int i = 0; i < txTmp.vin.size(); i++)
858 txTmp.vin[i].scriptSig = CScript();
859 txTmp.vin[nIn].scriptSig = scriptCode;
861 // Blank out some of the outputs
862 if ((nHashType & 0x1f) == SIGHASH_NONE)
867 // Let the others update at will
868 for (int i = 0; i < txTmp.vin.size(); i++)
870 txTmp.vin[i].nSequence = 0;
872 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
874 // Only lockin the txout payee at same index as txin
875 unsigned int nOut = nIn;
876 if (nOut >= txTmp.vout.size())
878 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
881 txTmp.vout.resize(nOut+1);
882 for (int i = 0; i < nOut; i++)
883 txTmp.vout[i].SetNull();
885 // Let the others update at will
886 for (int i = 0; i < txTmp.vin.size(); i++)
888 txTmp.vin[i].nSequence = 0;
891 // Blank out other inputs completely, not recommended for open transactions
892 if (nHashType & SIGHASH_ANYONECANPAY)
894 txTmp.vin[0] = txTmp.vin[nIn];
898 // Serialize and hash
899 CDataStream ss(SER_GETHASH);
901 ss << txTmp << nHashType;
902 return Hash(ss.begin(), ss.end());
906 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
907 const CTransaction& txTo, unsigned int nIn, int nHashType)
910 if (!key.SetPubKey(vchPubKey))
913 // Hash type is one byte tacked on to the end of the signature
917 nHashType = vchSig.back();
918 else if (nHashType != vchSig.back())
922 if (key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig))
937 bool Solver(const CScript& scriptPubKey, vector<pair<opcodetype, valtype> >& vSolutionRet)
940 static vector<CScript> vTemplates;
941 if (vTemplates.empty())
943 // Standard tx, sender provides pubkey, receiver adds signature
944 vTemplates.push_back(CScript() << OP_PUBKEY << OP_CHECKSIG);
946 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
947 vTemplates.push_back(CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG);
951 const CScript& script1 = scriptPubKey;
952 foreach(const CScript& script2, vTemplates)
954 vSolutionRet.clear();
955 opcodetype opcode1, opcode2;
956 vector<unsigned char> vch1, vch2;
959 CScript::const_iterator pc1 = script1.begin();
960 CScript::const_iterator pc2 = script2.begin();
963 bool f1 = script1.GetOp(pc1, opcode1, vch1);
964 bool f2 = script2.GetOp(pc2, opcode2, vch2);
968 reverse(vSolutionRet.begin(), vSolutionRet.end());
975 else if (opcode2 == OP_PUBKEY)
977 if (vch1.size() <= sizeof(uint256))
979 vSolutionRet.push_back(make_pair(opcode2, vch1));
981 else if (opcode2 == OP_PUBKEYHASH)
983 if (vch1.size() != sizeof(uint160))
985 vSolutionRet.push_back(make_pair(opcode2, vch1));
987 else if (opcode1 != opcode2)
994 vSolutionRet.clear();
999 bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
1001 scriptSigRet.clear();
1003 vector<pair<opcodetype, valtype> > vSolution;
1004 if (!Solver(scriptPubKey, vSolution))
1008 CRITICAL_BLOCK(cs_mapKeys)
1010 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1012 if (item.first == OP_PUBKEY)
1015 const valtype& vchPubKey = item.second;
1016 if (!mapKeys.count(vchPubKey))
1020 vector<unsigned char> vchSig;
1021 if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))
1023 vchSig.push_back((unsigned char)nHashType);
1024 scriptSigRet << vchSig;
1027 else if (item.first == OP_PUBKEYHASH)
1029 // Sign and give pubkey
1030 map<uint160, valtype>::iterator mi = mapPubKeys.find(uint160(item.second));
1031 if (mi == mapPubKeys.end())
1033 const vector<unsigned char>& vchPubKey = (*mi).second;
1034 if (!mapKeys.count(vchPubKey))
1038 vector<unsigned char> vchSig;
1039 if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))
1041 vchSig.push_back((unsigned char)nHashType);
1042 scriptSigRet << vchSig << vchPubKey;
1052 bool IsMine(const CScript& scriptPubKey)
1055 return Solver(scriptPubKey, 0, 0, scriptSig);
1059 bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned char>& vchPubKeyRet)
1061 vchPubKeyRet.clear();
1063 vector<pair<opcodetype, valtype> > vSolution;
1064 if (!Solver(scriptPubKey, vSolution))
1067 CRITICAL_BLOCK(cs_mapKeys)
1069 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1072 if (item.first == OP_PUBKEY)
1074 vchPubKey = item.second;
1076 else if (item.first == OP_PUBKEYHASH)
1078 map<uint160, valtype>::iterator mi = mapPubKeys.find(uint160(item.second));
1079 if (mi == mapPubKeys.end())
1081 vchPubKey = (*mi).second;
1083 if (!fMineOnly || mapKeys.count(vchPubKey))
1085 vchPubKeyRet = vchPubKey;
1094 bool ExtractHash160(const CScript& scriptPubKey, uint160& hash160Ret)
1098 vector<pair<opcodetype, valtype> > vSolution;
1099 if (!Solver(scriptPubKey, vSolution))
1102 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1104 if (item.first == OP_PUBKEYHASH)
1106 hash160Ret = uint160(item.second);
1114 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int nHashType)
1116 vector<vector<unsigned char> > stack;
1117 if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
1119 if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType))
1123 return CastToBool(stack.back());
1127 bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
1129 assert(nIn < txTo.vin.size());
1130 CTxIn& txin = txTo.vin[nIn];
1131 assert(txin.prevout.n < txFrom.vout.size());
1132 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1134 // Leave out the signature from the hash, since a signature can't sign itself.
1135 // The checksig op will also drop the signatures from its hash.
1136 uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
1138 if (!Solver(txout.scriptPubKey, hash, nHashType, txin.scriptSig))
1141 txin.scriptSig = scriptPrereq + txin.scriptSig;
1144 if (scriptPrereq.empty())
1145 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, 0))
1152 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int nHashType)
1154 assert(nIn < txTo.vin.size());
1155 const CTxIn& txin = txTo.vin[nIn];
1156 if (txin.prevout.n >= txFrom.vout.size())
1158 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1160 if (txin.prevout.hash != txFrom.GetHash())
1163 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nHashType))
1166 // Anytime a signature is successfully verified, it's proof the outpoint is spent,
1167 // so lets update the wallet spent flag if it doesn't know due to wallet.dat being
1168 // restored from backup or the user making copies of wallet.dat.
1169 WalletUpdateSpent(txin.prevout);