Coverage for tests/utils/block_utils.py: 97%
141 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
1import logging
3from typing import Optional
4from abc import ABC
5from monero import (
6 MoneroAltChain,
7 MoneroBlockHeader, MoneroBlock,
8 MoneroBlockTemplate, MoneroDaemonRpc
9)
11from .gen_utils import GenUtils
12from .context import TestContext, BinaryBlockContext
13from .tx_utils import TxUtils
15logger: logging.Logger = logging.getLogger("BlockUtils")
18class BlockUtils(ABC):
19 """Block test utilities."""
21 @classmethod
22 def test_block_header(cls, header: MoneroBlockHeader, is_full: Optional[bool], debug: bool = True) -> None:
23 """Test a block header.
25 :param MoneroBlockHeader header: header to test.
26 :param bool | None is_full: check full header.
27 :param bool debug: enable logging debug messages (default to `True`).
28 """
29 if debug:
30 logger.debug(f"Testing block header: {header.serialize()}")
31 # test base fields
32 assert header.height is not None
33 assert header.height >= 0
34 assert header.major_version is not None
35 assert header.major_version > 0
36 assert header.minor_version is not None
37 assert header.minor_version >= 0
38 assert header.timestamp is not None
39 if header.height == 0:
40 assert header.timestamp == 0
41 else:
42 assert header.timestamp > 0
43 assert header.prev_hash is not None
44 assert header.nonce is not None
45 if header.nonce == 0:
46 # TODO (monero-project): why is header nonce 0?
47 logger.warning(f"header nonce is 0 at height {header.height}")
48 else:
49 assert header.nonce > 0
50 # never seen defined
51 assert header.pow_hash is None
52 # test full header details
53 cls.test_full_header(header, is_full)
55 @classmethod
56 def test_full_header(cls, header: MoneroBlockHeader, is_full: Optional[bool]) -> None:
57 """Test full header details.
59 :param MoneroBlockHeader header: header to test full details.
60 :param bool | None is_full: indicates if `header`'s full details should be defined.
61 """
62 logger.debug(f"Testing full header: {header.serialize()}")
64 # num_txs always defined
65 assert header.num_txs is not None
66 assert header.num_txs >= 0
67 assert header.hash is not None
68 assert len(header.hash) == 64
70 if is_full:
71 # check full block
72 assert header.size is not None
73 assert header.depth is not None
74 assert header.difficulty_low is not None
75 assert header.difficulty_high is not None
76 assert header.cumulative_difficulty_low is not None
77 assert header.cumulative_difficulty_high is not None
78 assert header.miner_tx_hash is not None
79 assert header.weight is not None
80 assert header.size > 0
81 assert header.depth >= 0
82 assert header.difficulty_low > 0
83 assert header.difficulty_high >= 0
84 assert header.cumulative_difficulty_low > 0
85 assert header.cumulative_difficulty_high >= 0
86 assert 64 == len(header.hash)
87 assert 64 == len(header.miner_tx_hash)
88 assert header.orphan_status is not None
89 assert header.reward is not None
90 assert header.weight is not None
91 assert header.weight > 0
92 else:
93 assert header.size is None
94 assert header.depth is None
95 assert header.difficulty_low is None
96 assert header.difficulty_high is None
97 assert header.cumulative_difficulty_low is None
98 assert header.cumulative_difficulty_high is None
99 assert header.miner_tx_hash is None
100 assert header.orphan_status is None
101 assert header.reward is None
102 assert header.weight is None
104 @classmethod
105 def test_block(cls, block: MoneroBlock, ctx: TestContext) -> None:
106 """Test a block
108 :param MoneroBlock | None block: block to test.
109 :param TestContext ctx: test context.
110 """
111 logger.debug(f"Testing block: {block.serialize()}. Context: {ctx.serialize()}")
113 # test required fields
114 assert block.miner_tx is not None, "Expected block miner tx"
115 # TODO: miner tx doesn't have as much stuff, can't call TxUtils.test_tx?
116 TxUtils.test_miner_tx(block.miner_tx)
117 cls.test_block_header(block, ctx.header_is_full, False)
119 if ctx.has_hex:
120 assert block.hex is not None
121 assert len(block.hex) > 1
122 else:
123 assert block.hex is None
125 if ctx.has_txs:
126 assert ctx.tx_context is not None
127 for tx in block.txs:
128 assert block == tx.block
129 TxUtils.test_tx(tx, ctx.tx_context)
131 # test duplicates
132 num_block_txs: int = len(block.txs)
133 num_tx_hashes: int = len(block.tx_hashes)
135 if block.num_txs is not None:
136 assert block.num_txs == num_block_txs, f"Expected {block.num_txs}, got {num_block_txs}"
137 assert block.num_txs == num_tx_hashes, f"Expected {block.num_txs}, got {num_tx_hashes}"
138 assert num_tx_hashes == len(set(block.tx_hashes)), "Duplicate tx hashes found in block"
139 else:
140 assert num_block_txs == 0
141 assert num_tx_hashes == 0
143 else:
144 assert ctx.tx_context is None
145 assert len(block.txs) == 0, "No txs expected"
147 @classmethod
148 def test_get_blocks_range(
149 cls,
150 daemon: MoneroDaemonRpc,
151 start_height: Optional[int],
152 end_height: Optional[int],
153 chain_height: int,
154 chunked: bool,
155 block_ctx: BinaryBlockContext
156 ) -> None:
157 """Test get blocks by range.
159 :param MoneroDaemonRpc daemon: daemon to test.
160 :param int | None start_height: range start height.
161 :param int | None end_height: range end height.
162 :param int chain_height: blockchain height.
163 :param bool chunked: get blocks range chunked.
164 :param BinaryBlockContext block_ctx: binary block test context.
165 """
166 # fetch blocks by range
167 real_start_height: int = 0 if start_height is None else start_height
168 real_end_height: int = chain_height - 1 if end_height is None else end_height
169 blocks: list[MoneroBlock]
171 if chunked:
172 blocks = daemon.get_blocks_by_range_chunked(start_height, end_height)
173 else:
174 blocks = daemon.get_blocks_by_range(start_height, end_height)
176 num_blocks: int = len(blocks)
177 expected_num_blocks: int = real_end_height - real_start_height + 1
178 assert expected_num_blocks == num_blocks, f"Expected {expected_num_blocks} block(s), got {num_blocks}"
180 # test each block
181 for i, block in enumerate(blocks):
182 assert real_start_height + i == block.height
183 cls.test_block(block, block_ctx)
185 @classmethod
186 def is_tx_in_block(cls, tx_hash: str | None, block: MoneroBlock) -> bool:
187 """Check if transaction is included in block.
189 :param str | None tx_hash: tx's hash to check if included in block.
190 :param MoneroBlock block: block to check if `tx` is included in.
191 :returns bool: `True` if `tx_hash` is included in `block`, `False` otherwise.
192 """
193 # validate tx hash
194 assert tx_hash is not None
195 assert len(tx_hash) > 0
197 # search tx hash in block txs
198 for block_tx in block.txs:
199 if block_tx.hash == tx_hash:
200 return True
202 return False
204 @classmethod
205 def test_block_template(cls, template: MoneroBlockTemplate) -> None:
206 """Test a mining block template.
208 :param MoneroBlockTemplate template: mining block template to test.
209 """
210 logger.debug(f"Testing block template: {template.serialize()}")
211 assert template.block_template_blob is not None
212 assert template.block_hashing_blob is not None
213 assert template.difficulty_low is not None
214 assert template.difficulty_high is not None
215 assert template.expected_reward is not None
216 assert template.height is not None
217 assert template.prev_hash is not None
218 assert template.reserved_offset is not None
219 assert template.seed_height is not None
220 assert template.seed_height >= 0
221 assert template.seed_hash is not None
222 assert len(template.seed_hash) > 0
223 # next seed hash can be null or initialized TODO: test circumstances for each
225 @classmethod
226 def test_alt_chain(cls, alt_chain: MoneroAltChain) -> None:
227 """Test daemon alternative chain info.
229 :param MoneroAltChain alt_chain: alternative chain info to test.
230 """
231 logger.debug(f"Testing alternative chain: {alt_chain.serialize()}")
232 assert len(alt_chain.block_hashes) > 0
233 GenUtils.test_unsigned_big_integer(alt_chain.difficulty_low, True)
234 GenUtils.test_unsigned_big_integer(alt_chain.difficulty_high)
235 assert alt_chain.height is not None
236 assert alt_chain.length is not None
237 assert alt_chain.main_chain_parent_block_hash is not None
238 assert alt_chain.height > 0
239 assert alt_chain.length > 0
240 assert 64 == len(alt_chain.main_chain_parent_block_hash)