Revert mining changes in #5957

This reverts commit e2edf95cd3 6b04508e37 0df67f1f7a,
except the changes to the RPC tests.

A `generate` RPC call is introduced based on the old code.
This commit is contained in:
Wladimir J. van der Laan 2015-04-10 07:33:06 +02:00
parent 4ac79f99b0
commit 48265f3cf4
4 changed files with 97 additions and 91 deletions

View file

@ -87,7 +87,7 @@ void UpdateTime(CBlockHeader* pblock, const CBlockIndex* pindexPrev)
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
} }
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, CBlockIndex*& pindexPrev) CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
{ {
// Create new block // Create new block
auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
@ -132,7 +132,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, CBlockIndex*& pind
{ {
LOCK2(cs_main, mempool.cs); LOCK2(cs_main, mempool.cs);
pindexPrev = chainActive.Tip(); CBlockIndex* pindexPrev = chainActive.Tip();
const int nHeight = pindexPrev->nHeight + 1; const int nHeight = pindexPrev->nHeight + 1;
CCoinsViewCache view(pcoinsTip); CCoinsViewCache view(pcoinsTip);
@ -365,34 +365,45 @@ void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int&
// //
// ScanHash scans nonces looking for a hash with at least some zero bits. // ScanHash scans nonces looking for a hash with at least some zero bits.
// The nonce is usually preserved between calls, but periodically the block is // The nonce is usually preserved between calls, but periodically or if the
// rebuilt and nNonce starts over at zero. // nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at
// zero.
// //
bool static ScanHash(CBlockHeader *pblock, uint256 *phash) bool static ScanHash(const CBlockHeader *pblock, uint32_t& nNonce, uint256 *phash)
{ {
// Write the first 76 bytes of the block header to a double-SHA256 state.
CHash256 hasher;
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *pblock;
assert(ss.size() == 80);
hasher.Write((unsigned char*)&ss[0], 76);
while (true) { while (true) {
pblock->nNonce++; nNonce++;
*phash = pblock->GetHash();
// Write the last 4 bytes of the block header (the nonce) to a copy of
// the double-SHA256 state, and compute the result.
CHash256(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)phash);
// Return the nonce if the hash has at least some zero bits, // Return the nonce if the hash has at least some zero bits,
// caller will check if it has enough to reach the target // caller will check if it has enough to reach the target
if (((uint16_t*)phash)[15] == 0) if (((uint16_t*)phash)[15] == 0)
return true; return true;
// If nothing found after trying for a while, return false. // If nothing found after trying for a while, return -1
if ((pblock->nNonce & 0xfff) == 0) if ((nNonce & 0xfff) == 0)
return false; return false;
} }
} }
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, CBlockIndex*& pindexPrev) CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
{ {
CPubKey pubkey; CPubKey pubkey;
if (!reservekey.GetReservedKey(pubkey)) if (!reservekey.GetReservedKey(pubkey))
return NULL; return NULL;
CScript scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; CScript scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
return CreateNewBlock(scriptPubKey, pindexPrev); return CreateNewBlock(scriptPubKey);
} }
static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
@ -424,56 +435,6 @@ static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& rese
return true; return true;
} }
bool static ScanLoop(CBlock *pblock, CBlockIndex *pindexPrev, CWallet *pwallet, CReserveKey& reservekey)
{
UpdateTime(pblock, pindexPrev);
arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
uint256 hash;
if (ScanHash(pblock, &hash)) {
if (UintToArith256(hash) <= hashTarget) {
// Found a solution
SetThreadPriority(THREAD_PRIORITY_NORMAL);
LogPrintf("BitcoinMiner:\n");
LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex());
ProcessBlockFound(pblock, *pwallet, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
return true;
}
}
return false;
}
bool MineBlock(CWallet *pwallet, uint256& hash)
{
CReserveKey reservekey(pwallet);
unsigned int nExtraNonce = 0;
while (true) {
CBlockIndex *pindexPrev;
auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey, pindexPrev));
if (!pblocktemplate.get()) {
return false;
}
CBlock *pblock = &pblocktemplate->block;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
while (true) {
if (ScanLoop(pblock, pindexPrev, pwallet, reservekey)) {
hash = pblock->GetHash();
return true;
}
boost::this_thread::interruption_point();
if (pblock->nNonce >= 0xffff0000)
break;
}
}
}
void static BitcoinMiner(CWallet *pwallet) void static BitcoinMiner(CWallet *pwallet)
{ {
LogPrintf("BitcoinMiner started\n"); LogPrintf("BitcoinMiner started\n");
@ -497,9 +458,9 @@ void static BitcoinMiner(CWallet *pwallet)
// Create new block // Create new block
// //
unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrev; CBlockIndex* pindexPrev = chainActive.Tip();
auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey, pindexPrev)); auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
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");
@ -515,23 +476,52 @@ void static BitcoinMiner(CWallet *pwallet)
// Search // Search
// //
int64_t nStart = GetTime(); int64_t nStart = GetTime();
arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
uint256 hash;
uint32_t nNonce = 0;
while (true) { while (true) {
// Check if something found // Check if something found
if (ScanLoop(pblock, pindexPrev, pwallet, reservekey)) if (ScanHash(pblock, nNonce, &hash))
break; {
if (UintToArith256(hash) <= hashTarget)
{
// Found a solution
pblock->nNonce = nNonce;
assert(hash == pblock->GetHash());
SetThreadPriority(THREAD_PRIORITY_NORMAL);
LogPrintf("BitcoinMiner:\n");
LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex());
ProcessBlockFound(pblock, *pwallet, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// In regression test mode, stop mining after a block is found.
if (Params().MineBlocksOnDemand())
throw boost::thread_interrupted();
break;
}
}
// Check for stop or if block needs to be rebuilt // Check for stop or if block needs to be rebuilt
boost::this_thread::interruption_point(); boost::this_thread::interruption_point();
// Regtest mode doesn't require peers // Regtest mode doesn't require peers
if (vNodes.empty() && Params().MiningRequiresPeers()) if (vNodes.empty() && Params().MiningRequiresPeers())
break; break;
if (pblock->nNonce >= 0xffff0000) if (nNonce >= 0xffff0000)
break; break;
if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break; break;
if (pindexPrev != chainActive.Tip()) if (pindexPrev != chainActive.Tip())
break; break;
// Update nTime every few seconds
UpdateTime(pblock, pindexPrev);
if (Params().AllowMinDifficultyBlocks())
{
// Changing pblock->nTime can change work required on testnet:
hashTarget.SetCompact(pblock->nBits);
}
} }
} }
} }

View file

@ -24,11 +24,9 @@ struct CBlockTemplate
/** Run the miner threads */ /** Run the miner threads */
void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads); void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads);
/** Create a single block */
bool MineBlock(CWallet *pwallet, uint256& hash);
/** Generate a new block, without valid proof-of-work */ /** Generate a new block, without valid proof-of-work */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, CBlockIndex*& pindexPrev); CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn);
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, CBlockIndex*& pindexPrev); 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* block, const CBlockIndex* pindexPrev); void UpdateTime(CBlockHeader* block, const CBlockIndex* pindexPrev);

View file

@ -119,6 +119,7 @@ Value generate(const Array& params, bool fHelp)
throw runtime_error( throw runtime_error(
"generate numblocks\n" "generate numblocks\n"
"\nMine blocks immediately (before the RPC call returns)\n" "\nMine blocks immediately (before the RPC call returns)\n"
"\nNote: this function can only be used on the regtest network\n"
"1. numblocks (numeric) How many blocks are generated immediately.\n" "1. numblocks (numeric) How many blocks are generated immediately.\n"
"\nResult\n" "\nResult\n"
"[ blockhashes ] (array) hashes of blocks generated\n" "[ blockhashes ] (array) hashes of blocks generated\n"
@ -129,11 +130,14 @@ Value generate(const Array& params, bool fHelp)
if (pwalletMain == NULL) if (pwalletMain == NULL)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
if (!Params().MineBlocksOnDemand())
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest");
int nHeightStart = 0; int nHeightStart = 0;
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);
{ // Don't keep cs_main locked { // Don't keep cs_main locked
LOCK(cs_main); LOCK(cs_main);
@ -141,18 +145,33 @@ Value generate(const Array& params, bool fHelp)
nHeight = nHeightStart; nHeight = nHeightStart;
nHeightEnd = nHeightStart+nGenerate; nHeightEnd = nHeightStart+nGenerate;
} }
unsigned int nExtraNonce = 0;
Array blockHashes; Array blockHashes;
while (nHeight < nHeightEnd) { while (nHeight < nHeightEnd)
uint256 hash; {
if (!MineBlock(pwalletMain, hash)) auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
if (!pblocktemplate.get())
throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet keypool empty"); throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet keypool empty");
CBlock *pblock = &pblocktemplate->block;
{
LOCK(cs_main);
IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
}
while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
// Yes, there is a chance every nonce could fail to satisfy the -regtest
// target -- 1 in 2^(2^32). That ain't gonna happen.
++pblock->nNonce;
}
CValidationState state;
if (!ProcessNewBlock(state, NULL, pblock))
throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
++nHeight; ++nHeight;
blockHashes.push_back(hash.GetHex()); blockHashes.push_back(pblock->GetHash().GetHex());
} }
return blockHashes; return blockHashes;
} }
Value setgenerate(const Array& params, bool fHelp) Value setgenerate(const Array& params, bool fHelp)
{ {
if (fHelp || params.size() < 1 || params.size() > 2) if (fHelp || params.size() < 1 || params.size() > 2)
@ -475,7 +494,7 @@ Value getblocktemplate(const Array& params, bool fHelp)
// Store the pindexBest used before CreateNewBlock, to avoid races // Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew; CBlockIndex* pindexPrevNew = chainActive.Tip();
nStart = GetTime(); nStart = GetTime();
// Create new block // Create new block
@ -485,7 +504,7 @@ Value getblocktemplate(const Array& params, bool fHelp)
pblocktemplate = NULL; pblocktemplate = NULL;
} }
CScript scriptDummy = CScript() << OP_TRUE; CScript scriptDummy = CScript() << OP_TRUE;
pblocktemplate = CreateNewBlock(scriptDummy, pindexPrevNew); pblocktemplate = CreateNewBlock(scriptDummy);
if (!pblocktemplate) if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");

View file

@ -62,8 +62,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
Checkpoints::fEnabled = false; Checkpoints::fEnabled = false;
// Simple block creation, nothing special yet: // Simple block creation, nothing special yet:
CBlockIndex* pindexPrev; BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev));
// We can't make transactions until we have inputs // We can't make transactions until we have inputs
// Therefore, load 100 blocks :) // Therefore, load 100 blocks :)
@ -91,7 +90,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
delete pblocktemplate; delete pblocktemplate;
// Just to make sure we can still make simple blocks // Just to make sure we can still make simple blocks
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
delete pblocktemplate; delete pblocktemplate;
// block sigops > limit: 1000 CHECKMULTISIG + 1 // block sigops > limit: 1000 CHECKMULTISIG + 1
@ -109,7 +108,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11)); mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11));
tx.vin[0].prevout.hash = hash; tx.vin[0].prevout.hash = hash;
} }
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
delete pblocktemplate; delete pblocktemplate;
mempool.clear(); mempool.clear();
@ -129,14 +128,14 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11)); mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11));
tx.vin[0].prevout.hash = hash; tx.vin[0].prevout.hash = hash;
} }
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
delete pblocktemplate; delete pblocktemplate;
mempool.clear(); mempool.clear();
// orphan in mempool // orphan in mempool
hash = tx.GetHash(); hash = tx.GetHash();
mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11)); mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
delete pblocktemplate; delete pblocktemplate;
mempool.clear(); mempool.clear();
@ -154,7 +153,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
tx.vout[0].nValue = 5900000000LL; tx.vout[0].nValue = 5900000000LL;
hash = tx.GetHash(); hash = tx.GetHash();
mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11)); mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
delete pblocktemplate; delete pblocktemplate;
mempool.clear(); mempool.clear();
@ -165,7 +164,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
tx.vout[0].nValue = 0; tx.vout[0].nValue = 0;
hash = tx.GetHash(); hash = tx.GetHash();
mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11)); mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
delete pblocktemplate; delete pblocktemplate;
mempool.clear(); mempool.clear();
@ -183,7 +182,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
tx.vout[0].nValue -= 1000000; tx.vout[0].nValue -= 1000000;
hash = tx.GetHash(); hash = tx.GetHash();
mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11)); mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
delete pblocktemplate; delete pblocktemplate;
mempool.clear(); mempool.clear();
@ -197,17 +196,17 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
tx.vout[0].scriptPubKey = CScript() << OP_2; tx.vout[0].scriptPubKey = CScript() << OP_2;
hash = tx.GetHash(); hash = tx.GetHash();
mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11)); mempool.addUnchecked(hash, CTxMemPoolEntry(tx, 11, GetTime(), 111.0, 11));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
delete pblocktemplate; delete pblocktemplate;
mempool.clear(); mempool.clear();
// subsidy changing // subsidy changing
int nHeight = chainActive.Height(); int nHeight = chainActive.Height();
chainActive.Tip()->nHeight = 209999; chainActive.Tip()->nHeight = 209999;
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
delete pblocktemplate; delete pblocktemplate;
chainActive.Tip()->nHeight = 210000; chainActive.Tip()->nHeight = 210000;
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
delete pblocktemplate; delete pblocktemplate;
chainActive.Tip()->nHeight = nHeight; chainActive.Tip()->nHeight = nHeight;
@ -239,7 +238,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
mempool.addUnchecked(hash, CTxMemPoolEntry(tx2, 11, GetTime(), 111.0, 11)); mempool.addUnchecked(hash, CTxMemPoolEntry(tx2, 11, GetTime(), 111.0, 11));
BOOST_CHECK(!IsFinalTx(tx2)); BOOST_CHECK(!IsFinalTx(tx2));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
// Neither tx should have make it into the template. // Neither tx should have make it into the template.
BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 1); BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 1);
@ -252,7 +251,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 1)); BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 1));
BOOST_CHECK(IsFinalTx(tx2)); BOOST_CHECK(IsFinalTx(tx2));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pindexPrev)); BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3); BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3);
delete pblocktemplate; delete pblocktemplate;