Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/kernel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,11 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeMod
{
nStakeModifier = 0;
fGeneratedStakeModifier = false;

// modifier 0 on RegTest
if (Params().NetworkID() == CBaseChainParams::REGTEST) {
return true;
}
if (!pindexPrev) {
fGeneratedStakeModifier = true;
return true; // genesis block's modifier is 0
Expand Down Expand Up @@ -240,6 +245,10 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeMod
bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake)
{
nStakeModifier = 0;
// modifier 0 on RegTest
if (Params().NetworkID() == CBaseChainParams::REGTEST) {
return true;
}
if (!mapBlockIndex.count(hashBlockFrom))
return error("%s : block not indexed", __func__);
const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
Expand Down
7 changes: 5 additions & 2 deletions src/wallet/wallet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -472,8 +472,11 @@ bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
const uint256& wtxid = it->second;
std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
if (mit != mapWallet.end()) {
int depth = mit->second.GetDepthInMainChain();
if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
bool fConflicted;
const int nDepth = mit->second.GetDepthAndMempool(fConflicted);
// not in mempool txes can spend coins only if not coinstakes
const bool fConflictedCoinstake = fConflicted && mit->second.IsCoinStake();
if (nDepth > 0 || (nDepth == 0 && !mit->second.isAbandoned() && !fConflictedCoinstake) )
return true; // Spent
}
}
Expand Down
1 change: 1 addition & 0 deletions test/functional/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@

# vv Tests less than 5m vv
'wallet_abandonconflict.py',
'wallet_reorg-stake.py',
'rpc_rawtransaction.py',
'wallet_zapwallettxes.py',
'wallet_keypool_topup.py',
Expand Down
125 changes: 125 additions & 0 deletions test/functional/wallet_reorg-stake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
# Copyright (c) 2019 The PIVX Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.

from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import sync_blocks, sync_mempools, connect_nodes_bi, \
p2p_port, assert_equal, assert_raises_rpc_error
import urllib.parse

class ReorgStakeTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [["-minrelaytxfee=0.00001"],[]]


def generateBatchBlocks(self, nodeid, limit, batch_size = 5):
i = 0
while i < limit:
i += batch_size
if i <= limit:
self.nodes[nodeid].generate(batch_size)
else:
self.nodes[nodeid].generate(batch_size-i+limit)

def findUtxoInList(self, txid, vout, utxo_list):
for x in utxo_list:
if x["txid"] == txid and x["vout"] == vout:
return True, x
return False, None


def run_test(self):
# NLAST_POW_BLOCK = 250 - so mine 125 blocks each node (25 consecutive blocks for 5 times)
NMATURITY = 100
self.log.info("Mining 250 blocks (125 with node 0 and 125 with node 1)...")
for i in range(5):
self.generateBatchBlocks(0, 25)
sync_blocks(self.nodes)
self.generateBatchBlocks(1, 25)
sync_blocks(self.nodes)
sync_mempools(self.nodes)

# Check balances
balance0 = self.nodes[0].getbalance()
balance1 = self.nodes[1].getbalance()
# Last two 25-blocks bursts (for each node) are not mature: NMATURITY = 2 * (2 * 25)
assert_equal(balance0, 250.0 * (125 - 50))
assert_equal(balance1, 250.0 * (125 - 50))
self.log.info("Balances check out (%d, %d)" % (balance0, balance1))
initial_balance = balance0
initial_unspent = self.nodes[0].listunspent()

# PoS start reached (block 250) - disconnect nodes
self.nodes[0].disconnectnode(urllib.parse.urlparse(self.nodes[1].url).hostname + ":" + str(p2p_port(1)))
self.nodes[1].disconnectnode(urllib.parse.urlparse(self.nodes[0].url).hostname + ":" + str(p2p_port(0)))
self.log.info("Nodes disconnected")

# Stake one block with node-0 and save the stake input
self.log.info("Staking 1 block with node 0...")
self.nodes[0].generate(1)
last_block = self.nodes[0].getblock(self.nodes[0].getbestblockhash())
assert(len(last_block["tx"]) > 1) # a PoS block has at least two txes
coinstake_txid = last_block["tx"][1]
coinstake_tx = self.nodes[0].getrawtransaction(coinstake_txid, True)
assert(coinstake_tx["vout"][0]["scriptPubKey"]["hex"] == "") # first output of coinstake is empty
stakeinput = coinstake_tx["vin"][0]

# The stake input was unspent 1 block ago, now it's not
res, utxo = self.findUtxoInList(stakeinput["txid"], stakeinput["vout"], initial_unspent)
assert (res and utxo["spendable"])
res, utxo = self.findUtxoInList(stakeinput["txid"], stakeinput["vout"], self.nodes[0].listunspent())
assert (not res or not utxo["spendable"])
self.log.info("Coinstake input %s...%s-%d is no longer spendable." % (
stakeinput["txid"][:9], stakeinput["txid"][-4:], stakeinput["vout"]))

# Stake 10 more blocks with node-0 and check balances
self.log.info("Staking 10 more blocks with node 0...")
self.generateBatchBlocks(0, 10)
balance0 = initial_balance + 500 * 11 # mined blocks matured + staked blocks (250*11 + 250*11)
assert_equal(self.nodes[0].getbalance(), balance0)
self.log.info("Balance for node 0 checks out: %d" % balance0)

# verify that the stakeinput can't be spent
rawtx_unsigned = self.nodes[0].createrawtransaction(
[{"txid": str(stakeinput["txid"]), "vout": int(stakeinput["vout"])}],
{"xxncEuJK27ygNh7imNfaX8JV6ZQUnoBqzN": 249.99})
rawtx = self.nodes[0].signrawtransaction(rawtx_unsigned)
assert(rawtx["complete"])
assert_raises_rpc_error(-25, "Missing inputs",self.nodes[0].sendrawtransaction, rawtx["hex"])

# Stake 12 blocks with node-1
self.log.info("Staking 12 blocks with node 1...")
self.generateBatchBlocks(1, 12)
balance1 += 250 * 12 # staked blocks only (250*12)
assert_equal(self.nodes[1].getbalance(), balance1)
self.log.info("Balance for node 1 checks out: %d" % balance1)
new_best_hash = self.nodes[1].getbestblockhash()

# re-connect and sync nodes and check that node-0 gets on the other chain
self.log.info("Connecting and syncing nodes...")
connect_nodes_bi(self.nodes, 0, 1)
sync_blocks(self.nodes)
assert_equal(self.nodes[0].getbestblockhash(), new_best_hash)

# check balance of node-0
balance0 = initial_balance + 250 * 12 # mined blocks matured (250*12)
assert_equal(self.nodes[0].getbalance(), balance0) # <--- !!! THIS FAILS before PR #1043
self.log.info("Balance for node 0 checks out: %d" % balance0)

# check that NOW the original stakeinput is present and spendable
res, utxo = self.findUtxoInList(stakeinput["txid"], stakeinput["vout"], self.nodes[0].listunspent())
assert (res and utxo["spendable"]) # <--- !!! THIS FAILS before PR #1043
self.log.info("Coinstake input %s...%s-%d is spendable again." % (
stakeinput["txid"][:9], stakeinput["txid"][-4:], stakeinput["vout"]))
self.nodes[0].sendrawtransaction(rawtx["hex"])
self.nodes[1].generate(1)
sync_blocks(self.nodes)
res, utxo = self.findUtxoInList(stakeinput["txid"], stakeinput["vout"], self.nodes[0].listunspent())
assert (not res or not utxo["spendable"])


if __name__ == '__main__':
ReorgStakeTest().main()