// Copyright (c) 2009-2010 Satoshi Nakamoto
-// Copyright (c) 2011 The Bitcoin developers
+// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
-// file license.txt or http://www.opensource.org/licenses/mit-license.php.
-#include "headers.h"
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <boost/foreach.hpp>
+#include <boost/tuple/tuple.hpp>
using namespace std;
using namespace boost;
-bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
-
+#include "script.h"
+#include "keystore.h"
+#include "bignum.h"
+#include "key.h"
+#include "main.h"
+#include "sync.h"
+#include "util.h"
+bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
-typedef vector<unsigned char> valtype;
static const valtype vchFalse(0);
static const valtype vchZero(0);
static const valtype vchTrue(1, 1);
bool CastToBool(const valtype& vch)
{
- for (int i = 0; i < vch.size(); i++)
+ for (unsigned int i = 0; i < vch.size(); i++)
{
if (vch[i] != 0)
{
return false;
}
+//
+// WARNING: This does not work as expected for signed integers; the sign-bit
+// is left in place as the integer is zero-extended. The correct behavior
+// would be to move the most significant bit of the last byte during the
+// resize process. MakeSameSize() is currently only used by the disabled
+// opcodes OP_AND, OP_OR, and OP_XOR.
+//
void MakeSameSize(valtype& vch1, valtype& vch2)
{
// Lengthen the shorter one
if (vch1.size() < vch2.size())
+ // PATCH:
+ // +unsigned char msb = vch1[vch1.size()-1];
+ // +vch1[vch1.size()-1] &= 0x7f;
+ // vch1.resize(vch2.size(), 0);
+ // +vch1[vch1.size()-1] = msb;
vch1.resize(vch2.size(), 0);
if (vch2.size() < vch1.size())
+ // PATCH:
+ // +unsigned char msb = vch2[vch2.size()-1];
+ // +vch2[vch2.size()-1] &= 0x7f;
+ // vch2.resize(vch1.size(), 0);
+ // +vch2[vch2.size()-1] = msb;
vch2.resize(vch1.size(), 0);
}
}
-const char* GetTxnTypeName(txntype t)
+const char* GetTxnOutputType(txnouttype t)
{
switch (t)
{
case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
- // meta
- case OP_EVAL : return "OP_EVAL";
-
// expanson
+ case OP_NOP1 : return "OP_NOP1";
case OP_NOP2 : return "OP_NOP2";
case OP_NOP3 : return "OP_NOP3";
case OP_NOP4 : return "OP_NOP4";
// template matching params
- case OP_SCRIPTHASH : return "OP_SCRIPTHASH";
case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
case OP_PUBKEY : return "OP_PUBKEY";
}
}
-
-//
-// Returns true if script is valid.
-//
-bool EvalScriptInner(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType,
- CScript::const_iterator pbegincodehash, CScript::const_iterator pendcodehash, int& nOpCount, int& nSigOpCount, int nRecurseDepth)
+bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
CAutoBN_CTX pctx;
CScript::const_iterator pc = script.begin();
CScript::const_iterator pend = script.end();
+ CScript::const_iterator pbegincodehash = script.begin();
opcodetype opcode;
valtype vchPushValue;
vector<bool> vfExec;
vector<valtype> altstack;
if (script.size() > 10000)
return false;
+ int nOpCount = 0;
- // Limit OP_EVAL recursion
- if (nRecurseDepth > 2)
- return false;
try
{
// Control
//
case OP_NOP:
- case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
+ case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
break;
return false;
int n = CastToBigNum(stacktop(-1)).getint();
popstack(stack);
- if (n < 0 || n >= stack.size())
+ if (n < 0 || n >= (int)stack.size())
return false;
valtype vch = stacktop(-n-1);
if (opcode == OP_ROLL)
int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
if (nBegin < 0 || nEnd < nBegin)
return false;
- if (nBegin > vch.size())
+ if (nBegin > (int)vch.size())
nBegin = vch.size();
- if (nEnd > vch.size())
+ if (nEnd > (int)vch.size())
nEnd = vch.size();
vch.erase(vch.begin() + nEnd, vch.end());
vch.erase(vch.begin(), vch.begin() + nBegin);
int nSize = CastToBigNum(stacktop(-1)).getint();
if (nSize < 0)
return false;
- if (nSize > vch.size())
+ if (nSize > (int)vch.size())
nSize = vch.size();
if (opcode == OP_LEFT)
vch.erase(vch.begin() + nSize, vch.end());
if (stack.size() < 1)
return false;
valtype& vch = stacktop(-1);
- for (int i = 0; i < vch.size(); i++)
+ for (unsigned int i = 0; i < vch.size(); i++)
vch[i] = ~vch[i];
}
break;
+ //
+ // WARNING: These disabled opcodes exhibit unexpected behavior
+ // when used on signed integers due to a bug in MakeSameSize()
+ // [see definition of MakeSameSize() above].
+ //
case OP_AND:
case OP_OR:
case OP_XOR:
return false;
valtype& vch1 = stacktop(-2);
valtype& vch2 = stacktop(-1);
- MakeSameSize(vch1, vch2);
+ MakeSameSize(vch1, vch2); // <-- NOT SAFE FOR SIGNED VALUES
if (opcode == OP_AND)
{
- for (int i = 0; i < vch1.size(); i++)
+ for (unsigned int i = 0; i < vch1.size(); i++)
vch1[i] &= vch2[i];
}
else if (opcode == OP_OR)
{
- for (int i = 0; i < vch1.size(); i++)
+ for (unsigned int i = 0; i < vch1.size(); i++)
vch1[i] |= vch2[i];
}
else if (opcode == OP_XOR)
{
- for (int i = 0; i < vch1.size(); i++)
+ for (unsigned int i = 0; i < vch1.size(); i++)
vch1[i] ^= vch2[i];
}
popstack(stack);
//PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
// Subset of script starting at the most recent codeseparator
- CScript scriptCode(pbegincodehash, pendcodehash);
+ CScript scriptCode(pbegincodehash, pend);
// Drop the signature, since there's no way for a signature to sign itself
scriptCode.FindAndDelete(CScript(vchSig));
bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
- nSigOpCount++;
popstack(stack);
popstack(stack);
// ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
int i = 1;
- if (stack.size() < i)
+ if ((int)stack.size() < i)
return false;
int nKeysCount = CastToBigNum(stacktop(-i)).getint();
return false;
int ikey = ++i;
i += nKeysCount;
- if (stack.size() < i)
+ if ((int)stack.size() < i)
return false;
int nSigsCount = CastToBigNum(stacktop(-i)).getint();
return false;
int isig = ++i;
i += nSigsCount;
- if (stack.size() < i)
+ if ((int)stack.size() < i)
return false;
// Subset of script starting at the most recent codeseparator
- CScript scriptCode(pbegincodehash, pendcodehash);
+ CScript scriptCode(pbegincodehash, pend);
// Drop the signatures, since there's no way for a signature to sign itself
for (int k = 0; k < nSigsCount; k++)
}
ikey++;
nKeysCount--;
- nSigOpCount++;
// If there are more signatures left than keys left,
// then too many signatures have failed
}
break;
- case OP_EVAL:
- {
- // This code should be removed when OP_EVAL has
- // a majority of hashing power on the network.
- // OP_EVAL behaves just like OP_NOP until
- // opevaltime :
- if (!fTestNet || fDebug)
- {
- // 1328054400 is Feb 1, 2012
- int64 nEvalSwitchTime = GetArg("opevaltime", 1328054400);
- if (GetTime() < nEvalSwitchTime)
- break;
- }
-
- // Evaluate the top item on the stack as a Script
- // [serialized script ] -- [result(s) of executing script]
- if (stack.size() < 1)
- return false;
- valtype& vchScript = stacktop(-1);
- CScript subscript(vchScript.begin(), vchScript.end());
- popstack(stack);
-
- // Codeseparators not allowed
- if (subscript.Find(OP_CODESEPARATOR))
- return false;
-
- if (!EvalScriptInner(stack, subscript, txTo, nIn, nHashType,
- pbegincodehash, pendcodehash, nOpCount, nSigOpCount, nRecurseDepth++))
- return false;
- }
- break;
-
default:
return false;
}
return true;
}
-bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script,
- const CTransaction& txTo, unsigned int nIn, int nHashType, int& nSigOpCountRet)
-{
- CScript::const_iterator pbegincodehash = script.begin();
- CScript::const_iterator pendcodehash = script.end();
-
- int nOpCount = 0;
- return EvalScriptInner(stack, script, txTo, nIn, nHashType, pbegincodehash, pendcodehash,
- nOpCount, nSigOpCountRet, 0);
-}
-
scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
// Blank out other inputs' signatures
- for (int i = 0; i < txTmp.vin.size(); i++)
+ for (unsigned int i = 0; i < txTmp.vin.size(); i++)
txTmp.vin[i].scriptSig = CScript();
txTmp.vin[nIn].scriptSig = scriptCode;
txTmp.vout.clear();
// Let the others update at will
- for (int i = 0; i < txTmp.vin.size(); i++)
+ for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
{
- // Only lockin the txout payee at same index as txin
+ // Only lock-in the txout payee at same index as txin
unsigned int nOut = nIn;
if (nOut >= txTmp.vout.size())
{
return 1;
}
txTmp.vout.resize(nOut+1);
- for (int i = 0; i < nOut; i++)
+ for (unsigned int i = 0; i < nOut; i++)
txTmp.vout[i].SetNull();
// Let the others update at will
- for (int i = 0; i < txTmp.vin.size(); i++)
+ for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
}
// Serialize and hash
- CDataStream ss(SER_GETHASH);
+ CDataStream ss(SER_GETHASH, 0);
ss.reserve(10000);
ss << txTmp << nHashType;
return Hash(ss.begin(), ss.end());
}
+// Valid signature cache, to avoid doing expensive ECDSA signature checking
+// twice for every transaction (once when accepted into memory pool, and
+// again when accepted into the block chain)
+
+class CSignatureCache
+{
+private:
+ // sigdata_type is (signature hash, signature, public key):
+ typedef boost::tuple<uint256, std::vector<unsigned char>, std::vector<unsigned char> > sigdata_type;
+ std::set< sigdata_type> setValid;
+ CCriticalSection cs_sigcache;
+
+public:
+ bool
+ Get(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
+ {
+ LOCK(cs_sigcache);
+
+ sigdata_type k(hash, vchSig, pubKey);
+ std::set<sigdata_type>::iterator mi = setValid.find(k);
+ if (mi != setValid.end())
+ return true;
+ return false;
+ }
+
+ void Set(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
+ {
+ // DoS prevention: limit cache size to less than 10MB
+ // (~200 bytes per cache entry times 50,000 entries)
+ // Since there are a maximum of 20,000 signature operations per block
+ // 50,000 is a reasonable default.
+ int64 nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
+ if (nMaxCacheSize <= 0) return;
+
+ LOCK(cs_sigcache);
+
+ while (static_cast<int64>(setValid.size()) > nMaxCacheSize)
+ {
+ // Evict a random entry. Random because that helps
+ // foil would-be DoS attackers who might try to pre-generate
+ // and re-use a set of valid signatures just-slightly-greater
+ // than our cache size.
+ uint256 randomHash = GetRandHash();
+ std::vector<unsigned char> unused;
+ std::set<sigdata_type>::iterator it =
+ setValid.lower_bound(sigdata_type(randomHash, unused, unused));
+ if (it == setValid.end())
+ it = setValid.begin();
+ setValid.erase(*it);
+ }
+
+ sigdata_type k(hash, vchSig, pubKey);
+ setValid.insert(k);
+ }
+};
+
bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
const CTransaction& txTo, unsigned int nIn, int nHashType)
{
- CKey key;
- if (!key.SetPubKey(vchPubKey))
- return false;
+ static CSignatureCache signatureCache;
// Hash type is one byte tacked on to the end of the signature
if (vchSig.empty())
return false;
vchSig.pop_back();
- return key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig);
+ uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
+
+ if (signatureCache.Get(sighash, vchSig, vchPubKey))
+ return true;
+
+ CKey key;
+ if (!key.SetPubKey(vchPubKey))
+ return false;
+
+ if (!key.Verify(sighash, vchSig))
+ return false;
+
+ signatureCache.Set(sighash, vchSig, vchPubKey);
+ return true;
}
//
// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
//
-bool Solver(const CScript& scriptPubKey, txntype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
+bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
{
// Templates
- static map<txntype, CScript> mTemplates;
+ static map<txnouttype, CScript> mTemplates;
if (mTemplates.empty())
{
// Standard tx, sender provides pubkey, receiver adds signature
// Sender provides N pubkeys, receivers provides M signatures
mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
+ }
- // Sender provides script hash, receiver provides script and
- // as many signatures as required to satisfy script
- mTemplates.insert(make_pair(TX_SCRIPTHASH, CScript() << OP_DUP << OP_HASH160 << OP_SCRIPTHASH << OP_EQUALVERIFY << OP_EVAL));
+ // Shortcut for pay-to-script-hash, which are more constrained than the other types:
+ // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
+ if (scriptPubKey.IsPayToScriptHash())
+ {
+ typeRet = TX_SCRIPTHASH;
+ vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
+ vSolutionsRet.push_back(hashBytes);
+ return true;
}
// Scan templates
const CScript& script1 = scriptPubKey;
- BOOST_FOREACH(const PAIRTYPE(txntype, CScript)& tplate, mTemplates)
+ BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
{
const CScript& script2 = tplate.second;
vSolutionsRet.clear();
// Compare
CScript::const_iterator pc1 = script1.begin();
CScript::const_iterator pc2 = script2.begin();
- loop
+ while (true)
{
if (pc1 == script1.end() && pc2 == script2.end())
{
if (!script2.GetOp(pc2, opcode2, vch2))
break;
// Normal situation is to fall through
- // to other if/else statments
+ // to other if/else statements
}
if (opcode2 == OP_PUBKEY)
break;
vSolutionsRet.push_back(vch1);
}
- else if (opcode2 == OP_SCRIPTHASH)
- {
- if (vch1.size() != sizeof(uint160))
- break;
- vSolutionsRet.push_back(vch1);
- }
else if (opcode2 == OP_SMALLINTEGER)
{ // Single-byte small integer pushed onto vSolutions
if (opcode1 == OP_0 ||
}
-bool Sign1(const CBitcoinAddress& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
+bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
{
CKey key;
if (!keystore.GetKey(address, key))
{
int nSigned = 0;
int nRequired = multisigdata.front()[0];
- for (vector<valtype>::const_iterator it = multisigdata.begin()+1; it != multisigdata.begin()+multisigdata.size()-1; it++)
+ for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
{
- const valtype& pubkey = *it;
- CBitcoinAddress address;
- address.SetPubKey(pubkey);
- if (Sign1(address, keystore, hash, nHashType, scriptSigRet))
- {
+ const valtype& pubkey = multisigdata[i];
+ CKeyID keyID = CPubKey(pubkey).GetID();
+ if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
++nSigned;
- if (nSigned == nRequired) break;
- }
}
return nSigned==nRequired;
}
//
// Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
-// Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed).
-// Returns true if scriptPubKey could be completely satisified.
+// Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
+// unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
+// Returns false if scriptPubKey could not be completely satisfied.
//
-bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
+bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
+ CScript& scriptSigRet, txnouttype& whichTypeRet)
{
scriptSigRet.clear();
- txntype whichType;
vector<valtype> vSolutions;
- if (!Solver(scriptPubKey, whichType, vSolutions))
+ if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
return false;
- CBitcoinAddress address;
- valtype subscript;
- switch (whichType)
+ CKeyID keyID;
+ switch (whichTypeRet)
{
case TX_NONSTANDARD:
return false;
case TX_PUBKEY:
- address.SetPubKey(vSolutions[0]);
- return Sign1(address, keystore, hash, nHashType, scriptSigRet);
+ keyID = CPubKey(vSolutions[0]).GetID();
+ return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
case TX_PUBKEYHASH:
- address.SetHash160(uint160(vSolutions[0]));
- if (!Sign1(address, keystore, hash, nHashType, scriptSigRet))
+ keyID = CKeyID(uint160(vSolutions[0]));
+ if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
return false;
else
{
- valtype vch;
- keystore.GetPubKey(address, vch);
+ CPubKey vch;
+ keystore.GetPubKey(keyID, vch);
scriptSigRet << vch;
}
- break;
+ return true;
case TX_SCRIPTHASH:
- if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
- return false;
- if (!Solver(keystore, CScript(subscript.begin(), subscript.end()), hash, nHashType, scriptSigRet))
- return false;
- if (hash != 0)
- scriptSigRet << subscript; // signatures AND serialized script
- break;
+ return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
+
case TX_MULTISIG:
scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
}
- return true;
+ return false;
}
+int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
+{
+ switch (t)
+ {
+ case TX_NONSTANDARD:
+ return -1;
+ case TX_PUBKEY:
+ return 1;
+ case TX_PUBKEYHASH:
+ return 2;
+ case TX_MULTISIG:
+ if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
+ return -1;
+ return vSolutions[0][0] + 1;
+ case TX_SCRIPTHASH:
+ return 1; // doesn't include args needed by the script
+ }
+ return -1;
+}
bool IsStandard(const CScript& scriptPubKey)
{
vector<valtype> vSolutions;
- txntype whichType;
+ txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
}
-int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
+unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
{
- int nResult = 0;
+ unsigned int nResult = 0;
BOOST_FOREACH(const valtype& pubkey, pubkeys)
{
- CBitcoinAddress address;
- address.SetPubKey(pubkey);
- if (keystore.HaveKey(address))
+ CKeyID keyID = CPubKey(pubkey).GetID();
+ if (keystore.HaveKey(keyID))
++nResult;
}
return nResult;
}
+
+class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
+{
+private:
+ const CKeyStore *keystore;
+public:
+ CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
+ bool operator()(const CNoDestination &dest) const { return false; }
+ bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
+ bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
+};
+
+bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
+{
+ return boost::apply_visitor(CKeyStoreIsMineVisitor(&keystore), dest);
+}
+
bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
{
vector<valtype> vSolutions;
- txntype whichType;
+ txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
- CBitcoinAddress address;
+ CKeyID keyID;
switch (whichType)
{
case TX_NONSTANDARD:
return false;
case TX_PUBKEY:
- address.SetPubKey(vSolutions[0]);
- return keystore.HaveKey(address);
+ keyID = CPubKey(vSolutions[0]).GetID();
+ return keystore.HaveKey(keyID);
case TX_PUBKEYHASH:
- address.SetHash160(uint160(vSolutions[0]));
- return keystore.HaveKey(address);
+ keyID = CKeyID(uint160(vSolutions[0]));
+ return keystore.HaveKey(keyID);
case TX_SCRIPTHASH:
{
- valtype subscript;
- if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
+ CScript subscript;
+ if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
return false;
- return IsMine(keystore, CScript(subscript.begin(), subscript.end()));
+ return IsMine(keystore, subscript);
}
case TX_MULTISIG:
{
// them) enable spend-out-from-under-you attacks, especially
// in shared-wallet situations.
vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
- return HaveKeys(vSolutions, keystore);
+ return HaveKeys(keys, keystore) == keys.size();
}
}
return false;
}
-bool ExtractAddress(const CScript& scriptPubKey, const CKeyStore* keystore, CBitcoinAddress& addressRet)
+bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
{
vector<valtype> vSolutions;
- txntype whichType;
+ txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
- addressRet.SetPubKey(vSolutions[0]);
+ addressRet = CPubKey(vSolutions[0]).GetID();
return true;
}
else if (whichType == TX_PUBKEYHASH)
{
- addressRet.SetHash160(uint160(vSolutions[0]));
+ addressRet = CKeyID(uint160(vSolutions[0]));
return true;
}
else if (whichType == TX_SCRIPTHASH)
{
- addressRet.SetScriptHash160(uint160(vSolutions[0]));
+ addressRet = CScriptID(uint160(vSolutions[0]));
return true;
}
// Multisig txns have more than one address...
return false;
}
-bool ExtractAddresses(const CScript& scriptPubKey, const CKeyStore* keystore, txntype& typeRet, vector<CBitcoinAddress>& addressRet, int& nRequiredRet)
+class CAffectedKeysVisitor : public boost::static_visitor<void> {
+private:
+ const CKeyStore &keystore;
+ std::vector<CKeyID> &vKeys;
+
+public:
+ CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
+
+ void Process(const CScript &script) {
+ txnouttype type;
+ std::vector<CTxDestination> vDest;
+ int nRequired;
+ if (ExtractDestinations(script, type, vDest, nRequired)) {
+ BOOST_FOREACH(const CTxDestination &dest, vDest)
+ boost::apply_visitor(*this, dest);
+ }
+ }
+
+ void operator()(const CKeyID &keyId) {
+ if (keystore.HaveKey(keyId))
+ vKeys.push_back(keyId);
+ }
+
+ void operator()(const CScriptID &scriptId) {
+ CScript script;
+ if (keystore.GetCScript(scriptId, script))
+ Process(script);
+ }
+
+ void operator()(const CNoDestination &none) {}
+};
+
+
+void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
+ CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
+}
+
+bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
{
addressRet.clear();
typeRet = TX_NONSTANDARD;
if (typeRet == TX_MULTISIG)
{
nRequiredRet = vSolutions.front()[0];
- int n = vSolutions.back()[0];
- for (vector<valtype>::const_iterator it = vSolutions.begin()+1; it != vSolutions.begin()+vSolutions.size()-1; it++)
+ for (unsigned int i = 1; i < vSolutions.size()-1; i++)
{
- CBitcoinAddress address;
- address.SetPubKey(*it);
+ CTxDestination address = CPubKey(vSolutions[i]).GetID();
addressRet.push_back(address);
}
}
else
{
nRequiredRet = 1;
- CBitcoinAddress address;
- if (typeRet == TX_PUBKEYHASH)
- address.SetHash160(uint160(vSolutions.front()));
- else if (typeRet == TX_SCRIPTHASH)
- address.SetScriptHash160(uint160(vSolutions.front()));
- else if (typeRet == TX_PUBKEY)
- address.SetPubKey(vSolutions.front());
+ CTxDestination address;
+ if (!ExtractDestination(scriptPubKey, address))
+ return false;
addressRet.push_back(address);
}
return true;
}
-bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet, int nHashType)
+bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
+ bool fValidatePayToScriptHash, int nHashType)
{
- vector<vector<unsigned char> > stack;
- if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType, nSigOpCountRet))
+ vector<vector<unsigned char> > stack, stackCopy;
+ if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
return false;
- if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType, nSigOpCountRet))
+ if (fValidatePayToScriptHash)
+ stackCopy = stack;
+ if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType))
return false;
if (stack.empty())
return false;
- bool fResult = CastToBool(stack.back());
- // This code should be removed when a compatibility-breaking block chain split has passed.
- // Special check for OP_EVAL backwards-compatibility: if scriptPubKey or scriptSig contains
- // OP_EVAL, then result must be identical if OP_EVAL is treated as a no-op:
- if (scriptSig.Find(OP_EVAL)+scriptPubKey.Find(OP_EVAL) > 0)
+ if (CastToBool(stack.back()) == false)
+ return false;
+
+ // Additional validation for spend-to-script-hash transactions:
+ if (fValidatePayToScriptHash && scriptPubKey.IsPayToScriptHash())
{
- int nUnused = 0;
- stack.clear();
- CScript sigCopy = scriptSig;
- sigCopy.FindAndDelete(CScript(OP_EVAL));
- CScript pubKeyCopy = scriptPubKey;
- pubKeyCopy.FindAndDelete(CScript(OP_EVAL));
-
- if (!EvalScript(stack, sigCopy, txTo, nIn, nHashType, nUnused))
- return false;
- if (!EvalScript(stack, pubKeyCopy, txTo, nIn, nHashType, nUnused))
- return false;
- if (stack.empty())
+ if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
+ return false; // or validation fails
+
+ const valtype& pubKeySerialized = stackCopy.back();
+ CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
+ popstack(stackCopy);
+
+ if (!EvalScript(stackCopy, pubKey2, txTo, nIn, nHashType))
return false;
- if (fResult != CastToBool(stack.back()))
+ if (stackCopy.empty())
return false;
+ return CastToBool(stackCopy.back());
}
- return fResult;
+ return true;
}
-bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
+bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
{
assert(nIn < txTo.vin.size());
CTxIn& txin = txTo.vin[nIn];
- assert(txin.prevout.n < txFrom.vout.size());
- const CTxOut& txout = txFrom.vout[txin.prevout.n];
// Leave out the signature from the hash, since a signature can't sign itself.
// The checksig op will also drop the signatures from its hash.
- uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
+ uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
- if (!Solver(keystore, txout.scriptPubKey, hash, nHashType, txin.scriptSig))
+ txnouttype whichType;
+ if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
return false;
- txin.scriptSig = scriptPrereq + txin.scriptSig;
+ if (whichType == TX_SCRIPTHASH)
+ {
+ // Solver returns the subscript that need to be evaluated;
+ // the final scriptSig is the signatures from that
+ // and then the serialized subscript:
+ CScript subscript = txin.scriptSig;
+
+ // Recompute txn hash using subscript in place of scriptPubKey:
+ uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
+
+ txnouttype subType;
+ bool fSolved =
+ Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
+ // Append serialized subscript whether or not it is completely signed:
+ txin.scriptSig << static_cast<valtype>(subscript);
+ if (!fSolved) return false;
+ }
// Test solution
- int nUnused = 0;
- if (scriptPrereq.empty())
- if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nUnused, 0))
- return false;
-
- return true;
+ return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, true, 0);
}
+bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
+{
+ assert(nIn < txTo.vin.size());
+ CTxIn& txin = txTo.vin[nIn];
+ assert(txin.prevout.n < txFrom.vout.size());
+ assert(txin.prevout.hash == txFrom.GetHash());
+ const CTxOut& txout = txFrom.vout[txin.prevout.n];
-bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet, int nHashType)
+ return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
+}
+
+bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType)
{
assert(nIn < txTo.vin.size());
const CTxIn& txin = txTo.vin[nIn];
if (txin.prevout.hash != txFrom.GetHash())
return false;
- if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nSigOpCountRet, nHashType))
- return false;
+ return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, nHashType);
+}
- return true;
+static CScript PushAll(const vector<valtype>& values)
+{
+ CScript result;
+ BOOST_FOREACH(const valtype& v, values)
+ result << v;
+ return result;
}
-void CScript::SetBitcoinAddress(const CBitcoinAddress& address)
+static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
+ const vector<valtype>& vSolutions,
+ vector<valtype>& sigs1, vector<valtype>& sigs2)
{
- this->clear();
- if (address.IsScript())
- *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_EVAL;
- else
- *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_CHECKSIG;
+ // Combine all the signatures we've got:
+ set<valtype> allsigs;
+ BOOST_FOREACH(const valtype& v, sigs1)
+ {
+ if (!v.empty())
+ allsigs.insert(v);
+ }
+ BOOST_FOREACH(const valtype& v, sigs2)
+ {
+ if (!v.empty())
+ allsigs.insert(v);
+ }
+
+ // Build a map of pubkey -> signature by matching sigs to pubkeys:
+ assert(vSolutions.size() > 1);
+ unsigned int nSigsRequired = vSolutions.front()[0];
+ unsigned int nPubKeys = vSolutions.size()-2;
+ map<valtype, valtype> sigs;
+ BOOST_FOREACH(const valtype& sig, allsigs)
+ {
+ for (unsigned int i = 0; i < nPubKeys; i++)
+ {
+ const valtype& pubkey = vSolutions[i+1];
+ if (sigs.count(pubkey))
+ continue; // Already got a sig for this pubkey
+
+ if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0))
+ {
+ sigs[pubkey] = sig;
+ break;
+ }
+ }
+ }
+ // Now build a merged CScript:
+ unsigned int nSigsHave = 0;
+ CScript result; result << OP_0; // pop-one-too-many workaround
+ for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
+ {
+ if (sigs.count(vSolutions[i+1]))
+ {
+ result << sigs[vSolutions[i+1]];
+ ++nSigsHave;
+ }
+ }
+ // Fill any missing with OP_0:
+ for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
+ result << OP_0;
+
+ return result;
+}
+
+static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
+ const txnouttype txType, const vector<valtype>& vSolutions,
+ vector<valtype>& sigs1, vector<valtype>& sigs2)
+{
+ switch (txType)
+ {
+ case TX_NONSTANDARD:
+ // Don't know anything about this, assume bigger one is correct:
+ if (sigs1.size() >= sigs2.size())
+ return PushAll(sigs1);
+ return PushAll(sigs2);
+ case TX_PUBKEY:
+ case TX_PUBKEYHASH:
+ // Signatures are bigger than placeholders or empty scripts:
+ if (sigs1.empty() || sigs1[0].empty())
+ return PushAll(sigs2);
+ return PushAll(sigs1);
+ case TX_SCRIPTHASH:
+ if (sigs1.empty() || sigs1.back().empty())
+ return PushAll(sigs2);
+ else if (sigs2.empty() || sigs2.back().empty())
+ return PushAll(sigs1);
+ else
+ {
+ // Recur to combine:
+ valtype spk = sigs1.back();
+ CScript pubKey2(spk.begin(), spk.end());
+
+ txnouttype txType2;
+ vector<vector<unsigned char> > vSolutions2;
+ Solver(pubKey2, txType2, vSolutions2);
+ sigs1.pop_back();
+ sigs2.pop_back();
+ CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
+ result << spk;
+ return result;
+ }
+ case TX_MULTISIG:
+ return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
+ }
+
+ return CScript();
+}
+
+CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
+ const CScript& scriptSig1, const CScript& scriptSig2)
+{
+ txnouttype txType;
+ vector<vector<unsigned char> > vSolutions;
+ Solver(scriptPubKey, txType, vSolutions);
+
+ vector<valtype> stack1;
+ EvalScript(stack1, scriptSig1, CTransaction(), 0, 0);
+ vector<valtype> stack2;
+ EvalScript(stack2, scriptSig2, CTransaction(), 0, 0);
+
+ return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
+}
+
+unsigned int CScript::GetSigOpCount(bool fAccurate) const
+{
+ unsigned int n = 0;
+ const_iterator pc = begin();
+ opcodetype lastOpcode = OP_INVALIDOPCODE;
+ while (pc < end())
+ {
+ opcodetype opcode;
+ if (!GetOp(pc, opcode))
+ break;
+ if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
+ n++;
+ else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
+ {
+ if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
+ n += DecodeOP_N(lastOpcode);
+ else
+ n += 20;
+ }
+ lastOpcode = opcode;
+ }
+ return n;
+}
+
+unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
+{
+ if (!IsPayToScriptHash())
+ return GetSigOpCount(true);
+
+ // This is a pay-to-script-hash scriptPubKey;
+ // get the last item that the scriptSig
+ // pushes onto the stack:
+ const_iterator pc = scriptSig.begin();
+ vector<unsigned char> data;
+ while (pc < scriptSig.end())
+ {
+ opcodetype opcode;
+ if (!scriptSig.GetOp(pc, opcode, data))
+ return 0;
+ if (opcode > OP_16)
+ return 0;
+ }
+
+ /// ... and return its opcount:
+ CScript subscript(data.begin(), data.end());
+ return subscript.GetSigOpCount(true);
+}
+
+bool CScript::IsPayToScriptHash() const
+{
+ // Extra-fast test for pay-to-script-hash CScripts:
+ return (this->size() == 23 &&
+ this->at(0) == OP_HASH160 &&
+ this->at(1) == 0x14 &&
+ this->at(22) == OP_EQUAL);
+}
+
+class CScriptVisitor : public boost::static_visitor<bool>
+{
+private:
+ CScript *script;
+public:
+ CScriptVisitor(CScript *scriptin) { script = scriptin; }
+
+ bool operator()(const CNoDestination &dest) const {
+ script->clear();
+ return false;
+ }
+
+ bool operator()(const CKeyID &keyID) const {
+ script->clear();
+ *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
+ return true;
+ }
+
+ bool operator()(const CScriptID &scriptID) const {
+ script->clear();
+ *script << OP_HASH160 << scriptID << OP_EQUAL;
+ return true;
+ }
+};
+
+void CScript::SetDestination(const CTxDestination& dest)
+{
+ boost::apply_visitor(CScriptVisitor(this), dest);
}
void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
*this << key.GetPubKey();
*this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
}
-
-void CScript::SetEval(const CScript& subscript)
-{
- assert(!subscript.empty());
- uint160 subscriptHash = Hash160(subscript);
- this->clear();
- *this << OP_DUP << OP_HASH160 << subscriptHash << OP_EQUALVERIFY << OP_EVAL;
-}