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 = 4;
22 CBigNum CastToBigNum(const valtype& vch)
24 if (vch.size() > nMaxNumSize)
25 throw runtime_error("CastToBigNum() : overflow");
26 // Get rid of extra leading zeros
27 return CBigNum(CBigNum(vch).getvch());
30 bool CastToBool(const valtype& vch)
32 for (int i = 0; i < vch.size(); i++)
36 // Can be negative zero
37 if (i == vch.size()-1 && vch[i] == 0x80)
45 void MakeSameSize(valtype& vch1, valtype& vch2)
47 // Lengthen the shorter one
48 if (vch1.size() < vch2.size())
49 vch1.resize(vch2.size(), 0);
50 if (vch2.size() < vch1.size())
51 vch2.resize(vch1.size(), 0);
57 // Script is a stack machine (like Forth) that evaluates a predicate
58 // returning a bool indicating valid or not. There are no loops.
60 #define stacktop(i) (stack.at(stack.size()+(i)))
61 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
63 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
66 CScript::const_iterator pc = script.begin();
67 CScript::const_iterator pend = script.end();
68 CScript::const_iterator pbegincodehash = script.begin();
70 vector<valtype> altstack;
71 if (script.size() > 10000)
80 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
87 if (!script.GetOp(pc, opcode, vchPushValue))
89 if (vchPushValue.size() > 520)
91 if (opcode > OP_16 && nOpCount++ > 200)
94 if (opcode == OP_CAT ||
95 opcode == OP_SUBSTR ||
98 opcode == OP_INVERT ||
107 opcode == OP_LSHIFT ||
111 if (fExec && opcode <= OP_PUSHDATA4)
112 stack.push_back(vchPushValue);
113 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
138 CBigNum bn((int)opcode - (int)(OP_1 - 1));
139 stack.push_back(bn.getvch());
148 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
149 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
163 // <expression> if [statements] [else [statements]] endif
167 if (stack.size() < 1)
169 valtype& vch = stacktop(-1);
170 fValue = CastToBool(vch);
171 if (opcode == OP_NOTIF)
175 vfExec.push_back(fValue);
183 vfExec.back() = !vfExec.back();
198 // (false -- false) and return
199 if (stack.size() < 1)
201 bool fValue = CastToBool(stacktop(-1));
221 if (stack.size() < 1)
223 altstack.push_back(stacktop(-1));
228 case OP_FROMALTSTACK:
230 if (altstack.size() < 1)
232 stack.push_back(altstacktop(-1));
247 // (x1 x2 -- x1 x2 x1 x2)
248 if (stack.size() < 2)
250 valtype vch1 = stacktop(-2);
251 valtype vch2 = stacktop(-1);
252 stack.push_back(vch1);
253 stack.push_back(vch2);
259 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
260 if (stack.size() < 3)
262 valtype vch1 = stacktop(-3);
263 valtype vch2 = stacktop(-2);
264 valtype vch3 = stacktop(-1);
265 stack.push_back(vch1);
266 stack.push_back(vch2);
267 stack.push_back(vch3);
273 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
274 if (stack.size() < 4)
276 valtype vch1 = stacktop(-4);
277 valtype vch2 = stacktop(-3);
278 stack.push_back(vch1);
279 stack.push_back(vch2);
285 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
286 if (stack.size() < 6)
288 valtype vch1 = stacktop(-6);
289 valtype vch2 = stacktop(-5);
290 stack.erase(stack.end()-6, stack.end()-4);
291 stack.push_back(vch1);
292 stack.push_back(vch2);
298 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
299 if (stack.size() < 4)
301 swap(stacktop(-4), stacktop(-2));
302 swap(stacktop(-3), stacktop(-1));
309 if (stack.size() < 1)
311 valtype vch = stacktop(-1);
313 stack.push_back(vch);
320 CBigNum bn(stack.size());
321 stack.push_back(bn.getvch());
328 if (stack.size() < 1)
337 if (stack.size() < 1)
339 valtype vch = stacktop(-1);
340 stack.push_back(vch);
347 if (stack.size() < 2)
349 stack.erase(stack.end() - 2);
355 // (x1 x2 -- x1 x2 x1)
356 if (stack.size() < 2)
358 valtype vch = stacktop(-2);
359 stack.push_back(vch);
366 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
367 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
368 if (stack.size() < 2)
370 int n = CastToBigNum(stacktop(-1)).getint();
372 if (n < 0 || n >= stack.size())
374 valtype vch = stacktop(-n-1);
375 if (opcode == OP_ROLL)
376 stack.erase(stack.end()-n-1);
377 stack.push_back(vch);
383 // (x1 x2 x3 -- x2 x3 x1)
384 // x2 x1 x3 after first swap
385 // x2 x3 x1 after second swap
386 if (stack.size() < 3)
388 swap(stacktop(-3), stacktop(-2));
389 swap(stacktop(-2), stacktop(-1));
396 if (stack.size() < 2)
398 swap(stacktop(-2), stacktop(-1));
404 // (x1 x2 -- x2 x1 x2)
405 if (stack.size() < 2)
407 valtype vch = stacktop(-1);
408 stack.insert(stack.end()-2, vch);
419 if (stack.size() < 2)
421 valtype& vch1 = stacktop(-2);
422 valtype& vch2 = stacktop(-1);
423 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
425 if (stacktop(-1).size() > 520)
432 // (in begin size -- out)
433 if (stack.size() < 3)
435 valtype& vch = stacktop(-3);
436 int nBegin = CastToBigNum(stacktop(-2)).getint();
437 int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
438 if (nBegin < 0 || nEnd < nBegin)
440 if (nBegin > vch.size())
442 if (nEnd > vch.size())
444 vch.erase(vch.begin() + nEnd, vch.end());
445 vch.erase(vch.begin(), vch.begin() + nBegin);
455 if (stack.size() < 2)
457 valtype& vch = stacktop(-2);
458 int nSize = CastToBigNum(stacktop(-1)).getint();
461 if (nSize > vch.size())
463 if (opcode == OP_LEFT)
464 vch.erase(vch.begin() + nSize, vch.end());
466 vch.erase(vch.begin(), vch.end() - nSize);
474 if (stack.size() < 1)
476 CBigNum bn(stacktop(-1).size());
477 stack.push_back(bn.getvch());
488 if (stack.size() < 1)
490 valtype& vch = stacktop(-1);
491 for (int i = 0; i < vch.size(); i++)
501 if (stack.size() < 2)
503 valtype& vch1 = stacktop(-2);
504 valtype& vch2 = stacktop(-1);
505 MakeSameSize(vch1, vch2);
506 if (opcode == OP_AND)
508 for (int i = 0; i < vch1.size(); i++)
511 else if (opcode == OP_OR)
513 for (int i = 0; i < vch1.size(); i++)
516 else if (opcode == OP_XOR)
518 for (int i = 0; i < vch1.size(); i++)
527 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
530 if (stack.size() < 2)
532 valtype& vch1 = stacktop(-2);
533 valtype& vch2 = stacktop(-1);
534 bool fEqual = (vch1 == vch2);
535 // OP_NOTEQUAL is disabled because it would be too easy to say
536 // something like n != 1 and have some wiseguy pass in 1 with extra
537 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
538 //if (opcode == OP_NOTEQUAL)
542 stack.push_back(fEqual ? vchTrue : vchFalse);
543 if (opcode == OP_EQUALVERIFY)
567 if (stack.size() < 1)
569 CBigNum bn = CastToBigNum(stacktop(-1));
572 case OP_1ADD: bn += bnOne; break;
573 case OP_1SUB: bn -= bnOne; break;
574 case OP_2MUL: bn <<= 1; break;
575 case OP_2DIV: bn >>= 1; break;
576 case OP_NEGATE: bn = -bn; break;
577 case OP_ABS: if (bn < bnZero) bn = -bn; break;
578 case OP_NOT: bn = (bn == bnZero); break;
579 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
582 stack.push_back(bn.getvch());
596 case OP_NUMEQUALVERIFY:
600 case OP_LESSTHANOREQUAL:
601 case OP_GREATERTHANOREQUAL:
606 if (stack.size() < 2)
608 CBigNum bn1 = CastToBigNum(stacktop(-2));
609 CBigNum bn2 = CastToBigNum(stacktop(-1));
622 if (!BN_mul(&bn, &bn1, &bn2, pctx))
627 if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
632 if (!BN_mod(&bn, &bn1, &bn2, pctx))
637 if (bn2 < bnZero || bn2 > CBigNum(2048))
639 bn = bn1 << bn2.getulong();
643 if (bn2 < bnZero || bn2 > CBigNum(2048))
645 bn = bn1 >> bn2.getulong();
648 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
649 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
650 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
651 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
652 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
653 case OP_LESSTHAN: bn = (bn1 < bn2); break;
654 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
655 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
656 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
657 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
658 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
662 stack.push_back(bn.getvch());
664 if (opcode == OP_NUMEQUALVERIFY)
666 if (CastToBool(stacktop(-1)))
676 // (x min max -- out)
677 if (stack.size() < 3)
679 CBigNum bn1 = CastToBigNum(stacktop(-3));
680 CBigNum bn2 = CastToBigNum(stacktop(-2));
681 CBigNum bn3 = CastToBigNum(stacktop(-1));
682 bool fValue = (bn2 <= bn1 && bn1 < bn3);
686 stack.push_back(fValue ? vchTrue : vchFalse);
701 if (stack.size() < 1)
703 valtype& vch = stacktop(-1);
704 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
705 if (opcode == OP_RIPEMD160)
706 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
707 else if (opcode == OP_SHA1)
708 SHA1(&vch[0], vch.size(), &vchHash[0]);
709 else if (opcode == OP_SHA256)
710 SHA256(&vch[0], vch.size(), &vchHash[0]);
711 else if (opcode == OP_HASH160)
713 uint160 hash160 = Hash160(vch);
714 memcpy(&vchHash[0], &hash160, sizeof(hash160));
716 else if (opcode == OP_HASH256)
718 uint256 hash = Hash(vch.begin(), vch.end());
719 memcpy(&vchHash[0], &hash, sizeof(hash));
722 stack.push_back(vchHash);
726 case OP_CODESEPARATOR:
728 // Hash starts after the code separator
734 case OP_CHECKSIGVERIFY:
736 // (sig pubkey -- bool)
737 if (stack.size() < 2)
740 valtype& vchSig = stacktop(-2);
741 valtype& vchPubKey = stacktop(-1);
744 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
745 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
747 // Subset of script starting at the most recent codeseparator
748 CScript scriptCode(pbegincodehash, pend);
750 // Drop the signature, since there's no way for a signature to sign itself
751 scriptCode.FindAndDelete(CScript(vchSig));
753 bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
757 stack.push_back(fSuccess ? vchTrue : vchFalse);
758 if (opcode == OP_CHECKSIGVERIFY)
768 case OP_CHECKMULTISIG:
769 case OP_CHECKMULTISIGVERIFY:
771 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
774 if (stack.size() < i)
777 int nKeysCount = CastToBigNum(stacktop(-i)).getint();
782 if (stack.size() < i)
785 int nSigsCount = CastToBigNum(stacktop(-i)).getint();
786 if (nSigsCount < 0 || nSigsCount > nKeysCount)
790 if (stack.size() < i)
793 // Subset of script starting at the most recent codeseparator
794 CScript scriptCode(pbegincodehash, pend);
796 // Drop the signatures, since there's no way for a signature to sign itself
797 for (int k = 0; k < nSigsCount; k++)
799 valtype& vchSig = stacktop(-isig-k);
800 scriptCode.FindAndDelete(CScript(vchSig));
803 bool fSuccess = true;
804 while (fSuccess && nSigsCount > 0)
806 valtype& vchSig = stacktop(-isig);
807 valtype& vchPubKey = stacktop(-ikey);
810 if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
818 // If there are more signatures left than keys left,
819 // then too many signatures have failed
820 if (nSigsCount > nKeysCount)
826 stack.push_back(fSuccess ? vchTrue : vchFalse);
828 if (opcode == OP_CHECKMULTISIGVERIFY)
843 if (stack.size() + altstack.size() > 1000)
869 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
871 if (nIn >= txTo.vin.size())
873 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
876 CTransaction txTmp(txTo);
878 // In case concatenating two scripts ends up with two codeseparators,
879 // or an extra one at the end, this prevents all those possible incompatibilities.
880 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
882 // Blank out other inputs' signatures
883 for (int i = 0; i < txTmp.vin.size(); i++)
884 txTmp.vin[i].scriptSig = CScript();
885 txTmp.vin[nIn].scriptSig = scriptCode;
887 // Blank out some of the outputs
888 if ((nHashType & 0x1f) == SIGHASH_NONE)
893 // Let the others update at will
894 for (int i = 0; i < txTmp.vin.size(); i++)
896 txTmp.vin[i].nSequence = 0;
898 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
900 // Only lockin the txout payee at same index as txin
901 unsigned int nOut = nIn;
902 if (nOut >= txTmp.vout.size())
904 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
907 txTmp.vout.resize(nOut+1);
908 for (int i = 0; i < nOut; i++)
909 txTmp.vout[i].SetNull();
911 // Let the others update at will
912 for (int i = 0; i < txTmp.vin.size(); i++)
914 txTmp.vin[i].nSequence = 0;
917 // Blank out other inputs completely, not recommended for open transactions
918 if (nHashType & SIGHASH_ANYONECANPAY)
920 txTmp.vin[0] = txTmp.vin[nIn];
924 // Serialize and hash
925 CDataStream ss(SER_GETHASH);
927 ss << txTmp << nHashType;
928 return Hash(ss.begin(), ss.end());
932 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
933 const CTransaction& txTo, unsigned int nIn, int nHashType)
936 if (!key.SetPubKey(vchPubKey))
939 // Hash type is one byte tacked on to the end of the signature
943 nHashType = vchSig.back();
944 else if (nHashType != vchSig.back())
948 if (key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig))
963 bool Solver(const CScript& scriptPubKey, vector<pair<opcodetype, valtype> >& vSolutionRet)
966 static vector<CScript> vTemplates;
967 if (vTemplates.empty())
969 // Standard tx, sender provides pubkey, receiver adds signature
970 vTemplates.push_back(CScript() << OP_PUBKEY << OP_CHECKSIG);
972 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
973 vTemplates.push_back(CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG);
977 const CScript& script1 = scriptPubKey;
978 foreach(const CScript& script2, vTemplates)
980 vSolutionRet.clear();
981 opcodetype opcode1, opcode2;
982 vector<unsigned char> vch1, vch2;
985 CScript::const_iterator pc1 = script1.begin();
986 CScript::const_iterator pc2 = script2.begin();
989 bool f1 = script1.GetOp(pc1, opcode1, vch1);
990 bool f2 = script2.GetOp(pc2, opcode2, vch2);
994 reverse(vSolutionRet.begin(), vSolutionRet.end());
1001 else if (opcode2 == OP_PUBKEY)
1003 if (vch1.size() <= sizeof(uint256))
1005 vSolutionRet.push_back(make_pair(opcode2, vch1));
1007 else if (opcode2 == OP_PUBKEYHASH)
1009 if (vch1.size() != sizeof(uint160))
1011 vSolutionRet.push_back(make_pair(opcode2, vch1));
1013 else if (opcode1 != opcode2)
1020 vSolutionRet.clear();
1025 bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
1027 scriptSigRet.clear();
1029 vector<pair<opcodetype, valtype> > vSolution;
1030 if (!Solver(scriptPubKey, vSolution))
1034 CRITICAL_BLOCK(cs_mapKeys)
1036 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1038 if (item.first == OP_PUBKEY)
1041 const valtype& vchPubKey = item.second;
1042 if (!mapKeys.count(vchPubKey))
1046 vector<unsigned char> vchSig;
1047 if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))
1049 vchSig.push_back((unsigned char)nHashType);
1050 scriptSigRet << vchSig;
1053 else if (item.first == OP_PUBKEYHASH)
1055 // Sign and give pubkey
1056 map<uint160, valtype>::iterator mi = mapPubKeys.find(uint160(item.second));
1057 if (mi == mapPubKeys.end())
1059 const vector<unsigned char>& vchPubKey = (*mi).second;
1060 if (!mapKeys.count(vchPubKey))
1064 vector<unsigned char> vchSig;
1065 if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))
1067 vchSig.push_back((unsigned char)nHashType);
1068 scriptSigRet << vchSig << vchPubKey;
1078 bool IsMine(const CScript& scriptPubKey)
1081 return Solver(scriptPubKey, 0, 0, scriptSig);
1085 bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned char>& vchPubKeyRet)
1087 vchPubKeyRet.clear();
1089 vector<pair<opcodetype, valtype> > vSolution;
1090 if (!Solver(scriptPubKey, vSolution))
1093 CRITICAL_BLOCK(cs_mapKeys)
1095 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1098 if (item.first == OP_PUBKEY)
1100 vchPubKey = item.second;
1102 else if (item.first == OP_PUBKEYHASH)
1104 map<uint160, valtype>::iterator mi = mapPubKeys.find(uint160(item.second));
1105 if (mi == mapPubKeys.end())
1107 vchPubKey = (*mi).second;
1109 if (!fMineOnly || mapKeys.count(vchPubKey))
1111 vchPubKeyRet = vchPubKey;
1120 bool ExtractHash160(const CScript& scriptPubKey, uint160& hash160Ret)
1124 vector<pair<opcodetype, valtype> > vSolution;
1125 if (!Solver(scriptPubKey, vSolution))
1128 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1130 if (item.first == OP_PUBKEYHASH)
1132 hash160Ret = uint160(item.second);
1140 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int nHashType)
1142 vector<vector<unsigned char> > stack;
1143 if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
1145 if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType))
1149 return CastToBool(stack.back());
1153 bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
1155 assert(nIn < txTo.vin.size());
1156 CTxIn& txin = txTo.vin[nIn];
1157 assert(txin.prevout.n < txFrom.vout.size());
1158 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1160 // Leave out the signature from the hash, since a signature can't sign itself.
1161 // The checksig op will also drop the signatures from its hash.
1162 uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
1164 if (!Solver(txout.scriptPubKey, hash, nHashType, txin.scriptSig))
1167 txin.scriptSig = scriptPrereq + txin.scriptSig;
1170 if (scriptPrereq.empty())
1171 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, 0))
1178 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int nHashType)
1180 assert(nIn < txTo.vin.size());
1181 const CTxIn& txin = txTo.vin[nIn];
1182 if (txin.prevout.n >= txFrom.vout.size())
1184 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1186 if (txin.prevout.hash != txFrom.GetHash())
1189 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nHashType))
1192 // Anytime a signature is successfully verified, it's proof the outpoint is spent,
1193 // so lets update the wallet spent flag if it doesn't know due to wallet.dat being
1194 // restored from backup or the user making copies of wallet.dat.
1195 WalletUpdateSpent(txin.prevout);