detach wallet from miner

This commit is contained in:
Jonas Schnelli 2015-04-10 12:49:01 +02:00
parent da77a6f761
commit d0fc10a844
9 changed files with 61 additions and 61 deletions

View file

@ -156,8 +156,8 @@ void Shutdown()
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
if (pwalletMain) if (pwalletMain)
pwalletMain->Flush(false); pwalletMain->Flush(false);
GenerateBitcoins(false, NULL, 0);
#endif #endif
GenerateBitcoins(false, 0, Params());
StopNode(); StopNode();
UnregisterNodeSignals(GetNodeSignals()); UnregisterNodeSignals(GetNodeSignals());
@ -370,10 +370,8 @@ std::string HelpMessage(HelpMessageMode mode)
debugCategories += ", qt"; debugCategories += ", qt";
strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " + strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
_("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + "."); _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
#ifdef ENABLE_WALLET
strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0)); strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1)); strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
#endif
strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)")); strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0)); strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1)); strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
@ -1439,11 +1437,8 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing); boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing);
scheduler.scheduleEvery(f, nPowTargetSpacing); scheduler.scheduleEvery(f, nPowTargetSpacing);
#ifdef ENABLE_WALLET
// Generate coins in the background // Generate coins in the background
if (pwalletMain) GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 1), Params());
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1));
#endif
// ********************************************************* Step 11: finished // ********************************************************* Step 11: finished

View file

@ -17,9 +17,7 @@
#include "timedata.h" #include "timedata.h"
#include "util.h" #include "util.h"
#include "utilmoneystr.h" #include "utilmoneystr.h"
#ifdef ENABLE_WALLET #include "validationinterface.h"
#include "wallet/wallet.h"
#endif
#include <boost/thread.hpp> #include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple.hpp>
@ -362,7 +360,6 @@ void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int&
pblock->hashMerkleRoot = pblock->BuildMerkleTree(); pblock->hashMerkleRoot = pblock->BuildMerkleTree();
} }
#ifdef ENABLE_WALLET
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
// //
// Internal miner // Internal miner
@ -401,17 +398,7 @@ bool static ScanHash(const CBlockHeader *pblock, uint32_t& nNonce, uint256 *phas
} }
} }
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) static bool ProcessBlockFound(CBlock* pblock, const CChainParams& chainparams)
{
CPubKey pubkey;
if (!reservekey.GetReservedKey(pubkey))
return NULL;
CScript scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
return CreateNewBlock(scriptPubKey);
}
static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{ {
LogPrintf("%s\n", pblock->ToString()); LogPrintf("%s\n", pblock->ToString());
LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue)); LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
@ -423,14 +410,8 @@ static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& rese
return error("BitcoinMiner: generated block is stale"); return error("BitcoinMiner: generated block is stale");
} }
// Remove key from key pool // Inform about the new block
reservekey.KeepKey(); GetMainSignals().BlockFound(*pblock);
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
// Process this block the same as if we had received it from another node // Process this block the same as if we had received it from another node
CValidationState state; CValidationState state;
@ -440,15 +421,12 @@ static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& rese
return true; return true;
} }
void static BitcoinMiner(CWallet *pwallet) void static BitcoinMiner(const CChainParams& chainparams, const CScript& coinbaseScript)
{ {
LogPrintf("BitcoinMiner started\n"); LogPrintf("BitcoinMiner started\n");
SetThreadPriority(THREAD_PRIORITY_LOWEST); SetThreadPriority(THREAD_PRIORITY_LOWEST);
RenameThread("bitcoin-miner"); RenameThread("bitcoin-miner");
const CChainParams& chainparams = Params();
// Each thread has its own key and counter
CReserveKey reservekey(pwallet);
unsigned int nExtraNonce = 0; unsigned int nExtraNonce = 0;
try { try {
@ -474,7 +452,7 @@ void static BitcoinMiner(CWallet *pwallet)
unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrev = chainActive.Tip(); CBlockIndex* pindexPrev = chainActive.Tip();
auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey)); auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(coinbaseScript));
if (!pblocktemplate.get()) if (!pblocktemplate.get())
{ {
LogPrintf("Error in BitcoinMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); LogPrintf("Error in BitcoinMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
@ -506,7 +484,7 @@ void static BitcoinMiner(CWallet *pwallet)
SetThreadPriority(THREAD_PRIORITY_NORMAL); SetThreadPriority(THREAD_PRIORITY_NORMAL);
LogPrintf("BitcoinMiner:\n"); LogPrintf("BitcoinMiner:\n");
LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex()); LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex());
ProcessBlockFound(pblock, *pwallet, reservekey); ProcessBlockFound(pblock, chainparams);
SetThreadPriority(THREAD_PRIORITY_LOWEST); SetThreadPriority(THREAD_PRIORITY_LOWEST);
// In regression test mode, stop mining after a block is found. // In regression test mode, stop mining after a block is found.
@ -551,7 +529,7 @@ void static BitcoinMiner(CWallet *pwallet)
} }
} }
void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) void GenerateBitcoins(bool fGenerate, int nThreads, const CChainParams& chainparams)
{ {
static boost::thread_group* minerThreads = NULL; static boost::thread_group* minerThreads = NULL;
@ -573,9 +551,14 @@ void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
if (nThreads == 0 || !fGenerate) if (nThreads == 0 || !fGenerate)
return; return;
CScript coinbaseScript;
GetMainSignals().ScriptForMining(coinbaseScript);
//throw an error if no script was provided
if (!coinbaseScript.size())
throw std::runtime_error("No coinbase script available (mining requires a wallet)");
minerThreads = new boost::thread_group(); minerThreads = new boost::thread_group();
for (int i = 0; i < nThreads; i++) for (int i = 0; i < nThreads; i++)
minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); minerThreads->create_thread(boost::bind(&BitcoinMiner, boost::cref(chainparams), coinbaseScript));
} }
#endif // ENABLE_WALLET

View file

@ -11,6 +11,7 @@
#include <stdint.h> #include <stdint.h>
class CBlockIndex; class CBlockIndex;
class CChainParams;
class CReserveKey; class CReserveKey;
class CScript; class CScript;
class CWallet; class CWallet;
@ -24,10 +25,9 @@ struct CBlockTemplate
}; };
/** Run the miner threads */ /** Run the miner threads */
void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads); void GenerateBitcoins(bool fGenerate, int nThreads, const CChainParams& chainparams);
/** Generate a new block, without valid proof-of-work */ /** Generate a new block, without valid proof-of-work */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn); CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn);
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey);
/** Modify the extranonce in a block */ /** Modify the extranonce in a block */
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce); void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev); void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);

View file

@ -16,9 +16,6 @@
#include "rpcserver.h" #include "rpcserver.h"
#include "util.h" #include "util.h"
#include "validationinterface.h" #include "validationinterface.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include <stdint.h> #include <stdint.h>
@ -92,7 +89,6 @@ UniValue getnetworkhashps(const UniValue& params, bool fHelp)
return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
} }
#ifdef ENABLE_WALLET
UniValue getgenerate(const UniValue& params, bool fHelp) UniValue getgenerate(const UniValue& params, bool fHelp)
{ {
if (fHelp || params.size() != 0) if (fHelp || params.size() != 0)
@ -127,8 +123,6 @@ UniValue generate(const UniValue& params, bool fHelp)
+ HelpExampleCli("generate", "11") + HelpExampleCli("generate", "11")
); );
if (pwalletMain == NULL)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
if (!Params().MineBlocksOnDemand()) if (!Params().MineBlocksOnDemand())
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest"); throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest");
@ -136,7 +130,13 @@ UniValue generate(const UniValue& params, bool fHelp)
int nHeightEnd = 0; int nHeightEnd = 0;
int nHeight = 0; int nHeight = 0;
int nGenerate = params[0].get_int(); int nGenerate = params[0].get_int();
CReserveKey reservekey(pwalletMain);
CScript coinbaseScript;
GetMainSignals().ScriptForMining(coinbaseScript);
//throw an error if no script was provided
if (!coinbaseScript.size())
throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available (mining requires a wallet)");
{ // Don't keep cs_main locked { // Don't keep cs_main locked
LOCK(cs_main); LOCK(cs_main);
@ -148,9 +148,9 @@ UniValue generate(const UniValue& params, bool fHelp)
UniValue blockHashes(UniValue::VARR); UniValue blockHashes(UniValue::VARR);
while (nHeight < nHeightEnd) while (nHeight < nHeightEnd)
{ {
auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey)); auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(coinbaseScript));
if (!pblocktemplate.get()) if (!pblocktemplate.get())
throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet keypool empty"); throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
CBlock *pblock = &pblocktemplate->block; CBlock *pblock = &pblocktemplate->block;
{ {
LOCK(cs_main); LOCK(cs_main);
@ -170,7 +170,6 @@ UniValue generate(const UniValue& params, bool fHelp)
return blockHashes; return blockHashes;
} }
UniValue setgenerate(const UniValue& params, bool fHelp) UniValue setgenerate(const UniValue& params, bool fHelp)
{ {
if (fHelp || params.size() < 1 || params.size() > 2) if (fHelp || params.size() < 1 || params.size() > 2)
@ -193,8 +192,6 @@ UniValue setgenerate(const UniValue& params, bool fHelp)
+ HelpExampleRpc("setgenerate", "true, 1") + HelpExampleRpc("setgenerate", "true, 1")
); );
if (pwalletMain == NULL)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
if (Params().MineBlocksOnDemand()) if (Params().MineBlocksOnDemand())
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Use the generate method instead of setgenerate on this network"); throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Use the generate method instead of setgenerate on this network");
@ -212,12 +209,10 @@ UniValue setgenerate(const UniValue& params, bool fHelp)
mapArgs["-gen"] = (fGenerate ? "1" : "0"); mapArgs["-gen"] = (fGenerate ? "1" : "0");
mapArgs ["-genproclimit"] = itostr(nGenProcLimit); mapArgs ["-genproclimit"] = itostr(nGenProcLimit);
GenerateBitcoins(fGenerate, pwalletMain, nGenProcLimit); GenerateBitcoins(fGenerate, nGenProcLimit, Params());
return NullUniValue; return NullUniValue;
} }
#endif
UniValue getmininginfo(const UniValue& params, bool fHelp) UniValue getmininginfo(const UniValue& params, bool fHelp)
{ {
@ -257,9 +252,7 @@ UniValue getmininginfo(const UniValue& params, bool fHelp)
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC())); obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("chain", Params().NetworkIDString()));
#ifdef ENABLE_WALLET
obj.push_back(Pair("generate", getgenerate(params, false))); obj.push_back(Pair("generate", getgenerate(params, false)));
#endif
return obj; return obj;
} }

View file

@ -306,12 +306,10 @@ static const CRPCCommand vRPCCommands[] =
{ "mining", "prioritisetransaction", &prioritisetransaction, true }, { "mining", "prioritisetransaction", &prioritisetransaction, true },
{ "mining", "submitblock", &submitblock, true }, { "mining", "submitblock", &submitblock, true },
#ifdef ENABLE_WALLET
/* Coin generation */ /* Coin generation */
{ "generating", "getgenerate", &getgenerate, true }, { "generating", "getgenerate", &getgenerate, true },
{ "generating", "setgenerate", &setgenerate, true }, { "generating", "setgenerate", &setgenerate, true },
{ "generating", "generate", &generate, true }, { "generating", "generate", &generate, true },
#endif
/* Raw transactions */ /* Raw transactions */
{ "rawtransactions", "createrawtransaction", &createrawtransaction, true }, { "rawtransactions", "createrawtransaction", &createrawtransaction, true },

View file

@ -19,9 +19,13 @@ void RegisterValidationInterface(CValidationInterface* pwalletIn) {
g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1)); g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn, _1)); g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn, _1));
g_signals.BlockChecked.connect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2)); g_signals.BlockChecked.connect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
g_signals.ScriptForMining.connect(boost::bind(&CValidationInterface::GetScriptForMining, pwalletIn, _1));
g_signals.BlockFound.connect(boost::bind(&CValidationInterface::UpdateRequestCount, pwalletIn, _1));
} }
void UnregisterValidationInterface(CValidationInterface* pwalletIn) { void UnregisterValidationInterface(CValidationInterface* pwalletIn) {
g_signals.BlockFound.disconnect(boost::bind(&CValidationInterface::UpdateRequestCount, pwalletIn, _1));
g_signals.ScriptForMining.disconnect(boost::bind(&CValidationInterface::GetScriptForMining, pwalletIn, _1));
g_signals.BlockChecked.disconnect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2)); g_signals.BlockChecked.disconnect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn, _1)); g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn, _1));
g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1)); g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
@ -31,6 +35,8 @@ void UnregisterValidationInterface(CValidationInterface* pwalletIn) {
} }
void UnregisterAllValidationInterfaces() { void UnregisterAllValidationInterfaces() {
g_signals.BlockFound.disconnect_all_slots();
g_signals.ScriptForMining.disconnect_all_slots();
g_signals.BlockChecked.disconnect_all_slots(); g_signals.BlockChecked.disconnect_all_slots();
g_signals.Broadcast.disconnect_all_slots(); g_signals.Broadcast.disconnect_all_slots();
g_signals.Inventory.disconnect_all_slots(); g_signals.Inventory.disconnect_all_slots();

View file

@ -10,6 +10,7 @@
class CBlock; class CBlock;
struct CBlockLocator; struct CBlockLocator;
class CScript;
class CTransaction; class CTransaction;
class CValidationInterface; class CValidationInterface;
class CValidationState; class CValidationState;
@ -34,6 +35,8 @@ protected:
virtual void Inventory(const uint256 &hash) {} virtual void Inventory(const uint256 &hash) {}
virtual void ResendWalletTransactions(int64_t nBestBlockTime) {} virtual void ResendWalletTransactions(int64_t nBestBlockTime) {}
virtual void BlockChecked(const CBlock&, const CValidationState&) {} virtual void BlockChecked(const CBlock&, const CValidationState&) {}
virtual void GetScriptForMining(CScript &script) {};
virtual void UpdateRequestCount(const CBlock&) {};
friend void ::RegisterValidationInterface(CValidationInterface*); friend void ::RegisterValidationInterface(CValidationInterface*);
friend void ::UnregisterValidationInterface(CValidationInterface*); friend void ::UnregisterValidationInterface(CValidationInterface*);
friend void ::UnregisterAllValidationInterfaces(); friend void ::UnregisterAllValidationInterfaces();
@ -52,6 +55,10 @@ struct CMainSignals {
boost::signals2::signal<void (int64_t nBestBlockTime)> Broadcast; boost::signals2::signal<void (int64_t nBestBlockTime)> Broadcast;
/** Notifies listeners of a block validation result */ /** Notifies listeners of a block validation result */
boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked; boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked;
/** Notifies listeners that a key for mining is required (coinbase) */
boost::signals2::signal<void (CScript &script)> ScriptForMining;
/** Notifies listeners that a block has been successfully mined */
boost::signals2::signal<void (const CBlock&)> BlockFound;
}; };
CMainSignals& GetMainSignals(); CMainSignals& GetMainSignals();

View file

@ -2583,6 +2583,17 @@ void CWallet::UpdatedTransaction(const uint256 &hashTx)
} }
} }
void CWallet::GetScriptForMining(CScript &script)
{
CReserveKey reservekey(this);
reservekey.KeepKey();
CPubKey pubkey;
if (!reservekey.GetReservedKey(pubkey))
return;
script = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
}
void CWallet::LockCoin(COutPoint& output) void CWallet::LockCoin(COutPoint& output)
{ {
AssertLockHeld(cs_wallet); // setLockedCoins AssertLockHeld(cs_wallet); // setLockedCoins

View file

@ -680,6 +680,13 @@ public:
} }
} }
void GetScriptForMining(CScript &script);
void UpdateRequestCount(const CBlock& block)
{
LOCK(cs_wallet);
mapRequestCount[block.GetHash()] = 0;
};
unsigned int GetKeyPoolSize() unsigned int GetKeyPoolSize()
{ {
AssertLockHeld(cs_wallet); // setKeyPool AssertLockHeld(cs_wallet); // setKeyPool