localnet-lite 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. localnet_lite/__init__.py +33 -0
  2. localnet_lite/_connect.py +297 -0
  3. localnet_lite/cli.py +443 -0
  4. localnet_lite/defaults/localnet_capture.json +3962 -0
  5. localnet_lite/defaults/weights.json +82 -0
  6. localnet_lite/dev_keys.py +79 -0
  7. localnet_lite/doctor.py +323 -0
  8. localnet_lite/errors.py +126 -0
  9. localnet_lite/lite/__init__.py +1 -0
  10. localnet_lite/lite/client.py +444 -0
  11. localnet_lite/lite/commitments.py +277 -0
  12. localnet_lite/lite/crv3.py +169 -0
  13. localnet_lite/lite/defaults.py +221 -0
  14. localnet_lite/lite/fixed.py +75 -0
  15. localnet_lite/lite/memstats.py +23 -0
  16. localnet_lite/lite/mlkem.py +48 -0
  17. localnet_lite/lite/pool.py +210 -0
  18. localnet_lite/lite/prices.py +76 -0
  19. localnet_lite/lite/server.py +215 -0
  20. localnet_lite/lite/service.py +164 -0
  21. localnet_lite/lite/state.py +1555 -0
  22. localnet_lite/lite/wire.py +36 -0
  23. localnet_lite/lite/yuma.py +350 -0
  24. localnet_lite/parity.py +419 -0
  25. localnet_lite/real.py +645 -0
  26. localnet_lite/real_setup.py +97 -0
  27. localnet_lite/registration.py +42 -0
  28. localnet_lite/runner.py +536 -0
  29. localnet_lite/scaffold.py +70 -0
  30. localnet_lite/scenario.py +238 -0
  31. localnet_lite/templates/subnet/README.md.tmpl +39 -0
  32. localnet_lite/templates/subnet/package/__init__.py +2 -0
  33. localnet_lite/templates/subnet/package/chain.py +99 -0
  34. localnet_lite/templates/subnet/package/miner.py +136 -0
  35. localnet_lite/templates/subnet/package/owner.py +49 -0
  36. localnet_lite/templates/subnet/package/protocol.py +37 -0
  37. localnet_lite/templates/subnet/package/validator.py +160 -0
  38. localnet_lite/templates/subnet/pyproject.toml.tmpl +10 -0
  39. localnet_lite/templates/subnet/scenario.yaml +18 -0
  40. localnet_lite/templates/subnet/tests/test_miner.py.tmpl +50 -0
  41. localnet_lite/templates/subnet/tests/test_protocol.py.tmpl +19 -0
  42. localnet_lite/top.py +228 -0
  43. localnet_lite-0.1.0.dist-info/METADATA +199 -0
  44. localnet_lite-0.1.0.dist-info/RECORD +47 -0
  45. localnet_lite-0.1.0.dist-info/WHEEL +4 -0
  46. localnet_lite-0.1.0.dist-info/entry_points.txt +3 -0
  47. localnet_lite-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,33 @@
1
+ """Localnet Lite: test Bittensor subnets on a laptop.
2
+
3
+ import localnet_lite
4
+ client = localnet_lite.connect() # LNL_MODE=lite | real | unset (plain SDK client)
5
+
6
+ Importing this package stays light (no bittensor import) so `lnl doctor` keeps its budget.
7
+ """
8
+
9
+ from importlib.metadata import PackageNotFoundError, version
10
+
11
+ from .errors import LiteUnsupportedError
12
+
13
+ try:
14
+ __version__ = version("localnet-lite")
15
+ except PackageNotFoundError: # running from a source tree without an install
16
+ __version__ = "0.0.0+unknown"
17
+
18
+
19
+ def connect(network=None, **kw):
20
+ """An async bittensor Client chosen by LNL_MODE (see localnet_lite._connect)."""
21
+ from ._connect import connect as _connect
22
+
23
+ return _connect(network, **kw)
24
+
25
+
26
+ def connect_blocking(network=None, **kw):
27
+ """A blocking bittensor Subtensor chosen by LNL_MODE (see localnet_lite._connect)."""
28
+ from ._connect import connect_blocking as _connect_blocking
29
+
30
+ return _connect_blocking(network, **kw)
31
+
32
+
33
+ __all__ = ["LiteUnsupportedError", "__version__", "connect", "connect_blocking"]
@@ -0,0 +1,297 @@
1
+ """`localnet_lite.connect()`: one line that picks the chain from LNL_MODE.
2
+
3
+ client = localnet_lite.connect() # async bt.Client
4
+ sub = localnet_lite.connect_blocking() # blocking bt.Subtensor
5
+
6
+ | LNL_MODE | returns |
7
+ |----------------|------------------------------------------------------------------------|
8
+ | unset / empty | the plain SDK client, built exactly as the caller asked: unchanged |
9
+ | lite | a client on LiteSubstrate (lnl-state from `lnl up`), Lite network label |
10
+ | real | a client on the Real-mode endpoint (real_endpoint()), no public fallbacks |
11
+ | anything else | ValueError: never fall through to finney by accident |
12
+
13
+ Only public SDK constructor parameters are used (network, substrate, fallback_endpoints,
14
+ archive_endpoints); nothing in the SDK is patched (docs/LITE_CHAIN_SPEC.md §2).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ MODES = ("lite", "real")
25
+ REAL_DEFAULT_ENDPOINT = "ws://127.0.0.1:9944"
26
+
27
+
28
+ def state_dir() -> Path:
29
+ """Where `lnl up` keeps its state: $LNL_HOME, else ./.lnl."""
30
+ return Path(os.environ.get("LNL_HOME") or ".lnl")
31
+
32
+
33
+ def lite_address() -> tuple[str, int]:
34
+ """(host, port) of the running lnl-state: $LNL_LITE_ADDR or <state dir>/state.json."""
35
+ if addr := os.environ.get("LNL_LITE_ADDR"):
36
+ host, _, port = addr.rpartition(":")
37
+ return host or "127.0.0.1", int(port)
38
+ path = state_dir() / "state.json"
39
+ try:
40
+ info = json.loads(path.read_text(encoding="utf-8"))
41
+ except FileNotFoundError:
42
+ raise RuntimeError(
43
+ f"Lite chain not running (no {path}): start it with `lnl up`, or set LNL_LITE_ADDR"
44
+ ) from None
45
+ return info["host"], int(info["port"])
46
+
47
+
48
+ def real_endpoint() -> str:
49
+ """$LNL_REAL_ENDPOINT, else the port `lnl up --real` forwarded (<state dir>/real.json),
50
+ else ws://127.0.0.1:9944 (the official localnet's own port, e.g. on any Docker host)."""
51
+ if endpoint := os.environ.get("LNL_REAL_ENDPOINT"):
52
+ return endpoint
53
+ try:
54
+ info = json.loads((state_dir() / "real.json").read_text(encoding="utf-8"))
55
+ return str(info["endpoint"])
56
+ except (OSError, ValueError, KeyError, TypeError):
57
+ return REAL_DEFAULT_ENDPOINT
58
+
59
+
60
+ def check_real_link() -> None:
61
+ """Before a Real-mode client is handed out: if `lnl up --real` forwarded the endpoint,
62
+ check it answers, and restart a dead or stalled forwarder (real.ensure_link). Endpoints
63
+ set with LNL_REAL_ENDPOINT, or a node on this machine, aren't ours to manage."""
64
+ if os.environ.get("LNL_REAL_ENDPOINT"):
65
+ return
66
+ import sys
67
+
68
+ from . import real
69
+
70
+ real.ensure_link(state_dir(), say=lambda m: print(m, file=sys.stderr, flush=True))
71
+
72
+
73
+ def _mode() -> str:
74
+ mode = os.environ.get("LNL_MODE", "").strip().lower()
75
+ if mode and mode not in MODES:
76
+ raise ValueError(
77
+ f"unknown LNL_MODE={os.environ['LNL_MODE']!r}: use 'lite' or 'real', or unset it "
78
+ "for the normal SDK client"
79
+ )
80
+ return mode
81
+
82
+
83
+ def _keep_sdk_cache_local() -> None:
84
+ """The SDK caches token symbols per network in ~/.bittensor on connect. In Lite mode,
85
+ point that cache (the SDK's own BTCLI_TOKEN_SYMBOLS_CACHE setting) into the state dir."""
86
+ if "BTCLI_TOKEN_SYMBOLS_CACHE" not in os.environ:
87
+ d = state_dir()
88
+ d.mkdir(parents=True, exist_ok=True)
89
+ os.environ["BTCLI_TOKEN_SYMBOLS_CACHE"] = str((d / "token_symbols.json").resolve())
90
+ # Real mode's RPC backend caches runtime metadata in ~/.bittensor/runtime-cache (live
91
+ # run, 30 Nov); BITTENSOR_RUNTIME_CACHE_DIR is the SDK's own setting for it.
92
+ if "BITTENSOR_RUNTIME_CACHE_DIR" not in os.environ:
93
+ os.environ["BITTENSOR_RUNTIME_CACHE_DIR"] = str((state_dir() / "runtime-cache").resolve())
94
+
95
+
96
+ def _kwargs(mode: str, network: str | None, kw: dict[str, Any]) -> tuple[tuple, dict]:
97
+ if mode == "lite":
98
+ from .errors import install_error_hook
99
+ from .lite.client import LiteSubstrate
100
+ from .lite.server import LITE_NETWORK
101
+
102
+ _keep_sdk_cache_local()
103
+ install_error_hook()
104
+ return (LITE_NETWORK,), {**kw, "substrate": LiteSubstrate(*lite_address())}
105
+ if mode == "real":
106
+ from .errors import install_error_hook
107
+
108
+ _keep_sdk_cache_local()
109
+ install_error_hook()
110
+ check_real_link()
111
+ return (real_endpoint(),), {"fallback_endpoints": [], "archive_endpoints": [], **kw}
112
+ return ((network,) if network is not None else ()), kw
113
+
114
+
115
+ CONNECT_ATTEMPTS = 3
116
+ CONNECT_TIMEOUT = 60.0 # seconds per connect attempt (the transport retries inside it)
117
+ LINK_KEEP_EVERY = 10.0 # seconds between link checks while a Real client is connected
118
+
119
+
120
+ def real_client_class():
121
+ """bt.Client whose connect() survives a stall on the codespace link: on a connection
122
+ failure it closes, checks the link (restarting a dead or stalled forwarder), and tries
123
+ again, up to CONNECT_ATTEMPTS times. Only public SDK methods (connect, close) are used;
124
+ the relay behind `gh` stalls now and then for 10-45 s, longer than the SDK's fixed 10 s
125
+ WebSocket handshake timeout (docs/evidence/real_forwarder_investigation.md)."""
126
+ import asyncio
127
+ import contextlib
128
+ import sys
129
+
130
+ import bittensor as bt
131
+
132
+ from .errors import is_connection_error
133
+
134
+ class RealClient(bt.Client):
135
+ """On a link `lnl up --real` manages (no LNL_REAL_ENDPOINT), it also survives a stall
136
+ in the middle of a long-running command (D19): the SDK's own transport reconnects
137
+ for ever (its public `retry_forever`), a link keeper replaces a stalled forwarder,
138
+ and block waits re-subscribe after a reconnect. Pending requests are resubmitted by
139
+ the transport. If the link can't be restored, the command ends with the one-line
140
+ message, as before."""
141
+
142
+ def __init__(self, *args, **kwargs):
143
+ managed = kwargs.pop("lnl_managed", None)
144
+ managed = managed_link() if managed is None else managed
145
+ if managed:
146
+ kwargs.setdefault("retry_forever", True)
147
+ super().__init__(*args, **kwargs)
148
+ self._lnl_setup(managed)
149
+
150
+ def _lnl_setup(self, managed: bool) -> None:
151
+ self._lnl_managed = managed
152
+ self._lnl_keeper = None
153
+ self._lnl_lost = None
154
+
155
+ async def connect(self):
156
+ for attempt in range(1, CONNECT_ATTEMPTS + 1):
157
+ try:
158
+ # bounded: with retry_forever the transport itself never gives up
159
+ result = await asyncio.wait_for(super().connect(), CONNECT_TIMEOUT)
160
+ self._start_keeper()
161
+ return result
162
+ except Exception as e:
163
+ timed_out = isinstance(e, asyncio.TimeoutError | TimeoutError)
164
+ if attempt == CONNECT_ATTEMPTS or not (timed_out or is_connection_error(e)):
165
+ raise
166
+ first = str(e).strip().splitlines()[0] if str(e).strip() else type(e).__name__
167
+ print(
168
+ f"Real mode: connecting failed ({first}); checking the link and "
169
+ f"retrying ({attempt}/{CONNECT_ATTEMPTS - 1})",
170
+ file=sys.stderr,
171
+ flush=True,
172
+ )
173
+ with contextlib.suppress(Exception): # already failed; we reconnect next
174
+ await self.close()
175
+ await asyncio.to_thread(check_real_link)
176
+ raise AssertionError("unreachable")
177
+
178
+ async def close(self):
179
+ if self._lnl_keeper is not None:
180
+ self._lnl_keeper.cancel()
181
+ with contextlib.suppress(asyncio.CancelledError, Exception):
182
+ await self._lnl_keeper
183
+ self._lnl_keeper = None
184
+ await super().close()
185
+
186
+ def _start_keeper(self) -> None:
187
+ if self._lnl_managed and self._lnl_keeper is None:
188
+ self._lnl_keeper = asyncio.create_task(self._keep_link())
189
+
190
+ async def _keep_link(self) -> None:
191
+ """Every LINK_KEEP_EVERY seconds, one RPC through the link; if it doesn't answer,
192
+ restore the link (restart the forwarder). The transport reconnects by itself."""
193
+ from . import real
194
+
195
+ endpoint = real_endpoint()
196
+ while True:
197
+ await asyncio.sleep(LINK_KEEP_EVERY)
198
+ if await asyncio.to_thread(real.rpc_ready, endpoint, real.LINK_CHECK_TIMEOUT):
199
+ continue
200
+ print("Real mode: the link stopped answering; restoring it", file=sys.stderr,
201
+ flush=True) # fmt: skip
202
+ try:
203
+ await asyncio.to_thread(check_real_link)
204
+ except Exception as e: # RealLinkLost: nothing more we can do; end the command
205
+ self._lnl_lost = e
206
+ with contextlib.suppress(Exception):
207
+ await bt.Client.close(self)
208
+ return
209
+ print("Real mode: link restored; carrying on", file=sys.stderr, flush=True)
210
+
211
+ async def wait_for_block(self, block=None, *, timeout=None):
212
+ """The SDK's wait, re-subscribed after a reconnect (a reconnect ends block
213
+ subscriptions; plain requests are resubmitted by the transport)."""
214
+ loop = asyncio.get_running_loop()
215
+ target = block if block is not None else await self.block() + 1
216
+ deadline = None if timeout is None else loop.time() + timeout
217
+ while True:
218
+ left = None if deadline is None else max(0.0, deadline - loop.time())
219
+ try:
220
+ return await super().wait_for_block(target, timeout=left)
221
+ except Exception as e:
222
+ if deadline is not None and loop.time() >= deadline:
223
+ raise # the caller's own timeout
224
+ ended = isinstance(e, bt.ChainError) and "subscription ended" in str(e)
225
+ blip = ended or is_connection_error(e) or isinstance(e, TimeoutError)
226
+ if self._lnl_lost or not blip:
227
+ raise self._lnl_lost or e from e
228
+ await asyncio.sleep(1) # the transport is reconnecting meanwhile
229
+
230
+ async def execute(self, intent, wallet, **kwargs):
231
+ """Neuron registration in the clear on Real (D13), for any code using connect().
232
+
233
+ The SDK always MEV-shields `BurnedRegister` (the intent sets
234
+ `mev_shield_required`), and a shielded registration can't land through the
235
+ codespace link. So it goes through the SDK's public `submit_call(...,
236
+ shielded=False)` instead: the same call, signed by the same coldkey. Kept as
237
+ the SDK does it: an explicit `shielded=True`, a proxy, or a policy that refuses
238
+ raw calls. Every other intent is untouched."""
239
+ if isinstance(intent, bt.BurnedRegister) and _clear_registration_ok(self, kwargs):
240
+ hotkey = intent.hotkey_address(wallet, intent.hotkey_ss58)
241
+ call = bt.calls.SubtensorModule.burned_register(netuid=intent.netuid, hotkey=hotkey)
242
+ keep = ("policy", "period", "wait_for_inclusion", "wait_for_finalization")
243
+ passed = {k: kwargs[k] for k in keep if k in kwargs}
244
+ return await self.submit_call(call, wallet, shielded=False, **passed)
245
+ return await super().execute(intent, wallet, **kwargs)
246
+
247
+ return RealClient
248
+
249
+
250
+ def _clear_registration_ok(client, kwargs: dict) -> bool:
251
+ if kwargs.get("shielded") is True or kwargs.get("proxy_for"):
252
+ return False
253
+ policy = kwargs.get("policy") or getattr(client, "policy", None)
254
+ return policy is None or bool(getattr(policy, "allow_raw_calls", False))
255
+
256
+
257
+ _real_client = None
258
+
259
+
260
+ def _real_client_cls():
261
+ global _real_client
262
+ if _real_client is None:
263
+ _real_client = real_client_class()
264
+ return _real_client
265
+
266
+
267
+ def connect(network: str | None = None, **kw: Any):
268
+ """An async `bt.Client`; LNL_MODE picks the backend (see the module docstring)."""
269
+ mode = _mode()
270
+ import bittensor as bt
271
+
272
+ args, kwargs = _kwargs(mode, network, kw)
273
+ if mode == "real":
274
+ return _real_client_cls()(*args, **kwargs)
275
+ return bt.Client(*args, **kwargs)
276
+
277
+
278
+ def connect_blocking(network: str | None = None, **kw: Any):
279
+ """A blocking `bt.Subtensor`; LNL_MODE picks the backend (see the module docstring)."""
280
+ mode = _mode()
281
+ import bittensor as bt
282
+
283
+ args, kwargs = _kwargs(mode, network, kw)
284
+ if mode == "real" and managed_link():
285
+ kwargs.setdefault("retry_forever", True)
286
+ sub = bt.Subtensor(*args, **kwargs)
287
+ if mode == "real":
288
+ # Its blocking methods run on the Client it wraps; give that Client Real mode's
289
+ # connect retries, link keeping and clear registration.
290
+ sub._client.__class__ = _real_client_cls()
291
+ sub._client._lnl_setup(managed_link())
292
+ return sub
293
+
294
+
295
+ def managed_link() -> bool:
296
+ """The Real endpoint is the `lnl up --real` forward (not an LNL_REAL_ENDPOINT)."""
297
+ return not os.environ.get("LNL_REAL_ENDPOINT")