Introduce separate 'generate' RPC call

This commit is contained in:
Pieter Wuille 2015-03-31 20:28:28 -07:00
parent 0df67f1f7a
commit 6b04508e37
25 changed files with 162 additions and 142 deletions

View file

@ -29,14 +29,14 @@ class BIP66Test(BitcoinTestFramework):
cnt = self.nodes[0].getblockcount()
# Mine some old-version blocks
self.nodes[1].setgenerate(True, 100)
self.nodes[1].generate(100)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 100):
raise AssertionError("Failed to mine 100 version=2 blocks")
# Mine 750 new-version blocks
for i in xrange(15):
self.nodes[2].setgenerate(True, 50)
self.nodes[2].generate(50)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 850):
raise AssertionError("Failed to mine 750 version=3 blocks")
@ -44,7 +44,7 @@ class BIP66Test(BitcoinTestFramework):
# TODO: check that new DERSIG rules are not enforced
# Mine 1 new-version block
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 851):
raise AssertionFailure("Failed to mine a version=3 blocks")
@ -53,26 +53,26 @@ class BIP66Test(BitcoinTestFramework):
# Mine 198 new-version blocks
for i in xrange(2):
self.nodes[2].setgenerate(True, 99)
self.nodes[2].generate(99)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 1049):
raise AssertionError("Failed to mine 198 version=3 blocks")
# Mine 1 old-version block
self.nodes[1].setgenerate(True, 1)
self.nodes[1].generate(1)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 1050):
raise AssertionError("Failed to mine a version=2 block after 949 version=3 blocks")
# Mine 1 new-version blocks
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 1051):
raise AssertionError("Failed to mine a version=3 block")
# Mine 1 old-version blocks
try:
self.nodes[1].setgenerate(True, 1)
self.nodes[1].generate(1)
raise AssertionError("Succeeded to mine a version=2 block after 950 version=3 blocks")
except JSONRPCException:
pass
@ -81,7 +81,7 @@ class BIP66Test(BitcoinTestFramework):
raise AssertionError("Accepted a version=2 block after 950 version=3 blocks")
# Mine 1 new-version blocks
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 1052):
raise AssertionError("Failed to mine a version=3 block")

View file

@ -84,11 +84,11 @@ WaitPeers "$B1ARGS" 1
# 2 block, 50 XBT each == 100 XBT
# These will be transactions "A" and "B"
$CLI $B1ARGS setgenerate true 2
$CLI $B1ARGS generate 2
WaitBlocks
# 100 blocks, 0 mature == 0 XBT
$CLI $B2ARGS setgenerate true 100
$CLI $B2ARGS generate 100
WaitBlocks
CheckBalance "$B1ARGS" 100
@ -130,7 +130,7 @@ WaitPeers "$B1ARGS" 1
# Having B2 mine the next block puts the mutated
# transaction C in the chain:
$CLI $B2ARGS setgenerate true 1
$CLI $B2ARGS generate 1
WaitBlocks
# B1 should still be able to spend 100, because D is conflicted

View file

@ -34,12 +34,12 @@ class ForkNotifyTest(BitcoinTestFramework):
def run_test(self):
# Mine 51 up-version blocks
self.nodes[1].setgenerate(True, 51)
self.nodes[1].generate(51)
self.sync_all()
# -alertnotify should trigger on the 51'st,
# but mine and sync another to give
# -alertnotify time to write
self.nodes[1].setgenerate(True, 1)
self.nodes[1].generate(1)
self.sync_all()
with open(self.alert_filename, 'r') as f:
@ -49,9 +49,9 @@ class ForkNotifyTest(BitcoinTestFramework):
raise AssertionError("-alertnotify did not warn of up-version blocks")
# Mine more up-version blocks, should not get more alerts:
self.nodes[1].setgenerate(True, 1)
self.nodes[1].generate(1)
self.sync_all()
self.nodes[1].setgenerate(True, 1)
self.nodes[1].generate(1)
self.sync_all()
with open(self.alert_filename, 'r') as f:

View file

@ -51,7 +51,7 @@ class GetBlockTemplateLPTest(BitcoinTestFramework):
def run_test(self):
print "Warning: this test will take about 70 seconds in the best case. Be patient."
self.nodes[0].setgenerate(True, 10)
self.nodes[0].generate(10)
templat = self.nodes[0].getblocktemplate()
longpollid = templat['longpollid']
# longpollid should not change between successive invocations if nothing else happens
@ -66,7 +66,7 @@ class GetBlockTemplateLPTest(BitcoinTestFramework):
assert(thr.is_alive())
# Test 2: test that longpoll will terminate if another node generates a block
self.nodes[1].setgenerate(True, 1) # generate a block on another node
self.nodes[1].generate(1) # generate a block on another node
# check that thread will exit now that new transaction entered mempool
thr.join(5) # wait 5 seconds or until thread exits
assert(not thr.is_alive())
@ -74,7 +74,7 @@ class GetBlockTemplateLPTest(BitcoinTestFramework):
# Test 3: test that longpoll will terminate if we generate a block ourselves
thr = LongpollThread(self.nodes[0])
thr.start()
self.nodes[0].setgenerate(True, 1) # generate a block on another node
self.nodes[0].generate(1) # generate a block on another node
thr.join(5) # wait 5 seconds or until thread exits
assert(not thr.is_alive())

View file

@ -95,7 +95,7 @@ class GetBlockTemplateProposalTest(BitcoinTestFramework):
def run_test(self):
node = self.nodes[0]
node.setgenerate(True, 1) # Mine a block to leave initial block download
node.generate(1) # Mine a block to leave initial block download
tmpl = node.getblocktemplate()
if 'coinbasetxn' not in tmpl:
rawcoinbase = encodeUNum(tmpl['height'])

View file

@ -23,8 +23,8 @@ class GetChainTipsTest (BitcoinTestFramework):
# Split the network and build two chains of different lengths.
self.split_network ()
self.nodes[0].setgenerate (True, 10);
self.nodes[2].setgenerate (True, 20);
self.nodes[0].generate(10);
self.nodes[2].generate(20);
self.sync_all ()
tips = self.nodes[1].getchaintips ()

View file

@ -28,12 +28,12 @@ class InvalidateTest(BitcoinTestFramework):
def run_test(self):
print "Make sure we repopulate setBlockIndexCandidates after InvalidateBlock:"
print "Mine 4 blocks on Node 0"
self.nodes[0].setgenerate(True, 4)
self.nodes[0].generate(4)
assert(self.nodes[0].getblockcount() == 4)
besthash = self.nodes[0].getbestblockhash()
print "Mine competing 6 blocks on Node 1"
self.nodes[1].setgenerate(True, 6)
self.nodes[1].generate(6)
assert(self.nodes[1].getblockcount() == 6)
print "Connect nodes to force a reorg"
@ -61,7 +61,7 @@ class InvalidateTest(BitcoinTestFramework):
self.nodes[2].invalidateblock(self.nodes[2].getblockhash(3))
assert(self.nodes[2].getblockcount() == 2)
print "..and then mine a block"
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
print "Verify all nodes are at the right height"
time.sleep(5)
for i in xrange(3):

View file

@ -44,7 +44,7 @@ class ListTransactionsTest(BitcoinTestFramework):
{"txid":txid},
{"category":"receive","account":"","amount":Decimal("0.1"),"confirmations":0})
# mine a block, confirmations should change:
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
self.sync_all()
check_array_result(self.nodes[0].listtransactions(),
{"txid":txid},

View file

@ -41,7 +41,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
# Mine three blocks. After this, nodes[0] blocks
# 101, 102, and 103 are spend-able.
new_blocks = self.nodes[1].setgenerate(True, 4)
new_blocks = self.nodes[1].generate(4)
self.sync_all()
node0_address = self.nodes[0].getnewaddress()
@ -62,7 +62,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
# Broadcast and mine spend_102 and 103:
spend_102_id = self.nodes[0].sendrawtransaction(spend_102_raw)
spend_103_id = self.nodes[0].sendrawtransaction(spend_103_raw)
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
# Create 102_1 and 103_1:
spend_102_1_raw = self.create_tx(spend_102_id, node1_address, 50)
@ -70,7 +70,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
# Broadcast and mine 103_1:
spend_103_1_id = self.nodes[0].sendrawtransaction(spend_103_1_raw)
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
# ... now put spend_101 and spend_102_1 in memory pools:
spend_101_id = self.nodes[0].sendrawtransaction(spend_101_raw)

View file

@ -51,12 +51,12 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
spends1_id = [ self.nodes[0].sendrawtransaction(tx) for tx in spends1_raw ]
blocks = []
blocks.extend(self.nodes[0].setgenerate(True, 1))
blocks.extend(self.nodes[0].generate(1))
spends2_raw = [ self.create_tx(txid, node0_address, 49.99) for txid in spends1_id ]
spends2_id = [ self.nodes[0].sendrawtransaction(tx) for tx in spends2_raw ]
blocks.extend(self.nodes[0].setgenerate(True, 1))
blocks.extend(self.nodes[0].generate(1))
# mempool should be empty, all txns confirmed
assert_equal(set(self.nodes[0].getrawmempool()), set())
@ -76,7 +76,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
assert(tx["confirmations"] == 0)
# Generate another block, they should all get mined
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
# mempool should be empty, all txns confirmed
assert_equal(set(self.nodes[0].getrawmempool()), set())
for txid in spends1_id+spends2_id:

View file

@ -58,7 +58,7 @@ class MempoolSpendCoinbaseTest(BitcoinTestFramework):
assert_equal(self.nodes[0].getrawmempool(), [ spend_101_id ])
# mine a block, spend_101 should get confirmed
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
assert_equal(set(self.nodes[0].getrawmempool()), set())
# ... and now height 102 can be spent:

View file

@ -69,7 +69,7 @@ class ReceivedByTest(BitcoinTestFramework):
{ },
True)
#Bury Tx under 10 block so it will be returned by listreceivedbyaddress
self.nodes[1].setgenerate(True, 10)
self.nodes[1].generate(10)
self.sync_all()
check_array_result(self.nodes[1].listreceivedbyaddress(),
{"address":addr},
@ -106,7 +106,7 @@ class ReceivedByTest(BitcoinTestFramework):
raise AssertionError("Wrong balance returned by getreceivedbyaddress, %0.2f"%(balance))
#Bury Tx under 10 block so it will be returned by the default getreceivedbyaddress
self.nodes[1].setgenerate(True, 10)
self.nodes[1].generate(10)
self.sync_all()
balance = self.nodes[1].getreceivedbyaddress(addr)
if balance != Decimal("0.1"):
@ -136,7 +136,7 @@ class ReceivedByTest(BitcoinTestFramework):
if balance != balance_by_account:
raise AssertionError("Wrong balance returned by getreceivedbyaccount, %0.2f"%(balance))
self.nodes[1].setgenerate(True, 10)
self.nodes[1].generate(10)
self.sync_all()
# listreceivedbyaccount should return updated account balance
check_array_result(self.nodes[1].listreceivedbyaccount(),

View file

@ -90,7 +90,7 @@ class RESTTest (BitcoinTestFramework):
self.sync_all()
# now mine the transactions
newblockhash = self.nodes[1].setgenerate(True, 1)
newblockhash = self.nodes[1].generate(1)
self.sync_all()
#check if the 3 tx show up in the new block

View file

@ -51,7 +51,7 @@ class EstimateFeeTest(BitcoinTestFramework):
# Mine blocks with node2 until the memory pool clears:
count_start = self.nodes[2].getblockcount()
while len(self.nodes[2].getrawmempool()) > 0:
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
self.sync_all()
all_estimates = [ self.nodes[0].estimatefee(i) for i in range(1,20) ]
@ -70,7 +70,7 @@ class EstimateFeeTest(BitcoinTestFramework):
Decimal("0.0"), min_fee, 20)
tx_kbytes = (len(txhex)/2)/1000.0
fees_per_kb.append(float(fee)/tx_kbytes)
self.nodes[1].setgenerate(True, 1)
self.nodes[1].generate(1)
self.sync_all()
all_estimates = [ self.nodes[0].estimatefee(i) for i in range(1,20) ]
@ -81,7 +81,7 @@ class EstimateFeeTest(BitcoinTestFramework):
# Finish by mining a normal-sized block:
while len(self.nodes[0].getrawmempool()) > 0:
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
self.sync_all()
final_estimates = [ self.nodes[0].estimatefee(i) for i in range(1,20) ]

View file

@ -58,7 +58,7 @@ class TxnMallTest(BitcoinTestFramework):
# Have node0 mine a block:
if (self.options.mine_block):
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
sync_blocks(self.nodes[0:2])
tx1 = self.nodes[0].gettransaction(txid1)
@ -88,11 +88,11 @@ class TxnMallTest(BitcoinTestFramework):
# Now give doublespend to miner:
mutated_txid = self.nodes[2].sendrawtransaction(doublespend["hex"])
# ... mine a block...
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
# Reconnect the split network, and sync chain:
connect_nodes(self.nodes[1], 2)
self.nodes[2].setgenerate(True, 1) # Mine another block to make sure we sync
self.nodes[2].generate(1) # Mine another block to make sure we sync
sync_blocks(self.nodes)
# Re-fetch transaction info:

View file

@ -109,7 +109,7 @@ def initialize_chain(test_dir):
for peer in range(4):
for j in range(25):
set_node_times(rpcs, block_time)
rpcs[peer].setgenerate(True, 1)
rpcs[peer].generate(1)
block_time += 10*60
# Must sync before next peer starts generating blocks
sync_blocks(rpcs)

View file

@ -40,14 +40,14 @@ class WalletTest (BitcoinTestFramework):
def run_test (self):
print "Mining blocks..."
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
walletinfo = self.nodes[0].getwalletinfo()
assert_equal(walletinfo['immature_balance'], 50)
assert_equal(walletinfo['balance'], 0)
self.sync_all()
self.nodes[1].setgenerate(True, 101)
self.nodes[1].generate(101)
self.sync_all()
assert_equal(self.nodes[0].getbalance(), 50)
@ -63,11 +63,11 @@ class WalletTest (BitcoinTestFramework):
assert_equal(walletinfo['immature_balance'], 0)
# Have node0 mine a block, thus they will collect their own fee.
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
self.sync_all()
# Have node1 generate 100 blocks (so node0 can recover the fee)
self.nodes[1].setgenerate(True, 100)
self.nodes[1].generate(100)
self.sync_all()
# node0 should end up with 100 btc in block rewards plus fees, but
@ -96,7 +96,7 @@ class WalletTest (BitcoinTestFramework):
self.nodes[1].sendrawtransaction(txns_to_send[1]["hex"], True)
# Have node1 mine a block to confirm transactions:
self.nodes[1].setgenerate(True, 1)
self.nodes[1].generate(1)
self.sync_all()
assert_equal(self.nodes[0].getbalance(), 0)
@ -107,28 +107,28 @@ class WalletTest (BitcoinTestFramework):
address = self.nodes[0].getnewaddress("test")
self.nodes[2].settxfee(Decimal('0.001'))
txid = self.nodes[2].sendtoaddress(address, 10, "", "", False)
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
self.sync_all()
assert_equal(self.nodes[2].getbalance(), Decimal('89.99900000'))
assert_equal(self.nodes[0].getbalance(), Decimal('10.00000000'))
# Send 10 BTC with subtract fee from amount
txid = self.nodes[2].sendtoaddress(address, 10, "", "", True)
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
self.sync_all()
assert_equal(self.nodes[2].getbalance(), Decimal('79.99900000'))
assert_equal(self.nodes[0].getbalance(), Decimal('19.99900000'))
# Sendmany 10 BTC
txid = self.nodes[2].sendmany('from1', {address: 10}, 0, "", [])
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
self.sync_all()
assert_equal(self.nodes[2].getbalance(), Decimal('69.99800000'))
assert_equal(self.nodes[0].getbalance(), Decimal('29.99900000'))
# Sendmany 10 BTC with subtract fee from amount
txid = self.nodes[2].sendmany('from1', {address: 10}, 0, "", [address])
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
self.sync_all()
assert_equal(self.nodes[2].getbalance(), Decimal('59.99800000'))
assert_equal(self.nodes[0].getbalance(), Decimal('39.99800000'))

View file

@ -77,7 +77,7 @@ class WalletBackupTest(BitcoinTestFramework):
# Have the miner (node3) mine a block.
# Must sync mempools before mining.
sync_mempools(self.nodes)
self.nodes[3].setgenerate(True, 1)
self.nodes[3].generate(1)
# As above, this mirrors the original bash test.
def start_three(self):
@ -101,13 +101,13 @@ class WalletBackupTest(BitcoinTestFramework):
def run_test(self):
logging.info("Generating initial blockchain")
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
sync_blocks(self.nodes)
self.nodes[1].setgenerate(True, 1)
self.nodes[1].generate(1)
sync_blocks(self.nodes)
self.nodes[2].setgenerate(True, 1)
self.nodes[2].generate(1)
sync_blocks(self.nodes)
self.nodes[3].setgenerate(True, 100)
self.nodes[3].generate(100)
sync_blocks(self.nodes)
assert_equal(self.nodes[0].getbalance(), 50)
@ -134,7 +134,7 @@ class WalletBackupTest(BitcoinTestFramework):
self.do_one_round()
# Generate 101 more blocks, so any fees paid mature
self.nodes[3].setgenerate(True, 101)
self.nodes[3].generate(101)
self.sync_all()
balance0 = self.nodes[0].getbalance()

View file

@ -23,9 +23,9 @@ class ZapWalletTXesTest (BitcoinTestFramework):
def run_test (self):
print "Mining blocks..."
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
self.sync_all()
self.nodes[1].setgenerate(True, 101)
self.nodes[1].generate(101)
self.sync_all()
assert_equal(self.nodes[0].getbalance(), 50)
@ -33,7 +33,7 @@ class ZapWalletTXesTest (BitcoinTestFramework):
txid0 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)
txid1 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)
self.sync_all()
self.nodes[0].setgenerate(True, 1)
self.nodes[0].generate(1)
self.sync_all()
txid2 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)

View file

@ -372,8 +372,7 @@ bool static ScanHash(CBlockHeader *pblock, uint256 *phash)
{
while (true) {
pblock->nNonce++;
*phash = (CHashWriter(SER_GETHASH, 0) << *pblock).GetHash();
*phash = pblock->GetHash();
// Return the nonce if the hash has at least some zero bits,
// caller will check if it has enough to reach the target
@ -425,6 +424,56 @@ static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& rese
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 = chainActive.Tip(); // Actually needs cs_main...
auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
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)
{
LogPrintf("BitcoinMiner started\n");
@ -448,7 +497,7 @@ void static BitcoinMiner(CWallet *pwallet)
// Create new block
//
unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrev = chainActive.Tip();
CBlockIndex* pindexPrev = chainActive.Tip(); // Actually needs cs_main...
auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
if (!pblocktemplate.get())
@ -466,30 +515,10 @@ void static BitcoinMiner(CWallet *pwallet)
// Search
//
int64_t nStart = GetTime();
arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
uint256 hash;
while (true) {
// Check if something found
if (ScanHash(pblock, &hash))
{
if (UintToArith256(hash) <= hashTarget)
{
// Found a solution
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();
if (ScanLoop(pblock, pindexPrev, pwallet, reservekey))
break;
}
}
// Check for stop or if block needs to be rebuilt
boost::this_thread::interruption_point();
@ -503,13 +532,6 @@ void static BitcoinMiner(CWallet *pwallet)
if (pindexPrev != chainActive.Tip())
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,6 +24,8 @@ struct CBlockTemplate
/** Run the miner threads */
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 */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn);
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey);

View file

@ -29,6 +29,7 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "getaddednodeinfo", 0 },
{ "setgenerate", 0 },
{ "setgenerate", 1 },
{ "generate", 0 },
{ "getnetworkhashps", 0 },
{ "getnetworkhashps", 1 },
{ "sendtoaddress", 1 },

View file

@ -113,6 +113,45 @@ Value getgenerate(const Array& params, bool fHelp)
return GetBoolArg("-gen", false);
}
Value generate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"generate numblocks\n"
"\nMine blocks immediately (before the RPC call returns)\n"
"1. numblocks (numeric) How many blocks are generated immediately.\n"
"\nResult\n"
"[ blockhashes ] (array) hashes of blocks generated\n"
"\nExamples:\n"
"\nGenerate 11 blocks\n"
+ HelpExampleCli("generate", "11")
);
if (pwalletMain == NULL)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
int nHeightStart = 0;
int nHeightEnd = 0;
int nHeight = 0;
int nGenerate = params[0].get_int();
{ // Don't keep cs_main locked
LOCK(cs_main);
nHeightStart = chainActive.Height();
nHeight = nHeightStart;
nHeightEnd = nHeightStart+nGenerate;
}
Array blockHashes;
while (nHeight < nHeightEnd) {
uint256 hash;
if (!MineBlock(pwalletMain, hash))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet keypool empty");
++nHeight;
blockHashes.push_back(hash.GetHex());
}
return blockHashes;
}
Value setgenerate(const Array& params, bool fHelp)
{
@ -125,9 +164,6 @@ Value setgenerate(const Array& params, bool fHelp)
"\nArguments:\n"
"1. generate (boolean, required) Set to true to turn on generation, off to turn off.\n"
"2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
" Note: in -regtest mode, genproclimit controls how many blocks are generated immediately.\n"
"\nResult\n"
"[ blockhashes ] (array, -regtest only) hashes of blocks generated\n"
"\nExamples:\n"
"\nSet the generation on with a limit of one processor\n"
+ HelpExampleCli("setgenerate", "true 1") +
@ -154,52 +190,9 @@ Value setgenerate(const Array& params, bool fHelp)
fGenerate = false;
}
// -regtest mode: don't return until nGenProcLimit blocks are generated
if (fGenerate && Params().MineBlocksOnDemand())
{
int nHeightStart = 0;
int nHeightEnd = 0;
int nHeight = 0;
int nGenerate = (nGenProcLimit > 0 ? nGenProcLimit : 1);
CReserveKey reservekey(pwalletMain);
{ // Don't keep cs_main locked
LOCK(cs_main);
nHeightStart = chainActive.Height();
nHeight = nHeightStart;
nHeightEnd = nHeightStart+nGenerate;
}
unsigned int nExtraNonce = 0;
Array blockHashes;
while (nHeight < nHeightEnd)
{
auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
if (!pblocktemplate.get())
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;
blockHashes.push_back(pblock->GetHash().GetHex());
}
return blockHashes;
}
else // Not -regtest: start generate thread, return immediately
{
mapArgs["-gen"] = (fGenerate ? "1" : "0");
mapArgs ["-genproclimit"] = itostr(nGenProcLimit);
GenerateBitcoins(fGenerate, pwalletMain, nGenProcLimit);
}
return Value::null;
}

View file

@ -312,6 +312,7 @@ static const CRPCCommand vRPCCommands[] =
/* Coin generation */
{ "generating", "getgenerate", &getgenerate, true, false },
{ "generating", "setgenerate", &setgenerate, true, false },
{ "generating", "generate", &generate, true, false },
#endif
/* Raw transactions */

View file

@ -162,6 +162,7 @@ extern json_spirit::Value importwallet(const json_spirit::Array& params, bool fH
extern json_spirit::Value getgenerate(const json_spirit::Array& params, bool fHelp); // in rpcmining.cpp
extern json_spirit::Value setgenerate(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value generate(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getnetworkhashps(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getmininginfo(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value prioritisetransaction(const json_spirit::Array& params, bool fHelp);