fabric-resolver 0.1.2

Client library for the Spaces protocol certificate relay network.
Documentation
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
from __future__ import annotations

import json
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from typing import Optional
from urllib.request import Request, urlopen
from urllib.parse import urlencode

import libveritas as lv

from .seeds import DEFAULT_SEEDS
from .hints import (
    CompareHints,
    EpochResult,
    HandleHint,
    HintsResponse,
    SpaceHint,
)
from .pool import RelayPool


BADGE_ORANGE = "orange"
BADGE_UNVERIFIED = "unverified"
BADGE_NONE = "none"


class FabricError(Exception):
    def __init__(self, code: str, message: str, status: int = 0):
        self.code = code
        self.message = message
        self.status = status
        super().__init__(f"{code}: {message}" if status == 0
                         else f"{code} ({status}): {message}")


@dataclass
class Resolved:
    zone: lv.Zone
    roots: list[str]  # hex-encoded root IDs


@dataclass
class ResolvedBatch:
    zones: list[lv.Zone]
    roots: list[str]  # hex-encoded root IDs


@dataclass
class _EpochHint:
    root: str
    height: int


@dataclass
class _Query:
    space: str
    handles: list[str]
    epoch_hint: Optional[_EpochHint] = None

    def to_dict(self) -> dict:
        d: dict = {"space": self.space, "handles": self.handles}
        if self.epoch_hint is not None:
            d["epoch_hint"] = {
                "root": self.epoch_hint.root,
                "height": self.epoch_hint.height,
            }
        return d


@dataclass
class _QueryRequest:
    queries: list[_Query]

    def to_json(self) -> bytes:
        return json.dumps(
            {"queries": [q.to_dict() for q in self.queries]}
        ).encode()


class _TrustKind:
    TRUSTED = "trusted"
    SEMI_TRUSTED = "semi_trusted"
    OBSERVED = "observed"


class _AnchorPool:
    def __init__(self):
        self.trusted: list = []      # raw entries list (from JSON)
        self.semi_trusted: list = [] # raw entries list (from JSON)
        self.observed: list = []     # raw entries list (from JSON)

    def merged(self) -> list:
        """Combine all entries, dedup by block height."""
        all_entries = []
        all_entries.extend(self.trusted)
        all_entries.extend(self.semi_trusted)
        all_entries.extend(self.observed)
        seen = set()
        deduped = []
        for e in all_entries:
            h = e.get("block", {}).get("height", 0) if isinstance(e, dict) else 0
            if h not in seen:
                seen.add(h)
                deduped.append(e)
        return deduped


@dataclass
class ScanParams:
    """Parsed parameters from a veritas://scan?... URI."""
    id: str  # hex-encoded trust ID

    @staticmethod
    def parse(uri: str) -> "ScanParams":
        uri = uri.strip()
        prefix = "veritas://scan?"
        if not uri.startswith(prefix):
            raise FabricError("decode", "expected veritas://scan?... URI")
        query = uri[len(prefix):]
        params = {}
        for pair in query.split("&"):
            if "=" in pair:
                k, v = pair.split("=", 1)
                params[k] = v
        trust_id = params.get("id")
        if not trust_id:
            raise FabricError("decode", "missing id parameter")
        return ScanParams(id=trust_id)


class Fabric:
    def __init__(
        self,
        seeds: Optional[list[str]] = None,
        *,
        dev_mode: bool = False,
        prefer_latest: bool = True,
    ):
        self._seeds = seeds or list(DEFAULT_SEEDS)
        self._dev_mode = dev_mode
        self._prefer_latest = prefer_latest
        self._pool = RelayPool()
        self._veritas: Optional[lv.Veritas] = None
        self._trusted: Optional[lv.TrustSet] = None
        self._observed: Optional[lv.TrustSet] = None
        self._semi_trusted: Optional[lv.TrustSet] = None
        self._anchor_pool = _AnchorPool()
        self._zone_cache: dict[str, lv.Zone] = {}
        self._lock = threading.Lock()

    @property
    def relays(self) -> list[str]:
        return self._pool.urls()

    @property
    def veritas(self) -> Optional[lv.Veritas]:
        """The internal Veritas instance for offline verification. None until bootstrap() is called."""
        with self._lock:
            return self._veritas

    # -- Public API --

    def trust(self, trust_id: str) -> None:
        """Pin a specific trust ID (hex-encoded 32-byte hash).
        Bootstraps peers if needed, then fetches the anchor set for this ID."""
        if self._pool.is_empty():
            self._bootstrap_peers()
        self._update_anchors(trust_id, _TrustKind.TRUSTED)

    def trust_from_qr(self, payload: str) -> None:
        """Parse a veritas://scan?id=... QR payload and pin as trusted."""
        params = ScanParams.parse(payload)
        self.trust(params.id)

    def semi_trust_from_qr(self, payload: str) -> None:
        """Parse a veritas://scan?id=... QR payload and pin as semi-trusted."""
        params = ScanParams.parse(payload)
        self.semi_trust(params.id)

    def trusted(self) -> Optional[str]:
        """Return the hex-encoded trusted trust ID, or None if not set."""
        ts = self._trusted
        return bytes(ts.id).hex() if ts else None

    def observed(self) -> Optional[str]:
        """Return the hex-encoded observed trust ID, or None if not set."""
        ts = self._observed
        return bytes(ts.id).hex() if ts else None

    def semi_trust(self, trust_id: str) -> None:
        """Set a semi-trusted anchor from an external source (e.g. public explorer)."""
        if self._pool.is_empty():
            self._bootstrap_peers()
        self._update_anchors(trust_id, _TrustKind.SEMI_TRUSTED)

    def semi_trusted(self) -> Optional[str]:
        """Return the hex-encoded semi-trusted trust ID, or None if not set."""
        ts = self._semi_trusted
        return bytes(ts.id).hex() if ts else None

    def clear_trusted(self) -> None:
        """Clear the pinned trusted state."""
        self._trusted = None

    def badge(self, resolved: Resolved) -> str:
        """Return the verification badge for a Resolved handle."""
        return self.badge_for(resolved.zone.sovereignty, resolved.roots)

    def badge_for(self, sovereignty: str, roots: list[str]) -> str:
        """Return the verification badge given sovereignty and root IDs."""
        is_trusted = self._are_roots_trusted(roots)
        is_observed = is_trusted or self._are_roots_observed(roots)
        is_semi_trusted = is_trusted or self._are_roots_semi_trusted(roots)
        if is_trusted and sovereignty == "sovereign":
            return BADGE_ORANGE
        if is_observed and not is_trusted and not is_semi_trusted:
            return BADGE_UNVERIFIED
        return BADGE_NONE

    def resolve(self, handle: str) -> Resolved:
        batch = self.resolve_all([handle])
        zone = next((z for z in batch.zones if z.handle == handle), None)
        if zone is None:
            raise FabricError("decode", f"{handle} not found")
        return Resolved(zone=zone, roots=batch.roots)

    def resolve_by_id(self, num_id: str) -> Resolved:
        """Resolve a numeric ID to a verified handle."""
        self.bootstrap()
        urls = self._pool.shuffled_urls(4)
        last_err: Exception = FabricError("no_peers", "reverse resolution failed")

        for u in urls:
            try:
                req = Request(u + "/reverse?ids=" + num_id)
                with urlopen(req, timeout=10) as resp:
                    if resp.status >= 300:
                        self._pool.mark_failed(u)
                        continue
                    entries = json.loads(resp.read())
            except Exception as e:
                self._pool.mark_failed(u)
                last_err = FabricError("http", str(e))
                continue

            entry = next((e for e in entries if e.get("id") == num_id), None)
            if entry is None:
                continue

            try:
                resolved = self.resolve(entry["name"])
            except Exception as e:
                last_err = e
                continue

            if getattr(resolved.zone, "num_id", None) != num_id:
                last_err = FabricError("verify", f"num_id mismatch: expected {num_id}")
                continue

            self._pool.mark_alive(u)
            return resolved

        raise last_err

    def search_addr(self, name: str, addr: str) -> ResolvedBatch:
        """Search for handles by address record, verify via forward resolution."""
        self.bootstrap()
        urls = self._pool.shuffled_urls(4)
        last_err: Exception = FabricError("no_peers", "address search failed")

        for u in urls:
            try:
                req = Request(f"{u}/addrs?name={name}&addr={addr}")
                with urlopen(req, timeout=10) as resp:
                    if resp.status >= 300:
                        self._pool.mark_failed(u)
                        continue
                    result = json.loads(resp.read())
            except Exception as e:
                self._pool.mark_failed(u)
                last_err = FabricError("http", str(e))
                continue

            handles = result.get("handles", [])
            if not handles:
                continue

            rev_names = [h["rev"] for h in handles]
            try:
                batch = self.resolve_all(rev_names)
            except Exception as e:
                last_err = e
                continue

            # Filter to zones that actually contain the matching addr record
            matching = []
            for z in batch.zones:
                if z.records is not None:
                    try:
                        rs = lv.RecordSet(z.records)
                        for r in rs.unpack():
                            if hasattr(r, 'key') and hasattr(r, 'value'):
                                if r.key == name and len(r.value) > 0 and r.value[0] == addr:
                                    matching.append(z)
                                    break
                    except Exception:
                        continue

            if not matching:
                continue

            self._pool.mark_alive(u)
            return ResolvedBatch(zones=matching, roots=batch.roots)

        raise last_err

    def resolve_all(self, handles: list[str]) -> ResolvedBatch:
        lookup = lv.Lookup(handles)
        all_zones: list[lv.Zone] = []
        roots: list[str] = []

        prev_batch: list[str] = []
        batch = lookup.start()
        while batch:
            if batch == prev_batch:
                break
            verified = self._resolve_flat(batch)
            zones = verified.zones()
            prev_batch = batch
            batch = lookup.advance(zones)
            all_zones.extend(zones)
            roots.append(bytes(verified.root_id()).hex())

        expanded = lookup.expand_zones(all_zones)
        return ResolvedBatch(zones=expanded, roots=roots)

    def export(self, handle: str) -> bytes:
        """Export a certificate chain for a handle in .spacecert format."""
        lookup = lv.Lookup([handle])
        all_cert_bytes: list[bytes] = []

        prev_batch: list[str] = []
        batch = lookup.start()
        while batch:
            if batch == prev_batch:
                break
            verified = self._resolve_flat(batch)
            all_cert_bytes.extend(verified.certificates())
            zones = verified.zones()
            prev_batch = batch
            batch = lookup.advance(zones)

        return lv.create_certificate_chain(handle, all_cert_bytes)

    def bootstrap(self):
        if self._pool.is_empty():
            self._bootstrap_peers()
        if self._veritas is None or self._veritas.newest_anchor() == 0:
            self._update_anchors()

    def sign(self, cert: bytes, records: bytes, secret_key: bytes, primary: bool = True) -> bytes:
        """Build and sign a message. Returns message bytes."""
        self.bootstrap()
        builder = lv.MessageBuilder()
        builder.add_handle(cert, records)
        proof_req_json = builder.chain_proof_request()
        proof_bytes = self.prove(proof_req_json.encode())
        result = builder.build(proof_bytes)

        for u in result.unsigned:
            if primary:
                u.set_flags(u.flags() | 0x01)
            sig = lv.sign_schnorr(u.signing_id(), secret_key)
            signed = u.pack_sig(sig)
            result.message.set_records(u.canonical(), signed)

        return result.message.to_bytes()

    def publish(self, cert: bytes, records: bytes, secret_key: bytes, primary: bool = True) -> None:
        """Build, sign, and broadcast a message."""
        msg = self.sign(cert, records, secret_key, primary)
        self.broadcast(msg)

    def prove(self, request: bytes) -> bytes:
        """Request a chain proof from a relay."""
        self.bootstrap()
        urls = self._pool.shuffled_urls(4)
        last_err: Exception = FabricError("no_peers", "no peers available")

        for u in urls:
            try:
                resp = _post_json(u + "/chain-proof", request)
            except Exception as e:
                self._pool.mark_failed(u)
                last_err = e
                continue
            self._pool.mark_alive(u)
            return resp

        raise last_err

    def broadcast(self, msg_bytes: bytes) -> None:
        """Send a message to up to 4 random relays for gossip propagation."""
        self.bootstrap()
        urls = self._pool.shuffled_urls(4)
        if not urls:
            raise FabricError("no_peers", "no peers available")

        any_ok = False
        last_err: Optional[Exception] = None
        for u in urls:
            try:
                _post_binary(u + "/message", msg_bytes)
                any_ok = True
            except Exception as e:
                last_err = e
        if not any_ok:
            raise last_err or FabricError("no_peers", "no peers available")

    def peers(self) -> list[dict]:
        urls = self._pool.shuffled_urls(1)
        if not urls:
            raise FabricError("no_peers", "no peers available")
        return _fetch_peers(urls[0])

    def refresh_peers(self):
        current = self._pool.urls()
        new_urls = []
        for u in current:
            try:
                for p in _fetch_peers(u):
                    new_urls.append(p["url"])
            except Exception:
                pass
        self._pool.refresh(new_urls)
        if self._pool.is_empty():
            raise FabricError("no_peers", "no peers available")

    # -- Internal --

    def _are_roots_trusted(self, roots: list[str]) -> bool:
        ts = self._trusted
        if ts is None:
            return False
        return all(
            any(bytes(r) == bytes.fromhex(root) for r in ts.roots)
            for root in roots
        )

    def _are_roots_observed(self, roots: list[str]) -> bool:
        ts = self._observed
        if ts is None:
            return False
        return all(
            any(bytes(r) == bytes.fromhex(root) for r in ts.roots)
            for root in roots
        )

    def _are_roots_semi_trusted(self, roots: list[str]) -> bool:
        ts = self._semi_trusted
        if ts is None:
            return False
        return all(
            any(bytes(r) == bytes.fromhex(root) for r in ts.roots)
            for root in roots
        )

    def _bootstrap_peers(self):
        urls: set[str] = set()
        for seed in self._seeds:
            urls.add(seed)
            try:
                for p in _fetch_peers(seed):
                    urls.add(p["url"])
            except Exception:
                pass
        if not urls:
            raise FabricError("no_peers", "no peers available")
        self._pool.refresh(list(urls))

    def _update_anchors(self, trust_id: Optional[str] = None, kind: str = ""):
        if not kind:
            kind = _TrustKind.TRUSTED if (trust_id is not None and trust_id != "") else _TrustKind.OBSERVED

        if kind == _TrustKind.TRUSTED or kind == _TrustKind.SEMI_TRUSTED:
            anchor_hash = trust_id
            peers = self._pool.shuffled_urls(4)
        else:
            anchor_hash, peers = self._fetch_latest_trust_id()

        anchors, entries = self._fetch_anchors(anchor_hash, peers)
        trust_set = anchors.compute_trust_set()
        if bytes(trust_set.id).hex() != anchor_hash:
            raise FabricError("decode", "anchor root mismatch")

        with self._lock:
            if kind == _TrustKind.TRUSTED:
                self._anchor_pool.trusted = entries
            elif kind == _TrustKind.SEMI_TRUSTED:
                self._anchor_pool.semi_trusted = entries
            else:
                self._anchor_pool.observed = entries

            # Rebuild veritas from merged anchors
            merged = self._anchor_pool.merged()
            if merged:
                merged_anchors = lv.Anchors.from_json(json.dumps(merged))
                self._veritas = lv.Veritas(merged_anchors)

            if kind == _TrustKind.TRUSTED:
                self._trusted = trust_set
            elif kind == _TrustKind.SEMI_TRUSTED:
                self._semi_trusted = trust_set
            else:
                self._observed = trust_set

    def _resolve_flat(self, handles: list[str]) -> lv.VerifiedMessage:
        by_space: dict[str, list[str]] = {}
        for h in handles:
            space, label = _parse_handle(h)
            by_space.setdefault(space, []).append(label)

        queries = []
        for space, labels in by_space.items():
            q = _Query(space=space, handles=labels)
            with self._lock:
                cached = self._zone_cache.get(space)
                if cached is not None:
                    hint = _epoch_hint_from_zone(cached)
                    if hint is not None:
                        q.epoch_hint = hint
            queries.append(q)

        return self._query(_QueryRequest(queries=queries))

    def _query(self, request: _QueryRequest) -> lv.VerifiedMessage:
        self.bootstrap()

        ctx = lv.QueryContext()
        with self._lock:
            for q in request.queries:
                cached = self._zone_cache.get(q.space)
                if cached is not None:
                    try:
                        ctx.add_zone(lv.zone_to_bytes(cached))
                    except Exception:
                        pass

        if self._prefer_latest:
            relays = self._pick_relays(request, 4)
        else:
            relays = self._pool.shuffled_urls(4)

        verified = self._send_query(ctx, request, relays)

        zones = verified.zones()
        with self._lock:
            for z in zones:
                if z.handle.startswith("@") or z.handle.startswith("#"):
                    self._zone_cache[z.handle] = z

        return verified

    def _send_query(
        self,
        ctx: lv.QueryContext,
        request: _QueryRequest,
        relays: list[str],
    ) -> lv.VerifiedMessage:
        q_parts: list[str] = []
        hint_parts: list[str] = []
        for q in request.queries:
            ctx.add_request(q.space)
            q_parts.append(q.space)
            for h in q.handles:
                if h:
                    ctx.add_request(h + q.space)
                    q_parts.append(h + q.space)
            if q.epoch_hint is not None:
                hint_parts.append(
                    f"{q.space}:{q.epoch_hint.root}:{q.epoch_hint.height}"
                )

        last_err: Exception = FabricError("no_peers", "no peers available")

        for u in relays:
            try:
                params = {"q": ",".join(q_parts)}
                if hint_parts:
                    params["hints"] = ",".join(hint_parts)
                query_url = u + "/query?" + urlencode(params)
                req = Request(query_url)
                with urlopen(req, timeout=10) as resp:
                    resp_bytes = resp.read()
                    if resp.status >= 300:
                        self._pool.mark_failed(u)
                        last_err = FabricError("relay", resp_bytes.decode(), resp.status)
                        continue
            except FabricError:
                raise
            except Exception as e:
                self._pool.mark_failed(u)
                last_err = e
                continue

            try:
                msg = lv.Message(resp_bytes)
            except Exception as e:
                self._pool.mark_failed(u)
                last_err = FabricError("decode", f"{u}/query: {e}")
                continue

            with self._lock:
                v = self._veritas
            if v is None:
                raise FabricError("no_peers", "no veritas instance")

            try:
                options = lv.verify_dev_mode() if self._dev_mode else 0
                verified = v.verify_with_options(ctx, msg, options)
            except Exception as e:
                self._pool.mark_failed(u)
                last_err = FabricError("verify", str(e))
                continue

            self._pool.mark_alive(u)
            return verified

        raise last_err

    def _pick_relays(self, request: _QueryRequest, count: int) -> list[str]:
        hints_query = _hints_query_string(request)
        shuffled = self._pool.shuffled_urls(0)

        results: list[tuple[str, HintsResponse]] = []

        for i in range(0, len(shuffled), count):
            if len(results) >= count:
                break
            batch = shuffled[i : i + count]

            with ThreadPoolExecutor(max_workers=len(batch)) as pool:
                futures = {
                    pool.submit(_fetch_hints, u, hints_query): u for u in batch
                }
                for fut in as_completed(futures):
                    u = futures[fut]
                    try:
                        h = fut.result()
                        results.append((u, h))
                    except Exception:
                        self._pool.mark_failed(u)

        from functools import cmp_to_key
        results.sort(key=cmp_to_key(lambda a, b: -CompareHints(a[1], b[1])))

        return [r[0] for r in results]

    def _fetch_latest_trust_id(self) -> tuple[str, list[str]]:
        votes: dict[str, dict] = {}

        for seed in self._seeds:
            try:
                req = Request(seed + "/anchors", method="HEAD")
                with urlopen(req, timeout=10) as resp:
                    root = resp.headers.get("X-Anchor-Root", "")
                    height_str = resp.headers.get("X-Anchor-Height", "0")
                    height = int(height_str) if height_str else 0
            except Exception:
                continue

            if root:
                key = f"{root}:{height}"
                if key in votes:
                    votes[key]["peers"].append(seed)
                else:
                    votes[key] = {"height": height, "peers": [seed]}

        best_key = ""
        best_score = -1
        for key, v in votes.items():
            score = len(v["peers"]) * 1_000_000 + v["height"]
            if score > best_score:
                best_score = score
                best_key = key

        if not best_key:
            raise FabricError("no_peers", "no peers available")

        parts = best_key.split(":", 1)
        return parts[0], votes[best_key]["peers"]

    def _fetch_anchors(
        self, hash_str: str, peers: list[str]
    ) -> tuple[lv.Anchors, list]:
        last_err: Exception = FabricError("no_peers", "no peers available")

        for u in peers:
            try:
                req = Request(u + "/anchors?root=" + hash_str)
                with urlopen(req, timeout=10) as resp:
                    if resp.status >= 300:
                        last_err = FabricError(
                            "relay", resp.read().decode(), resp.status
                        )
                        continue
                    body = json.loads(resp.read())
            except FabricError:
                raise
            except Exception as e:
                last_err = FabricError("http", str(e))
                continue

            entries = body.get("entries")
            if entries is None:
                last_err = FabricError(
                    "decode", "missing entries in anchor response"
                )
                continue

            try:
                anchors = lv.Anchors.from_json(json.dumps(entries))
            except Exception as e:
                last_err = FabricError("decode", f"parsing anchors: {e}")
                continue

            return anchors, entries

        raise last_err


# -- Utilities --


def _parse_handle(handle: str) -> tuple[str, str]:
    """Returns (space, label)."""
    for i, c in enumerate(handle):
        if c in ("@", "#"):
            if i == 0:
                return handle, ""
            return handle[i:], handle[:i]
    return handle, ""


def _hints_query_string(request: _QueryRequest) -> str:
    parts: set[str] = set()
    for q in request.queries:
        parts.add(q.space)
        for h in q.handles:
            parts.add(h + q.space)
    return ",".join(parts)


def _epoch_hint_from_zone(z: lv.Zone) -> Optional[_EpochHint]:
    if z.commitment.is_exists():
        return _EpochHint(
            root=z.commitment.state_root.hex(),
            height=z.commitment.block_height,
        )
    return None


def _fetch_peers(relay_url: str) -> list[dict]:
    req = Request(relay_url + "/peers")
    with urlopen(req, timeout=10) as resp:
        if resp.status >= 300:
            raise FabricError("relay", resp.read().decode(), resp.status)
        return json.loads(resp.read())


def _fetch_hints(relay_url: str, query: str) -> HintsResponse:
    url = relay_url + "/hints?" + urlencode({"q": query})
    req = Request(url)
    with urlopen(req, timeout=10) as resp:
        if resp.status >= 300:
            raise FabricError("relay", f"hints: status {resp.status}")
        data = json.loads(resp.read())

    return HintsResponse(
        anchor_tip=data.get("anchor_tip", 0),
        spaces=[
            SpaceHint(
                space=s["space"],
                epoch_tip=s["epoch_tip"],
                seq=s["seq"],
                delegate_seq=s["delegate_seq"],
            )
            for s in data.get("spaces", [])
        ],
        epochs=[
            EpochResult(
                epoch_tip=e["epoch_tip"],
                handles=[
                    HandleHint(handle=h["handle"], seq=h["seq"])
                    for h in e.get("handles", [])
                ],
            )
            for e in data.get("epochs", [])
        ],
    )


def _post_json(url: str, body: bytes) -> bytes:
    req = Request(
        url,
        data=body,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urlopen(req, timeout=10) as resp:
        data = resp.read()
        if resp.status >= 300:
            raise FabricError("relay", data.decode(), resp.status)
        return data


def _post_binary(url: str, body: bytes) -> bytes:
    req = Request(
        url,
        data=body,
        headers={"Content-Type": "application/octet-stream"},
        method="POST",
    )
    with urlopen(req, timeout=10) as resp:
        data = resp.read()
        if resp.status >= 300:
            raise FabricError("relay", data.decode(), resp.status)
        return data