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);
21 bool CastToBool(const valtype& vch)
23 return (CBigNum(vch) != bnZero);
26 void MakeSameSize(valtype& vch1, valtype& vch2)
28 // Lengthen the shorter one
29 if (vch1.size() < vch2.size())
30 vch1.resize(vch2.size(), 0);
31 if (vch2.size() < vch1.size())
32 vch2.resize(vch1.size(), 0);
38 // Script is a stack machine (like Forth) that evaluates a predicate
39 // returning a bool indicating valid or not. There are no loops.
41 #define stacktop(i) (stack.at(stack.size()+(i)))
42 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
44 bool EvalScript(const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType,
45 vector<vector<unsigned char> >* pvStackRet)
48 CScript::const_iterator pc = script.begin();
49 CScript::const_iterator pend = script.end();
50 CScript::const_iterator pbegincodehash = script.begin();
52 vector<valtype> stack;
53 vector<valtype> altstack;
60 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
67 if (!script.GetOp(pc, opcode, vchPushValue))
70 if (fExec && opcode <= OP_PUSHDATA4)
71 stack.push_back(vchPushValue);
72 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
97 CBigNum bn((int)opcode - (int)(OP_1 - 1));
98 stack.push_back(bn.getvch());
112 stack.push_back(bn.getvch());
121 // <expression> if [statements] [else [statements]] endif
125 if (stack.size() < 1)
127 valtype& vch = stacktop(-1);
128 if (opcode == OP_VERIF || opcode == OP_VERNOTIF)
129 fValue = (CBigNum(VERSION) >= CBigNum(vch));
131 fValue = CastToBool(vch);
132 if (opcode == OP_NOTIF || opcode == OP_VERNOTIF)
136 vfExec.push_back(fValue);
144 vfExec.back() = !vfExec.back();
159 // (false -- false) and return
160 if (stack.size() < 1)
162 bool fValue = CastToBool(stacktop(-1));
182 if (stack.size() < 1)
184 altstack.push_back(stacktop(-1));
189 case OP_FROMALTSTACK:
191 if (altstack.size() < 1)
193 stack.push_back(altstacktop(-1));
208 // (x1 x2 -- x1 x2 x1 x2)
209 if (stack.size() < 2)
211 valtype vch1 = stacktop(-2);
212 valtype vch2 = stacktop(-1);
213 stack.push_back(vch1);
214 stack.push_back(vch2);
220 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
221 if (stack.size() < 3)
223 valtype vch1 = stacktop(-3);
224 valtype vch2 = stacktop(-2);
225 valtype vch3 = stacktop(-1);
226 stack.push_back(vch1);
227 stack.push_back(vch2);
228 stack.push_back(vch3);
234 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
235 if (stack.size() < 4)
237 valtype vch1 = stacktop(-4);
238 valtype vch2 = stacktop(-3);
239 stack.push_back(vch1);
240 stack.push_back(vch2);
246 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
247 if (stack.size() < 6)
249 valtype vch1 = stacktop(-6);
250 valtype vch2 = stacktop(-5);
251 stack.erase(stack.end()-6, stack.end()-4);
252 stack.push_back(vch1);
253 stack.push_back(vch2);
259 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
260 if (stack.size() < 4)
262 swap(stacktop(-4), stacktop(-2));
263 swap(stacktop(-3), stacktop(-1));
270 if (stack.size() < 1)
272 valtype vch = stacktop(-1);
274 stack.push_back(vch);
281 CBigNum bn(stack.size());
282 stack.push_back(bn.getvch());
289 if (stack.size() < 1)
298 if (stack.size() < 1)
300 valtype vch = stacktop(-1);
301 stack.push_back(vch);
308 if (stack.size() < 2)
310 stack.erase(stack.end() - 2);
316 // (x1 x2 -- x1 x2 x1)
317 if (stack.size() < 2)
319 valtype vch = stacktop(-2);
320 stack.push_back(vch);
327 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
328 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
329 if (stack.size() < 2)
331 int n = CBigNum(stacktop(-1)).getint();
333 if (n < 0 || n >= stack.size())
335 valtype vch = stacktop(-n-1);
336 if (opcode == OP_ROLL)
337 stack.erase(stack.end()-n-1);
338 stack.push_back(vch);
344 // (x1 x2 x3 -- x2 x3 x1)
345 // x2 x1 x3 after first swap
346 // x2 x3 x1 after second swap
347 if (stack.size() < 3)
349 swap(stacktop(-3), stacktop(-2));
350 swap(stacktop(-2), stacktop(-1));
357 if (stack.size() < 2)
359 swap(stacktop(-2), stacktop(-1));
365 // (x1 x2 -- x2 x1 x2)
366 if (stack.size() < 2)
368 valtype vch = stacktop(-1);
369 stack.insert(stack.end()-2, vch);
380 if (stack.size() < 2)
382 valtype& vch1 = stacktop(-2);
383 valtype& vch2 = stacktop(-1);
384 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
391 // (in begin size -- out)
392 if (stack.size() < 3)
394 valtype& vch = stacktop(-3);
395 int nBegin = CBigNum(stacktop(-2)).getint();
396 int nEnd = nBegin + CBigNum(stacktop(-1)).getint();
397 if (nBegin < 0 || nEnd < nBegin)
399 if (nBegin > vch.size())
401 if (nEnd > vch.size())
403 vch.erase(vch.begin() + nEnd, vch.end());
404 vch.erase(vch.begin(), vch.begin() + nBegin);
414 if (stack.size() < 2)
416 valtype& vch = stacktop(-2);
417 int nSize = CBigNum(stacktop(-1)).getint();
420 if (nSize > vch.size())
422 if (opcode == OP_LEFT)
423 vch.erase(vch.begin() + nSize, vch.end());
425 vch.erase(vch.begin(), vch.end() - nSize);
433 if (stack.size() < 1)
435 CBigNum bn(stacktop(-1).size());
436 stack.push_back(bn.getvch());
447 if (stack.size() < 1)
449 valtype& vch = stacktop(-1);
450 for (int i = 0; i < vch.size(); i++)
460 if (stack.size() < 2)
462 valtype& vch1 = stacktop(-2);
463 valtype& vch2 = stacktop(-1);
464 MakeSameSize(vch1, vch2);
465 if (opcode == OP_AND)
467 for (int i = 0; i < vch1.size(); i++)
470 else if (opcode == OP_OR)
472 for (int i = 0; i < vch1.size(); i++)
475 else if (opcode == OP_XOR)
477 for (int i = 0; i < vch1.size(); i++)
486 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
489 if (stack.size() < 2)
491 valtype& vch1 = stacktop(-2);
492 valtype& vch2 = stacktop(-1);
493 bool fEqual = (vch1 == vch2);
494 // OP_NOTEQUAL is disabled because it would be too easy to say
495 // something like n != 1 and have some wiseguy pass in 1 with extra
496 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
497 //if (opcode == OP_NOTEQUAL)
501 stack.push_back(fEqual ? vchTrue : vchFalse);
502 if (opcode == OP_EQUALVERIFY)
526 if (stack.size() < 1)
528 CBigNum bn(stacktop(-1));
531 case OP_1ADD: bn += bnOne; break;
532 case OP_1SUB: bn -= bnOne; break;
533 case OP_2MUL: bn <<= 1; break;
534 case OP_2DIV: bn >>= 1; break;
535 case OP_NEGATE: bn = -bn; break;
536 case OP_ABS: if (bn < bnZero) bn = -bn; break;
537 case OP_NOT: bn = (bn == bnZero); break;
538 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
541 stack.push_back(bn.getvch());
555 case OP_NUMEQUALVERIFY:
559 case OP_LESSTHANOREQUAL:
560 case OP_GREATERTHANOREQUAL:
565 if (stack.size() < 2)
567 CBigNum bn1(stacktop(-2));
568 CBigNum bn2(stacktop(-1));
581 if (!BN_mul(&bn, &bn1, &bn2, pctx))
586 if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
591 if (!BN_mod(&bn, &bn1, &bn2, pctx))
598 bn = bn1 << bn2.getulong();
604 bn = bn1 >> bn2.getulong();
607 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
608 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
609 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
610 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
611 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
612 case OP_LESSTHAN: bn = (bn1 < bn2); break;
613 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
614 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
615 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
616 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
617 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
621 stack.push_back(bn.getvch());
623 if (opcode == OP_NUMEQUALVERIFY)
625 if (CastToBool(stacktop(-1)))
635 // (x min max -- out)
636 if (stack.size() < 3)
638 CBigNum bn1(stacktop(-3));
639 CBigNum bn2(stacktop(-2));
640 CBigNum bn3(stacktop(-1));
641 bool fValue = (bn2 <= bn1 && bn1 < bn3);
645 stack.push_back(fValue ? vchTrue : vchFalse);
660 if (stack.size() < 1)
662 valtype& vch = stacktop(-1);
663 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
664 if (opcode == OP_RIPEMD160)
665 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
666 else if (opcode == OP_SHA1)
667 SHA1(&vch[0], vch.size(), &vchHash[0]);
668 else if (opcode == OP_SHA256)
669 SHA256(&vch[0], vch.size(), &vchHash[0]);
670 else if (opcode == OP_HASH160)
672 uint160 hash160 = Hash160(vch);
673 memcpy(&vchHash[0], &hash160, sizeof(hash160));
675 else if (opcode == OP_HASH256)
677 uint256 hash = Hash(vch.begin(), vch.end());
678 memcpy(&vchHash[0], &hash, sizeof(hash));
681 stack.push_back(vchHash);
685 case OP_CODESEPARATOR:
687 // Hash starts after the code separator
693 case OP_CHECKSIGVERIFY:
695 // (sig pubkey -- bool)
696 if (stack.size() < 2)
699 valtype& vchSig = stacktop(-2);
700 valtype& vchPubKey = stacktop(-1);
703 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
704 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
706 // Subset of script starting at the most recent codeseparator
707 CScript scriptCode(pbegincodehash, pend);
709 // Drop the signature, since there's no way for a signature to sign itself
710 scriptCode.FindAndDelete(CScript(vchSig));
712 bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
716 stack.push_back(fSuccess ? vchTrue : vchFalse);
717 if (opcode == OP_CHECKSIGVERIFY)
727 case OP_CHECKMULTISIG:
728 case OP_CHECKMULTISIGVERIFY:
730 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
733 if (stack.size() < i)
736 int nKeysCount = CBigNum(stacktop(-i)).getint();
741 if (stack.size() < i)
744 int nSigsCount = CBigNum(stacktop(-i)).getint();
745 if (nSigsCount < 0 || nSigsCount > nKeysCount)
749 if (stack.size() < i)
752 // Subset of script starting at the most recent codeseparator
753 CScript scriptCode(pbegincodehash, pend);
755 // Drop the signatures, since there's no way for a signature to sign itself
756 for (int k = 0; k < nSigsCount; k++)
758 valtype& vchSig = stacktop(-isig-k);
759 scriptCode.FindAndDelete(CScript(vchSig));
762 bool fSuccess = true;
763 while (fSuccess && nSigsCount > 0)
765 valtype& vchSig = stacktop(-isig);
766 valtype& vchPubKey = stacktop(-ikey);
769 if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
777 // If there are more signatures left than keys left,
778 // then too many signatures have failed
779 if (nSigsCount > nKeysCount)
785 stack.push_back(fSuccess ? vchTrue : vchFalse);
787 if (opcode == OP_CHECKMULTISIGVERIFY)
805 return (stack.empty() ? false : CastToBool(stack.back()));
818 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
820 if (nIn >= txTo.vin.size())
822 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
825 CTransaction txTmp(txTo);
827 // In case concatenating two scripts ends up with two codeseparators,
828 // or an extra one at the end, this prevents all those possible incompatibilities.
829 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
831 // Blank out other inputs' signatures
832 for (int i = 0; i < txTmp.vin.size(); i++)
833 txTmp.vin[i].scriptSig = CScript();
834 txTmp.vin[nIn].scriptSig = scriptCode;
836 // Blank out some of the outputs
837 if ((nHashType & 0x1f) == SIGHASH_NONE)
842 // Let the others update at will
843 for (int i = 0; i < txTmp.vin.size(); i++)
845 txTmp.vin[i].nSequence = 0;
847 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
849 // Only lockin the txout payee at same index as txin
850 unsigned int nOut = nIn;
851 if (nOut >= txTmp.vout.size())
853 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
856 txTmp.vout.resize(nOut+1);
857 for (int i = 0; i < nOut; i++)
858 txTmp.vout[i].SetNull();
860 // Let the others update at will
861 for (int i = 0; i < txTmp.vin.size(); i++)
863 txTmp.vin[i].nSequence = 0;
866 // Blank out other inputs completely, not recommended for open transactions
867 if (nHashType & SIGHASH_ANYONECANPAY)
869 txTmp.vin[0] = txTmp.vin[nIn];
873 // Serialize and hash
874 CDataStream ss(SER_GETHASH);
876 ss << txTmp << nHashType;
877 return Hash(ss.begin(), ss.end());
881 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
882 const CTransaction& txTo, unsigned int nIn, int nHashType)
885 if (!key.SetPubKey(vchPubKey))
888 // Hash type is one byte tacked on to the end of the signature
892 nHashType = vchSig.back();
893 else if (nHashType != vchSig.back())
897 if (key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig))
912 bool Solver(const CScript& scriptPubKey, vector<pair<opcodetype, valtype> >& vSolutionRet)
915 static vector<CScript> vTemplates;
916 if (vTemplates.empty())
918 // Standard tx, sender provides pubkey, receiver adds signature
919 vTemplates.push_back(CScript() << OP_PUBKEY << OP_CHECKSIG);
921 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
922 vTemplates.push_back(CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG);
926 const CScript& script1 = scriptPubKey;
927 foreach(const CScript& script2, vTemplates)
929 vSolutionRet.clear();
930 opcodetype opcode1, opcode2;
931 vector<unsigned char> vch1, vch2;
934 CScript::const_iterator pc1 = script1.begin();
935 CScript::const_iterator pc2 = script2.begin();
938 bool f1 = script1.GetOp(pc1, opcode1, vch1);
939 bool f2 = script2.GetOp(pc2, opcode2, vch2);
943 reverse(vSolutionRet.begin(), vSolutionRet.end());
950 else if (opcode2 == OP_PUBKEY)
952 if (vch1.size() <= sizeof(uint256))
954 vSolutionRet.push_back(make_pair(opcode2, vch1));
956 else if (opcode2 == OP_PUBKEYHASH)
958 if (vch1.size() != sizeof(uint160))
960 vSolutionRet.push_back(make_pair(opcode2, vch1));
962 else if (opcode1 != opcode2)
969 vSolutionRet.clear();
974 bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
976 scriptSigRet.clear();
978 vector<pair<opcodetype, valtype> > vSolution;
979 if (!Solver(scriptPubKey, vSolution))
983 CRITICAL_BLOCK(cs_mapKeys)
985 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
987 if (item.first == OP_PUBKEY)
990 const valtype& vchPubKey = item.second;
991 if (!mapKeys.count(vchPubKey))
995 vector<unsigned char> vchSig;
996 if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))
998 vchSig.push_back((unsigned char)nHashType);
999 scriptSigRet << vchSig;
1002 else if (item.first == OP_PUBKEYHASH)
1004 // Sign and give pubkey
1005 map<uint160, valtype>::iterator mi = mapPubKeys.find(uint160(item.second));
1006 if (mi == mapPubKeys.end())
1008 const vector<unsigned char>& vchPubKey = (*mi).second;
1009 if (!mapKeys.count(vchPubKey))
1013 vector<unsigned char> vchSig;
1014 if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))
1016 vchSig.push_back((unsigned char)nHashType);
1017 scriptSigRet << vchSig << vchPubKey;
1027 bool IsMine(const CScript& scriptPubKey)
1030 return Solver(scriptPubKey, 0, 0, scriptSig);
1034 bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned char>& vchPubKeyRet)
1036 vchPubKeyRet.clear();
1038 vector<pair<opcodetype, valtype> > vSolution;
1039 if (!Solver(scriptPubKey, vSolution))
1042 CRITICAL_BLOCK(cs_mapKeys)
1044 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1047 if (item.first == OP_PUBKEY)
1049 vchPubKey = item.second;
1051 else if (item.first == OP_PUBKEYHASH)
1053 map<uint160, valtype>::iterator mi = mapPubKeys.find(uint160(item.second));
1054 if (mi == mapPubKeys.end())
1056 vchPubKey = (*mi).second;
1058 if (!fMineOnly || mapKeys.count(vchPubKey))
1060 vchPubKeyRet = vchPubKey;
1069 bool ExtractHash160(const CScript& scriptPubKey, uint160& hash160Ret)
1073 vector<pair<opcodetype, valtype> > vSolution;
1074 if (!Solver(scriptPubKey, vSolution))
1077 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1079 if (item.first == OP_PUBKEYHASH)
1081 hash160Ret = uint160(item.second);
1089 bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
1091 assert(nIn < txTo.vin.size());
1092 CTxIn& txin = txTo.vin[nIn];
1093 assert(txin.prevout.n < txFrom.vout.size());
1094 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1096 // Leave out the signature from the hash, since a signature can't sign itself.
1097 // The checksig op will also drop the signatures from its hash.
1098 uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
1100 if (!Solver(txout.scriptPubKey, hash, nHashType, txin.scriptSig))
1103 txin.scriptSig = scriptPrereq + txin.scriptSig;
1106 if (scriptPrereq.empty())
1107 if (!EvalScript(txin.scriptSig + CScript(OP_CODESEPARATOR) + txout.scriptPubKey, txTo, nIn))
1114 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int nHashType)
1116 assert(nIn < txTo.vin.size());
1117 const CTxIn& txin = txTo.vin[nIn];
1118 if (txin.prevout.n >= txFrom.vout.size())
1120 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1122 if (txin.prevout.hash != txFrom.GetHash())
1125 if (!EvalScript(txin.scriptSig + CScript(OP_CODESEPARATOR) + txout.scriptPubKey, txTo, nIn, nHashType))
1128 // Anytime a signature is successfully verified, it's proof the outpoint is spent,
1129 // so lets update the wallet spent flag if it doesn't know due to wallet.dat being
1130 // restored from backup or the user making copies of wallet.dat.
1131 WalletUpdateSpent(txin.prevout);