-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathtest_commitments.py
More file actions
402 lines (339 loc) · 16.7 KB
/
Copy pathtest_commitments.py
File metadata and controls
402 lines (339 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
"""Tests for allways.commitments — commitment string parsing + query_map read."""
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from allways.commitments import (
parse_commitment_data,
read_miner_commitments,
read_unexecutable_commitments,
)
class TestParseCommitmentData:
def test_valid_two_rates(self):
raw = 'v1:btc:bc1qaddr:tao:5Caddr:340:350'
pair = parse_commitment_data(raw, uid=1, hotkey='hk1')
assert pair is not None
assert pair.uid == 1
assert pair.hotkey == 'hk1'
assert pair.from_chain == 'btc'
assert pair.from_address == 'bc1qaddr'
assert pair.to_chain == 'tao'
assert pair.to_address == '5Caddr'
assert pair.rate == 340.0
assert pair.rate_str == '340'
assert pair.counter_rate == 350.0
assert pair.counter_rate_str == '350'
def test_valid_same_rate_both_directions(self):
raw = 'v1:btc:bc1qaddr:tao:5Caddr:345:345'
pair = parse_commitment_data(raw)
assert pair is not None
assert pair.rate == 345.0
assert pair.counter_rate == 345.0
def test_normalization_swaps_rates(self):
"""When posted as tao->btc, normalization flips to btc->tao and swaps rates."""
raw = 'v1:tao:5Caddr:btc:bc1qaddr:340:350'
pair = parse_commitment_data(raw)
assert pair is not None
assert pair.from_chain == 'btc'
assert pair.to_chain == 'tao'
assert pair.from_address == 'bc1qaddr'
assert pair.to_address == '5Caddr'
# Original forward rate (340) was for tao->btc, now becomes reverse
assert pair.rate == 350.0
assert pair.rate_str == '350'
assert pair.counter_rate == 340.0
assert pair.counter_rate_str == '340'
def test_fractional_rates(self):
raw = 'v1:btc:bc1qaddr:tao:5Caddr:345.12:350.45'
pair = parse_commitment_data(raw)
assert pair is not None
assert pair.rate == 345.12
assert pair.rate_str == '345.12'
assert pair.counter_rate == 350.45
assert pair.counter_rate_str == '350.45'
def test_get_rate_for_direction(self):
raw = 'v1:btc:bc1qaddr:tao:5Caddr:340:350'
pair = parse_commitment_data(raw)
# Forward (btc -> tao)
rate, rate_str = pair.get_rate_for_direction('btc')
assert rate == 340.0
assert rate_str == '340'
# Reverse (tao -> btc)
rate, rate_str = pair.get_rate_for_direction('tao')
assert rate == 350.0
assert rate_str == '350'
def test_get_rate_for_direction_after_normalization(self):
"""Full pipeline: tao->btc commitment normalizes, then direction lookup works."""
raw = 'v1:tao:5Caddr:btc:bc1qaddr:340:350'
pair = parse_commitment_data(raw)
# After normalization: source=btc, dest=tao
# Original 340 was tao->btc (now reverse), 350 was btc->tao (now forward)
fwd_rate, fwd_str = pair.get_rate_for_direction('btc')
rev_rate, rev_str = pair.get_rate_for_direction('tao')
assert fwd_rate == 350.0
assert fwd_str == '350'
assert rev_rate == 340.0
assert rev_str == '340'
def test_wrong_part_count_too_few(self):
assert parse_commitment_data('v1:btc:addr:tao:addr:345') is None
def test_wrong_part_count_too_many(self):
assert parse_commitment_data('v1:btc:addr:tao:addr:340:350:extra') is None
def test_wrong_version(self):
assert parse_commitment_data('v2:btc:addr:tao:addr:340:350') is None
def test_no_version_prefix(self):
assert parse_commitment_data('3:btc:addr:tao:addr:340:350') is None
def test_unsupported_source_chain(self):
assert parse_commitment_data('v1:eth:addr:tao:addr:340:350') is None
def test_unsupported_dest_chain(self):
assert parse_commitment_data('v1:btc:addr:eth:addr:340:350') is None
def test_invalid_rate_not_a_number(self):
assert parse_commitment_data('v1:btc:addr:tao:addr:abc:350') is None
def test_invalid_reverse_rate_not_a_number(self):
assert parse_commitment_data('v1:btc:addr:tao:addr:340:abc') is None
def test_empty_string(self):
assert parse_commitment_data('') is None
def test_rate_zero(self):
pair = parse_commitment_data('v1:btc:addr:tao:addr:0:0')
assert pair is not None
assert pair.rate == 0.0
assert pair.counter_rate == 0.0
def test_high_precision_rate_normalized_to_sig_figs(self):
raw = 'v1:btc:bc1qaddr:tao:5Caddr:0.0001234567:340.987654'
pair = parse_commitment_data(raw)
assert pair is not None
assert pair.rate_str == '0.00012346'
assert pair.counter_rate_str == '340.99'
def test_normalized_rate_str_round_trips_to_float(self):
"""Scoring uses .rate (float), consensus hash uses .rate_str — they must agree."""
raw = 'v1:btc:bc1qaddr:tao:5Caddr:0.0001234567:340.987654'
pair = parse_commitment_data(raw)
assert float(pair.rate_str) == pair.rate
assert float(pair.counter_rate_str) == pair.counter_rate
def test_already_canonical_rate_is_unchanged(self):
raw = 'v1:btc:bc1qaddr:tao:5Caddr:345:0.5'
pair = parse_commitment_data(raw)
assert pair is not None
assert pair.rate_str == '345'
assert pair.counter_rate_str == '0.5'
def test_normalization_strips_trailing_zeros(self):
raw = 'v1:btc:bc1qaddr:tao:5Caddr:345.000000:0.500000'
pair = parse_commitment_data(raw)
assert pair.rate_str == '345'
assert pair.counter_rate_str == '0.5'
def test_negative_rate_rejected(self):
assert parse_commitment_data('v1:btc:addr:tao:addr:-1:340') is None
def test_negative_counter_rate_rejected(self):
assert parse_commitment_data('v1:btc:addr:tao:addr:340:-1') is None
def test_nan_rate_rejected(self):
assert parse_commitment_data('v1:btc:addr:tao:addr:nan:340') is None
def test_inf_rate_rejected(self):
assert parse_commitment_data('v1:btc:addr:tao:addr:inf:340') is None
assert parse_commitment_data('v1:btc:addr:tao:addr:340:-inf') is None
def test_disabled_direction_produces_zero_dest_amount(self):
"""Full guard chain: disabled direction → rate=0 → to_amount=0 → contract rejects."""
from allways.utils.rate import calculate_to_amount
raw = 'v1:btc:bc1qaddr:tao:5Caddr:345:0'
pair = parse_commitment_data(raw)
# Validator calls get_rate_for_direction for the disabled direction
rate, rate_str = pair.get_rate_for_direction('tao')
assert rate == 0.0
assert rate <= 0 # validator guard: if selected_rate <= 0: reject
# Even if the guard were bypassed, calculate_to_amount returns 0
to_amount = calculate_to_amount(1_000_000_000, rate_str, is_reverse=True, to_decimals=9, from_decimals=8)
assert to_amount == 0 # contract would reject with InvalidAmount
def test_single_direction_forward_only(self):
"""Miner supports only BTC→TAO (counter_rate=0 means TAO→BTC not offered)."""
raw = 'v1:btc:bc1qaddr:tao:5Caddr:345:0'
pair = parse_commitment_data(raw)
assert pair is not None
assert pair.rate == 345.0
assert pair.counter_rate == 0.0
# Forward direction returns valid rate
rate, rate_str = pair.get_rate_for_direction('btc')
assert rate == 345.0
# Counter direction returns 0
rate, rate_str = pair.get_rate_for_direction('tao')
assert rate == 0.0
def test_single_direction_counter_only(self):
"""Miner posts tao→btc only. After normalization, rate=0, counter_rate has the value."""
raw = 'v1:tao:5Caddr:btc:bc1qaddr:345:0'
pair = parse_commitment_data(raw)
assert pair is not None
# Normalization flips: btc→tao becomes source→dest
# Original rate 345 was tao→btc (now counter), original 0 was btc→tao (now forward)
assert pair.rate == 0.0
assert pair.counter_rate == 345.0
# BTC→TAO returns 0 (not supported)
rate, _ = pair.get_rate_for_direction('btc')
assert rate == 0.0
# TAO→BTC returns 345
rate, _ = pair.get_rate_for_direction('tao')
assert rate == 345.0
def test_default_uid_and_hotkey(self):
pair = parse_commitment_data('v1:btc:addr:tao:addr:1.0:2.0')
assert pair.uid == 0
assert pair.hotkey == ''
def test_same_chain(self):
assert parse_commitment_data('v1:btc:addr:btc:addr:340:350') is None
class TestReadMinerCommitmentsQueryMap:
"""Coverage for the query_map-batched read.
``read_miner_commitments`` used to do N separate ``substrate.query`` calls
in a for-loop. It now uses ``substrate.query_map`` to pull every
``(hotkey, commitment)`` pair under ``Commitments.CommitmentOf(netuid)``
in a single RPC. These tests mock the substrate interface to exercise
the new path — the hotkey→uid filter, the decode fallthrough, and the
"commitment exists but miner dereg'd" dropout.
"""
def make_subtensor(self, hotkeys: list[str], rows: list[tuple[str, str]]) -> MagicMock:
"""Build a mock subtensor whose metagraph and query_map match the args.
``rows`` is a list of (hotkey, raw_commitment_text) pairs as they'd
come back from Commitments.CommitmentOf. Each raw text is wrapped in
a fake metadata object that the real ``decode_commitment_field``
can parse.
"""
subtensor = MagicMock()
metagraph = SimpleNamespace(
hotkeys=list(hotkeys),
n=SimpleNamespace(item=lambda: len(hotkeys)),
)
subtensor.metagraph.return_value = metagraph
def fake_query_map(module, storage_function, params):
for hotkey, raw in rows:
key = SimpleNamespace(value=hotkey)
# Fake the ink!-shaped metadata that decode_commitment_field walks.
metadata = SimpleNamespace(value={'info': {'fields': [{'Raw0': '0x' + raw.encode().hex()}]}})
yield key, metadata
subtensor.substrate.query_map.side_effect = fake_query_map
return subtensor
def test_returns_parsed_pairs_for_every_registered_miner(self):
subtensor = self.make_subtensor(
hotkeys=['hk_a', 'hk_b'],
rows=[
('hk_a', 'v1:btc:bc1qaddr_a:tao:5C_a:340:350'),
('hk_b', 'v1:btc:bc1qaddr_b:tao:5C_b:345:355'),
],
)
pairs = read_miner_commitments(subtensor, netuid=7)
assert len(pairs) == 2
by_hotkey = {p.hotkey: p for p in pairs}
assert by_hotkey['hk_a'].uid == 0
assert by_hotkey['hk_b'].uid == 1
assert by_hotkey['hk_a'].rate == 340.0
assert by_hotkey['hk_b'].rate == 345.0
def test_drops_dereg_hotkey_still_in_storage(self):
"""A miner can deregister before their commitment is cleared from
Commitments.CommitmentOf. Those rows must be skipped."""
subtensor = self.make_subtensor(
hotkeys=['hk_live'], # only hk_live is in the metagraph
rows=[
('hk_live', 'v1:btc:bc1qlive:tao:5Clive:340:350'),
('hk_ghost', 'v1:btc:bc1qghost:tao:5Cghost:999:999'),
],
)
pairs = read_miner_commitments(subtensor, netuid=7)
assert [p.hotkey for p in pairs] == ['hk_live']
def test_single_query_map_call(self):
"""Regression guard: we must not fall back into an N-RPC loop."""
subtensor = self.make_subtensor(
hotkeys=['hk_a', 'hk_b', 'hk_c'],
rows=[('hk_a', 'v1:btc:a:tao:a:1:1')],
)
read_miner_commitments(subtensor, netuid=7)
assert subtensor.substrate.query_map.call_count == 1
# And no per-hotkey query() calls leaked back in.
assert subtensor.substrate.query.call_count == 0
def test_transient_error_returns_empty_list(self):
"""ConnectionError / TimeoutError during query_map shouldn't raise."""
subtensor = MagicMock()
subtensor.metagraph.return_value = SimpleNamespace(hotkeys=['hk_a'], n=SimpleNamespace(item=lambda: 1))
subtensor.substrate.query_map.side_effect = ConnectionError('websocket dead')
with patch('allways.commitments.bt.logging.warning'):
pairs = read_miner_commitments(subtensor, netuid=7)
assert pairs == []
# Sentinel rates chosen so is_executable_rate returns False under any normal
# (min, max) BTC/TAO bounds: 1e9 TAO/BTC is so high even 1 sat maps above max,
# and 1e-9 TAO/BTC inverted is the symmetric low-side rejection.
BOUNDS_REASONABLE = {'min_swap_rao': 500_000_000, 'max_swap_rao': 5_000_000_000} # 0.5–5 TAO
class TestParseCommitmentDataExecutability:
def test_drops_pair_with_sentinel_forward_rate_when_bounds_set(self):
raw = 'v1:btc:bc1qaddr:tao:5Caddr:1e9:350'
assert parse_commitment_data(raw, **BOUNDS_REASONABLE) is None
def test_drops_pair_with_sentinel_counter_rate_when_bounds_set(self):
raw = 'v1:btc:bc1qaddr:tao:5Caddr:340:1e-9'
assert parse_commitment_data(raw, **BOUNDS_REASONABLE) is None
def test_admits_pair_with_one_sentinel_one_zero(self):
"""Zero stays opt-out semantics — a pair with one direction at 0 and
the other direction executable must not be dropped just because 0
looks sentinel-shaped."""
raw = 'v1:btc:bc1qaddr:tao:5Caddr:340:0'
pair = parse_commitment_data(raw, **BOUNDS_REASONABLE)
assert pair is not None
assert pair.rate == 340.0
assert pair.counter_rate == 0.0
def test_permissive_when_bounds_zero(self):
"""Default-permissive: with bounds at 0/0, even absurd rates parse."""
raw = 'v1:btc:bc1qaddr:tao:5Caddr:1e9:1e-9'
pair = parse_commitment_data(raw)
assert pair is not None
def test_bounds_at_max_zero_uses_min_only(self):
"""max_swap_rao=0 is the contract's 'unset' sentinel; min-only bounds
still admit a normal rate (no upper cap to enforce)."""
raw = 'v1:btc:bc1qaddr:tao:5Caddr:340:350'
pair = parse_commitment_data(raw, min_swap_rao=500_000_000, max_swap_rao=0)
assert pair is not None
class TestReadMinerCommitmentsExecutability:
def make_subtensor(self, hotkeys, rows):
subtensor = MagicMock()
metagraph = SimpleNamespace(
hotkeys=list(hotkeys),
n=SimpleNamespace(item=lambda: len(hotkeys)),
)
subtensor.metagraph.return_value = metagraph
def fake_query_map(module, storage_function, params):
for hotkey, raw in rows:
key = SimpleNamespace(value=hotkey)
metadata = SimpleNamespace(value={'info': {'fields': [{'Raw0': '0x' + raw.encode().hex()}]}})
yield key, metadata
subtensor.substrate.query_map.side_effect = fake_query_map
return subtensor
def test_drops_sentinel_pair_when_bounds_supplied(self):
subtensor = self.make_subtensor(
hotkeys=['hk_a', 'hk_b'],
rows=[
('hk_a', 'v1:btc:a:tao:a:340:350'),
('hk_b', 'v1:btc:b:tao:b:1e9:350'),
],
)
pairs = read_miner_commitments(subtensor, netuid=7, **BOUNDS_REASONABLE)
assert [p.hotkey for p in pairs] == ['hk_a']
def test_permissive_when_no_bounds_admits_sentinel(self):
subtensor = self.make_subtensor(
hotkeys=['hk_a'],
rows=[('hk_a', 'v1:btc:a:tao:a:1e9:350')],
)
pairs = read_miner_commitments(subtensor, netuid=7)
assert [p.hotkey for p in pairs] == ['hk_a']
class TestReadUnexecutableCommitments:
def make_subtensor(self, hotkeys, rows):
subtensor = MagicMock()
metagraph = SimpleNamespace(
hotkeys=list(hotkeys),
n=SimpleNamespace(item=lambda: len(hotkeys)),
)
subtensor.metagraph.return_value = metagraph
def fake_query_map(module, storage_function, params):
for hotkey, raw in rows:
key = SimpleNamespace(value=hotkey)
metadata = SimpleNamespace(value={'info': {'fields': [{'Raw0': '0x' + raw.encode().hex()}]}})
yield key, metadata
subtensor.substrate.query_map.side_effect = fake_query_map
return subtensor
def test_returns_only_bounded_drops_not_malformed(self):
subtensor = self.make_subtensor(
hotkeys=['hk_good', 'hk_sentinel', 'hk_garbage'],
rows=[
('hk_good', 'v1:btc:a:tao:a:340:350'),
('hk_sentinel', 'v1:btc:b:tao:b:1e9:350'),
('hk_garbage', 'x'),
],
)
out = read_unexecutable_commitments(subtensor, netuid=7, **BOUNDS_REASONABLE)
assert out == {'hk_sentinel'}