Coverage for tests/utils/blockchain_utils.py: 90%

108 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 19:49 +0000

1import logging 

2 

3from abc import ABC 

4from time import sleep 

5from monero import MoneroNetworkType, MoneroGenerateBlocksResult, MoneroDaemonRpc, MoneroBlockHeader 

6 

7from .block_generation import is_generation_fast 

8from .string_utils import StringUtils 

9from .test_utils import TestUtils as Utils 

10from .mining_utils import MiningUtils 

11from .tx_spammer import TxSpammer 

12 

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

14 

15 

16class BlockchainUtils(ABC): 

17 """Blockchain utilities to be used in integration tests.""" 

18 

19 CHECK_BLOCK_TIMEOUT_SECONDS: int = 5 

20 """Timeout in seconds to check blockchain mining progress.""" 

21 

22 GENERATE_BLOCKS_PER_REQUEST: int = 5 

23 """Blocks that a request of generateblocks makes in regtest. At a high difficulty a block takes seconds, and a request has a timeout.""" 

24 

25 @classmethod 

26 def get_height(cls) -> int: 

27 """Get current blockchain height. 

28 

29 :returns int: current blockchain height. 

30 """ 

31 return MiningUtils.get_daemon().get_height() 

32 

33 @classmethod 

34 def has_reached_height(cls, height: int) -> bool: 

35 """Check if blockchain has reached height. 

36 

37 :param int height: blockchain height to check. 

38 :returns bool: `True` if blockchain has reached `height`. 

39 """ 

40 return height <= cls.get_height() 

41 

42 @classmethod 

43 def blockchain_is_ready(cls) -> bool: 

44 """Indicates if blockchain has reached minimum height for running tests. 

45 

46 :returns bool: `True` if blockchain is ready, `False` otherwise. 

47 """ 

48 # check if blockchain has reached minimum block height 

49 return cls.has_reached_height(Utils.MIN_BLOCK_HEIGHT) 

50 

51 @classmethod 

52 def wait_for_height(cls, height: int) -> int: 

53 """Wait for blockchain height. 

54 

55 :param int height: height to wait for. 

56 :returns int: blockchain height. 

57 """ 

58 daemon: MoneroDaemonRpc = MiningUtils.get_daemon() 

59 current_height: int = daemon.get_height() 

60 # check if already reached height 

61 if height <= current_height: 

62 # return last height 

63 return current_height 

64 

65 # on regtest with a low difficulty the blocks are generated, which makes the ones that are asked for and no more. The miner makes blocks 

66 # while the loop below sleeps, and at a low difficulty that is dozens of blocks: the chain grows by more than the tests want, and the 

67 # transactions of the setup, which some tests look for in the last 100 blocks, are left below them. At a high difficulty the miner is 

68 # faster than generating, so it mines. If something is mining already, its blocks are waited for 

69 if Utils.REGTEST and not MiningUtils.is_mining() and is_generation_fast(daemon): 

70 return cls._generate_blocks_until(daemon, current_height, height) 

71 

72 # start mining if not active 

73 stop_mining: bool = False 

74 if not MiningUtils.is_mining(): 

75 MiningUtils.start_mining() 

76 stop_mining = True 

77 

78 # wait until blockchain reaches desired height 

79 while current_height < height: 

80 p: str = StringUtils.get_percentage(current_height, height) 

81 logger.info(f"[{p}] Waiting for blockchain height ({current_height}/{height})") 

82 block: MoneroBlockHeader = daemon.wait_for_next_block_header() 

83 assert block.height is not None 

84 current_height = block.height 

85 sleep(cls.CHECK_BLOCK_TIMEOUT_SECONDS) 

86 

87 # stop mining, if started 

88 if stop_mining: 

89 MiningUtils.stop_mining() 

90 sleep(cls.CHECK_BLOCK_TIMEOUT_SECONDS) 

91 current_height = daemon.get_height() 

92 

93 logger.info(f"[100%] Reached blockchain height: {current_height}") 

94 

95 return current_height 

96 

97 @classmethod 

98 def _generate_blocks_until(cls, daemon: MoneroDaemonRpc, current_height: int, height: int) -> int: 

99 """Generate blocks to the mining address until the blockchain has a height (regtest only). 

100 

101 :param MoneroDaemonRpc daemon: daemon that generates the blocks. 

102 :param int current_height: height of the blockchain. 

103 :param int height: height to reach. 

104 :returns int: blockchain height. 

105 """ 

106 while current_height < height: 

107 p: str = StringUtils.get_percentage(current_height, height) 

108 logger.info(f"[{p}] Generating blocks ({current_height}/{height})") 

109 num_blocks: int = min(cls.GENERATE_BLOCKS_PER_REQUEST, height - current_height) 

110 MiningUtils.generate_blocks(Utils.MINING_ADDRESS, num_blocks, daemon) 

111 current_height = daemon.get_height() 

112 

113 logger.info(f"[100%] Reached blockchain height: {current_height}") 

114 return current_height 

115 

116 @classmethod 

117 def wait_until_blockchain_ready(cls) -> int: 

118 """Wait until blockchain is ready. 

119 

120 :returns int: blockchain height. 

121 """ 

122 # wait for minimum blockchain height 

123 height: int = cls.wait_for_height(Utils.MIN_BLOCK_HEIGHT) 

124 # stop mining 

125 MiningUtils.try_stop_mining() 

126 return height 

127 

128 @classmethod 

129 def wait_for_blocks(cls, num_blocks: int) -> int: 

130 """Start mining and wait for blocks. 

131 

132 :param int num_blocks: number of blocks to wait. 

133 :returns int: blockchain height. 

134 """ 

135 # validate parameters 

136 assert num_blocks >= 0, f"Invalid number of blocks to wait for: {num_blocks}" 

137 height: int = cls.get_height() 

138 # wait for block height 

139 return cls.wait_for_height(height + num_blocks) 

140 

141 @classmethod 

142 def setup_blockchain(cls, network_type: MoneroNetworkType) -> None: 

143 """Setup blockchain for integration tests. 

144 

145 :param MoneroNetworkType network_type: blockchain network type to setup. 

146 """ 

147 # check if blockchain is already setup 

148 if cls.blockchain_is_ready(): 

149 logger.debug("Already setup blockchain") 

150 return 

151 

152 # wait until blockchain reaches desired height 

153 cls.wait_until_blockchain_ready() 

154 # spam some transactions on blockchain 

155 spammer: TxSpammer = TxSpammer(network_type) 

156 spammer.spam() 

157 # wait for spammed txs to confirm 

158 cls.wait_for_blocks(11) 

159 

160 # create an alternative chain on regtest 

161 if Utils.REGTEST: 

162 cls.reorg_blockchain() 

163 

164 @classmethod 

165 def reorg_blockchain(cls, num_blocks: int = 3) -> int: 

166 """Force a blockchain reorganization and ensure it completes successfully (regtest only). 

167 

168 Forks the chain at the current tip: first mines a short chain on top of it, then mines 

169 a longer alternate chain from the same fork point. Since the alternate chain has more 

170 cumulative work, the daemon must reorg onto it, replacing the blocks of the original 

171 chain. 

172 

173 :param int num_blocks: number of blocks to mine on the original chain before forking 

174 (the alternate chain mines one more block than this to guarantee it wins the reorg). 

175 :returns int: blockchain height after the reorg. 

176 """ 

177 assert num_blocks >= 1, f"Invalid number of blocks to reorg: {num_blocks}" 

178 

179 daemon: MoneroDaemonRpc = MiningUtils.get_daemon() 

180 

181 # mining must be stopped so it doesn't race with the forced reorg 

182 stop_mining: bool = MiningUtils.try_stop_mining() 

183 

184 try: 

185 # mark the fork point: the last common block between both chains 

186 fork_header: MoneroBlockHeader = daemon.get_last_block_header() 

187 assert fork_header.hash is not None and fork_header.height is not None 

188 fork_hash: str = fork_header.hash 

189 fork_height: int = fork_header.height 

190 

191 # mine the original, shorter chain on top of the fork point 

192 original: MoneroGenerateBlocksResult = daemon.generate_blocks(Utils.MINING_ADDRESS, num_blocks, fork_hash) 

193 assert original.height == fork_height + num_blocks, \ 

194 f"Failed to build original chain: expected height {fork_height + num_blocks}, got {original.height}" 

195 original_hash: str = daemon.get_block_hash(fork_height + 1) 

196 logger.debug(f"Built original chain of {num_blocks} block(s) on top of height {fork_height}") 

197 

198 # mine a longer alternate chain from the same fork point to force a reorg 

199 alt_num_blocks: int = num_blocks + 1 

200 alt: MoneroGenerateBlocksResult = daemon.generate_blocks(Utils.MINING_ADDRESS, alt_num_blocks, fork_hash) 

201 assert alt.height == fork_height + alt_num_blocks, \ 

202 f"Failed to build alternate chain: expected height {fork_height + alt_num_blocks}, got {alt.height}" 

203 logger.debug(f"Built alternate chain of {alt_num_blocks} block(s) on top of height {fork_height}") 

204 finally: 

205 # restart mining, if it was active before 

206 if stop_mining: 

207 MiningUtils.try_start_mining() 

208 

209 # ensure the reorg was accepted: the active chain must now follow the heavier alternate fork 

210 active_hash: str = daemon.get_block_hash(fork_height + 1) 

211 assert active_hash != original_hash, \ 

212 "Reorg failed: block after the fork point was not replaced by the alternate chain" 

213 assert active_hash in alt.block_hashes, \ 

214 "Reorg failed: active chain block is not part of the generated alternate chain" 

215 

216 original_header: MoneroBlockHeader = daemon.get_block_header_by_hash(original_hash) 

217 assert original_header.orphan_status is True, \ 

218 "Reorg failed: original chain block was not marked as orphaned" 

219 

220 reorg_height: int = daemon.get_height() 

221 logger.debug(f"Blockchain reorg succeeded: active chain now at height {reorg_height}") 

222 

223 return reorg_height