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
4 changes: 4 additions & 0 deletions tests/test_monero_daemon_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,10 @@ def test_stop_mining(self, daemon: MoneroDaemon) -> None:
def test_get_mining_status(self, daemon: MoneroDaemon) -> None:
daemon.get_mining_status()

@pytest.mark.not_supported
def test_generate_blocks(self, daemon: MoneroDaemon) -> None:
daemon.generate_blocks('', 10, '', 0)

@pytest.mark.not_supported
def test_prune_blockchain(self, daemon: MoneroDaemon) -> None:
daemon.prune_blockchain(False)
Expand Down
7 changes: 7 additions & 0 deletions tests/test_monero_daemon_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -779,14 +779,21 @@ def test_get_hard_fork_information(self, daemon: MoneroDaemonRpc) -> None:
@pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
def test_get_alternative_chains(self, daemon: MoneroDaemonRpc) -> None:
alt_chains: list[MoneroAltChain] = daemon.get_alt_chains()
if len(alt_chains) == 0:
logger.warning("No alternative chain found!")

for alt_chain in alt_chains:
BlockUtils.test_alt_chain(alt_chain)

# Can get alternative block hashes
@pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
def test_get_alternative_block_ids(self, daemon: MoneroDaemonRpc) -> None:
alt_block_ids: list[str] = daemon.get_alt_block_hashes()
if len(alt_block_ids) == 0:
logger.warning("No alternative block ids found!")

for alt_block_id in alt_block_ids:
logger.debug(f"Testing alternarive block id: {alt_block_id}")
assert alt_block_id is not None
# TODO: common validation
assert 64, len(alt_block_id)
Expand Down
68 changes: 67 additions & 1 deletion tests/utils/blockchain_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from abc import ABC
from time import sleep
from monero import MoneroNetworkType
from monero import MoneroNetworkType, MoneroGenerateBlocksResult

from .string_utils import StringUtils
from .test_utils import TestUtils as Utils
Expand All @@ -11,6 +11,7 @@

logger: logging.Logger = logging.getLogger("BlockchainUtils")


# Blockchain utilities to be used in integration tests
class BlockchainUtils(ABC):
"""Blockchain utilities."""
Expand Down Expand Up @@ -126,3 +127,68 @@ def setup_blockchain(cls, network_type: MoneroNetworkType) -> None:
spammer.spam()
# wait for spammed txs to confirm
cls.wait_for_blocks(11)

# create an alternative chain on regtest
if Utils.REGTEST:
cls.reorg_blockchain()

@classmethod
def reorg_blockchain(cls, num_blocks: int = 3) -> int:
"""Force a blockchain reorganization and ensure it completes successfully (regtest only).

Forks the chain at the current tip: first mines a short chain on top of it, then mines
a longer alternate chain from the same fork point. Since the alternate chain has more
cumulative work, the daemon must reorg onto it, replacing the blocks of the original
chain.

:param int num_blocks: number of blocks to mine on the original chain before forking
(the alternate chain mines one more block than this to guarantee it wins the reorg).
:returns int: blockchain height after the reorg.
"""
assert num_blocks >= 1, f"Invalid number of blocks to reorg: {num_blocks}"

daemon = MiningUtils.get_daemon()

# mining must be stopped so it doesn't race with the forced reorg
stop_mining: bool = MiningUtils.try_stop_mining()

try:
# mark the fork point: the last common block between both chains
fork_header = daemon.get_last_block_header()
assert fork_header.hash is not None and fork_header.height is not None
fork_hash: str = fork_header.hash
fork_height: int = fork_header.height

# mine the original, shorter chain on top of the fork point
original: MoneroGenerateBlocksResult = daemon.generate_blocks(Utils.MINING_ADDRESS, num_blocks, fork_hash)
assert original.height == fork_height + num_blocks, \
f"Failed to build original chain: expected height {fork_height + num_blocks}, got {original.height}"
original_hash: str = daemon.get_block_hash(fork_height + 1)
logger.debug(f"Built original chain of {num_blocks} block(s) on top of height {fork_height}")

# mine a longer alternate chain from the same fork point to force a reorg
alt_num_blocks: int = num_blocks + 1
alt: MoneroGenerateBlocksResult = daemon.generate_blocks(Utils.MINING_ADDRESS, alt_num_blocks, fork_hash)
assert alt.height == fork_height + alt_num_blocks, \
f"Failed to build alternate chain: expected height {fork_height + alt_num_blocks}, got {alt.height}"
logger.debug(f"Built alternate chain of {alt_num_blocks} block(s) on top of height {fork_height}")
finally:
# restart mining, if it was active before
if stop_mining:
MiningUtils.try_start_mining()

# ensure the reorg was accepted: the active chain must now follow the heavier alternate fork
active_hash: str = daemon.get_block_hash(fork_height + 1)
assert active_hash != original_hash, \
"Reorg failed: block after the fork point was not replaced by the alternate chain"
assert active_hash in alt.block_hashes, \
"Reorg failed: active chain block is not part of the generated alternate chain"

original_header = daemon.get_block_header_by_hash(original_hash)
assert original_header.orphan_status is True, \
"Reorg failed: original chain block was not marked as orphaned"

reorg_height: int = daemon.get_height()
logger.debug(f"Blockchain reorg succeeded: active chain now at height {reorg_height}")

return reorg_height
Loading