-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats.py
More file actions
3011 lines (2757 loc) · 157 KB
/
Copy pathstats.py
File metadata and controls
3011 lines (2757 loc) · 157 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
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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2026 Tech1k <https://tech1k.com>
"""Share/hashrate accounting and a tiny status HTTP server."""
from __future__ import annotations
import asyncio
import html as _html
import ipaddress
import itertools
import json
import logging
import time
from collections import deque
from urllib.parse import parse_qs, quote, unquote, urlsplit
from . import __version__, address, assets, cryptonote, qr, util
from .coin import COINBASE_MATURITY
from .stratum import short_agent
log = logging.getLogger("testnetpool.stats")
# AGPL §13: the running version's corresponding source. A forked deployment should
# repoint this at its own published source (footer + /api/info both use it).
SOURCE_URL = "https://github.com/Tech1k/testnetpool.com"
# Brand strings for page <meta> + social cards. TAGLINE is the short slogan (also
# what you'd put on the OG banner image); META_DESCRIPTION is the fuller sentence
# search engines and link previews show.
# Bland + descriptive, a set with CypherFaucet's "Free testnet coins for developers".
TAGLINE = "Testnet mining pool for developers"
META_DESCRIPTION = ("Testnet mining pool for developers - a transparent, open-source pool "
"for Bitcoin, Litecoin, and Monero. Solo or PPLNS, no sign-up.")
# Per-deployment public-URL / share-image, set once from [stats] at server start.
_META = {"site_url": "", "node_dashboard_url": "", "onion": ""}
# Rolling windows (seconds) surfaced on the dashboard / API.
POOL_WINDOWS = (("1m", 60), ("5m", 300), ("1h", 3600), ("1d", 86400))
MINER_WINDOWS = (("5m", 300), ("1h", 3600), ("24h", 86400))
def _limiter_key(ip: str) -> str:
"""Rate-limit key for an IP. IPv6 is collapsed to its /64 so a client holding a /64
(the smallest routed IPv6 allocation) can't rotate unlimited distinct /128 addresses
to defeat the per-IP limit. IPv4 is used verbatim."""
try:
a = ipaddress.ip_address(ip)
except ValueError:
return ip
if a.version == 6:
return f"{ipaddress.ip_network(f'{ip}/64', strict=False).network_address}/64"
return ip
def client_ip(peer_ip: str, xff: str, trust_private: bool = False) -> str:
"""The real client IP for rate limiting. Behind a reverse proxy on LOOPBACK (the
normal topology) the socket peer is the proxy, so trust the last X-Forwarded-For hop.
A private (RFC1918/ULA) peer is trusted ONLY when the operator opts in
(stats.trust_private_proxy) - otherwise a client on a private/overlay bind could spoof
XFF to evade the per-IP limit. A direct public peer is never trusted (XFF is spoofable)."""
if xff:
try:
a = ipaddress.ip_address(peer_ip)
except ValueError:
a = None
if a is not None and (a.is_loopback or (trust_private and a.is_private)):
hop = xff.split(",")[-1].strip()
if hop:
return hop
return peer_ip
class HttpRateLimiter:
"""Per-IP sliding-window rate limit for the stats HTTP server - in-memory, no
dependency. `limit` requests per `window` seconds; limit<=0 disables it."""
MAX_KEYS = 100_000 # bound the tracked-IP map against a distinct-IP flood
def __init__(self, limit: int, window: float = 60.0):
self.limit = limit
self.window = window
self._hits: dict[str, deque] = {}
self._last_prune = 0.0
def allow(self, ip: str, now: float) -> bool:
if self.limit <= 0:
return True
if now - self._last_prune > 300:
self._prune(now)
self._last_prune = now
key = _limiter_key(ip)
dq = self._hits.get(key)
if dq is None:
# Evict the oldest-inserted key when at the cap so a flood of distinct IPs
# (esp. spoofed/rotated) can't grow the map without bound. The 300s prune
# already reclaims idle keys; this is the hard backstop.
if len(self._hits) >= self.MAX_KEYS:
self._hits.pop(next(iter(self._hits)), None)
dq = self._hits[key] = deque()
cutoff = now - self.window
while dq and dq[0] < cutoff:
dq.popleft()
if len(dq) >= self.limit:
return False
dq.append(now)
return True
def _prune(self, now: float) -> None:
cutoff = now - self.window
for ip in list(self._hits):
dq = self._hits[ip]
while dq and dq[0] < cutoff:
dq.popleft()
if not dq:
del self._hits[ip]
# A share of difficulty D represents ~D * coin.hashes_per_diff1 hash attempts
# (2^16 for scrypt, 2^32 for sha256d). The multiplier is taken from the coin.
HASHRATE_WINDOW = 600.0 # seconds
MAX_KEPT_BLOCKS = 200 # in-memory recent-block ring; full history lives in SQLite
# The snapshot drives every dashboard/JSON hit and runs SQLite aggregates + a per-connection
# pass ON the event loop. Browsers poll it (auto-refresh) and CORS is open, so without a cache
# N concurrent viewers => N rebuilds/sec, each stalling share validation. A short TTL collapses
# that to at most one rebuild per window; the dashboard does not need sub-second freshness.
SNAPSHOT_TTL = 2.0 # seconds
# Cap the per-connection array the JSON API serializes (the HTML dashboard never renders it,
# only the connected_miners count + agent histogram). Bounds one rebuild's cost and the
# response size with thousands of rigs; the exact count stays in connected_miners.
MAX_SNAPSHOT_MINERS = 2000
MAX_HTTP_CONNS = 512 # hard concurrent-connection cap for the dashboard/API server
class Stats:
def __init__(self, pool):
self.pool = pool
self.start_time = time.time()
self.accepted_shares = 0
self.total_difficulty = 0.0
self.blocks: deque[dict] = deque(maxlen=MAX_KEPT_BLOCKS)
self.blocks_found = 0 # lifetime count (the deque is capped for display)
self.reject_reasons: dict[str, int] = {} # reason -> count, for transparency
self._recent: deque[tuple[float, float]] = deque() # (time, difficulty)
self._snap_cache: tuple[float, dict] | None = None # (monotonic_ts, snapshot)
def record_share(self, difficulty: float, now: float) -> None:
self.accepted_shares += 1
self.total_difficulty += difficulty
self._recent.append((now, difficulty))
self._trim(now)
def record_reject(self, reason: str) -> None:
"""Tally a rejected share by reason (low-diff / stale / duplicate / ...), so
the API can show the pool isn't silently dropping work."""
self.reject_reasons[reason] = self.reject_reasons.get(reason, 0) + 1
def record_block(self, height: int, block_hash: str, accepted: bool, reason: str) -> None:
if accepted: # a node-rejected candidate isn't a found block
self.blocks_found += 1
self.blocks.append(
{
"height": height,
"hash": block_hash,
"accepted": accepted,
"reason": reason,
"time": int(time.time()),
}
)
def _trim(self, now: float) -> None:
cutoff = now - HASHRATE_WINDOW
while self._recent and self._recent[0][0] < cutoff:
self._recent.popleft()
def hashrate(self) -> float:
now = time.time()
self._trim(now)
if not self._recent:
return 0.0
window = max(now - self._recent[0][0], 1.0)
diff_sum = sum(d for _, d in self._recent)
return diff_sum * self.pool.coin.hashes_per_diff1 / window
def snapshot(self) -> dict:
"""Cached public snapshot. Callers treat the result as read-only (verified: every
external consumer only reads it; all snap[...] writes are inside _build_snapshot),
so returning the shared cached dict within the TTL is safe."""
mono = time.monotonic()
cached = self._snap_cache
if cached is not None and (mono - cached[0]) < SNAPSHOT_TTL:
return cached[1]
snap = self._build_snapshot()
self._snap_cache = (mono, snap)
return snap
def _build_snapshot(self) -> dict:
conns = self.pool.connections
job = self.pool.current_job()
hr = self.hashrate()
net_target = job.network_target if job else None
# Network difficulty (relative to the coin's diff-1) and, given current
# pool hashrate, the expected time to find a block: E[hashes] = 2^256 /
# target, so E[seconds] = (2^256 / target) / hashrate. Coin-independent.
net_diff = (self.pool.coin.diff1_target / net_target) if net_target else None
eta = ((1 << 256) / net_target / hr) if (net_target and hr > 0) else None
# Network hashrate. Prefer the node's own getnetworkhashps (chainwork over the
# ACTUAL elapsed time of recent blocks - the value Bitcoin Core / mempool.space
# report, and the only sane one on testnet, where the 20-min min-difficulty rule
# makes the instantaneous difficulty a terrible proxy). Fall back to the
# difficulty-based estimate H = diff * hashes_per_diff1 / block_time for Monero,
# which has no such RPC and whose per-block retarget makes it the canonical value.
node_hps = getattr(self.pool, "network_hashps", None)
if node_hps:
net_hr = node_hps
else:
block_time = getattr(self.pool.coin, "block_time", 0)
net_hr = (net_diff * self.pool.coin.hashes_per_diff1 / block_time
if (net_diff and block_time) else None)
# NOTE: no peer IP here on purpose - the public API exposes the pool's
# behaviour, never the miners' network identities. The connection id is
# enough to distinguish sessions; raw IPs stay in the operator's logs only.
# Per-connection detail is a JSON-API field only (the HTML dashboard renders the
# connected_miners count + agent histogram, never this list). Cap it so one rebuild
# and the response stay bounded with thousands of rigs; connected_miners stays exact.
miners = [
{
"id": c.id,
"worker": c.worker,
"difficulty": c.vardiff.difficulty,
"accepted": c.accepted,
"rejected": c.rejected,
"best": getattr(c, "best", 0.0),
"last_share_ago": round(time.time() - c.last_share, 1) if c.last_share else None,
}
for c in itertools.islice(conns, MAX_SNAPSHOT_MINERS) # conns is a set; cap the slice
]
# Connected-miner breakdown by self-reported software (public-pool style).
# Self-reported and trivially spoofed, so advisory only. Coarsened to
# product + major.minor (short_agent) before it ever leaves the process: the
# full agent fingerprints a miner (OS/arch/lib/compiler), like its IP, so -
# like the IP - we keep it internal and never publish it.
agent_counts: dict[str, int] = {}
for c in conns:
ua = short_agent(getattr(c, "user_agent", "")) or "unknown"
agent_counts[ua] = agent_counts.get(ua, 0) + 1
snap = {
"coin": self.pool.cfg.coin,
"chain": self.pool.cfg.chain,
"explorer_url": getattr(self.pool.cfg, "explorer_url", ""),
"explorer_tx_url": getattr(self.pool.cfg, "explorer_tx_url", ""),
"algo": self.pool.coin.algo,
"mode": self.pool.cfg.mode,
"uptime": round(time.time() - self.start_time, 1),
"connected_miners": len(conns),
"accepted_shares": self.accepted_shares,
"pool_hashrate_hs": round(hr, 2),
"network_difficulty": round(net_diff, 4) if net_diff else None,
"network_hashrate_hs": round(net_hr, 2) if net_hr else None,
"est_seconds_per_block": round(eta) if eta else None,
"blocks_found": self.blocks_found,
"blocks": list(self.blocks)[-20:],
"height": self.pool.current_height,
# Age of the current block template; rises if the node stalls (lets a
# monitor catch a wedged-but-running pool). None until the first template.
"template_age_seconds": (round(time.time() - self.pool.last_template_ts, 1)
if getattr(self.pool, "last_template_ts", 0) else None),
# Transactions in the block we're currently mining (None = coin not parsed
# for it, e.g. Monero), and the node's mempool depth if we poll it.
"block_txs": (len(job.tx_data) if (job is not None and hasattr(job, "tx_data"))
else None),
"mempool": getattr(self.pool, "mempool", None),
"rejected_shares": sum(self.reject_reasons.values()),
"reject_reasons": dict(self.reject_reasons),
# Count of IPs currently temp-banned for abuse (never the IPs themselves).
"banned_ips": (self.pool.bans.snapshot(time.time())["banned_ips"]
if getattr(self.pool, "bans", None) else 0),
# Node/RPC health: peer count, tip age, sync - so the dashboard can tell
# "node isolated / network stuck" apart from a merely busy node.
"node_health": getattr(self.pool, "node_health", {}) or {},
"include_transactions": bool(getattr(self.pool.cfg, "include_transactions", False)),
# Whether the pool is ACTUALLY building full blocks right now (config OR
# MWEB-forced, from the live job) - the honest signal for the /template view,
# since post-MWEB Litecoin includes every tx even when the config flag is off.
"full_block": bool(getattr(job, "include_transactions", False)),
"miners": miners,
"miner_agents": agent_counts,
# The pool's own faucet (fee + swept-dust destination), so the UI
# can badge it. It's a public pool address, never a miner's identity.
"faucet_address": getattr(getattr(self.pool.cfg, "public", None),
"faucet_address", "") or "",
}
# Public mode: extra pool stats from the DB (hashrate windows, current
# round effort, active/known counts, best share).
acc = self.pool.accounting
if acc is not None:
now = int(time.time())
# Found-block count comes from the DB so it survives restarts (the
# in-memory counter resets to 0 on each start).
snap["blocks_found"] = acc.blocks_found()
mult = self.pool.coin.hashes_per_diff1
pw = acc.pool_hashrate_windows(now)
snap["pool_hashrate"] = {lbl: round(pw[w] * mult / w, 2) for lbl, w in POOL_WINDOWS}
snap["pool_hashrate_hs"] = snap["pool_hashrate"]["5m"] # back-compat
rd, rstart = acc.round_share_diff(now)
snap["current_round"] = {
"share_diff": round(rd, 4),
"network_diff": round(net_diff, 4) if net_diff else None,
"effort_percent": round(rd / net_diff * 100, 2) if net_diff else None,
"round_start_ts": rstart,
"round_age_seconds": (now - rstart) if rstart else None,
}
counts = acc.active_counts(now)
snap["active_miners"] = counts["active_miners"]
snap["known_miners"] = counts["known_miners"]
snap["best_share"] = acc.pool_best_share()
snap["block_counts"] = acc.block_counts()
pub = self.pool.cfg.public
snap["payout"] = {
"model": "PPLNS",
"fee_percent": pub.fee_percent,
"min_payout": pub.min_payout,
"pplns_window": pub.pplns_window,
"maturity_confirmations": getattr(self.pool.coin, "maturity", COINBASE_MATURITY),
"payout_interval_seconds": pub.payout_interval,
"sweep_after_days": pub.sweep_after_days,
}
else:
snap["pool_hashrate"] = {lbl: (snap["pool_hashrate_hs"] if w <= 600 else None)
for lbl, w in POOL_WINDOWS}
snap["current_round"] = None
snap["active_miners"] = None
snap["known_miners"] = None
# Solo keeps no DB, so the best share is the best across live sessions.
live_best = max((getattr(c, "best", 0.0) for c in conns), default=0.0)
snap["best_share"] = live_best or None
snap["block_counts"] = None
snap["payout"] = {"model": "solo",
"maturity_confirmations": getattr(self.pool.coin, "maturity", COINBASE_MATURITY)}
return snap
# --- formatting / escaping helpers ------------------------
def esc(s) -> str:
"""HTML-escape for text AND double-quoted attributes (quote=True)."""
return _html.escape("" if s is None else str(s), quote=True)
def _fmt_num(n) -> str:
"""Compact human number for the UI (None -> em-dash placeholder). The number
formatting itself lives in util.numfmt so logs and dashboard agree exactly and
neither ever shows scientific notation."""
return "—" if n is None else util.numfmt(n)
def fmt_coins(base_units, dp: int = 8) -> str:
"""Integer base units (1e8 = 1 coin) -> fixed-dp decimal, integer math only."""
if base_units is None:
return "—"
neg = base_units < 0
whole, frac = divmod(abs(int(base_units)), 100_000_000)
s = f"{whole:,}.{frac:08d}"
if dp == 0:
s = s.split(".")[0]
elif dp != 8:
s = s[: -(8 - dp)]
return ("-" if neg else "") + s
def fmt_hashrate(hs) -> str:
if not hs:
return "0 H/s"
hs = float(hs)
for unit in ("H/s", "KH/s", "MH/s", "GH/s", "TH/s", "PH/s", "EH/s", "ZH/s"):
if hs < 1000:
return f"{hs:.2f} {unit}"
hs /= 1000
return f"{hs:.2f} YH/s"
def fmt_count(n) -> str:
if n is None:
return "—"
return f"{int(n):,}".replace(",", " ") # narrow no-break space
def ago(ts) -> str:
if not ts:
return "—"
d = int(time.time()) - int(ts)
if d < 0:
return "just now"
for unit, size in (("s", 60), ("m", 60), ("h", 24), ("d", 365)):
if d < size:
return f"{d}{unit} ago"
d //= size
return f"{d}y ago"
def fmt_duration(seconds) -> str:
if not seconds:
return "—"
seconds = float(seconds)
for unit, size in (("s", 60), ("m", 60), ("h", 24), ("d", 365)):
if seconds < size:
return f"{seconds:.1f}{unit}"
seconds /= size
return f"{seconds:.1f}y"
def trunc(s, head: int = 8, tail: int = 4) -> str:
"""Middle-truncate AND escape. Never re-escape the result."""
s = "" if s is None else str(s)
shown = s if len(s) <= head + tail + 1 else f"{s[:head]}…{s[-tail:]}"
return esc(shown)
def addr_link(addr, base: str = "", faucet: str = "") -> str:
"""Link an address to its full miner page at ``{base}/miner/<addr>``. If it is
the pool's ``faucet`` address (fee + swept-dust destination), badge it so it is
not mistaken for a regular miner - it tops payouts/balances by design."""
a = "" if addr is None else str(addr)
link = f'<a href="{esc(base)}/miner/{esc(quote(a, safe=""))}">{trunc(a)}</a>'
if faucet and a == faucet:
link += (' <span class="pill faucet" '
'title="The pool\'s faucet - pool fees + swept dust collect here">faucet</span>')
return link
def _worker_link(base: str, addr: str, worker: str) -> str:
"""Link a named rig to its per-worker page; the default (unnamed) rig stays
plain text (there is no name to drill into)."""
label = worker or "(default)"
if not worker or worker == "(default)":
return esc(label)
return (f'<a href="{esc(base)}/worker/{esc(quote(addr, safe=""))}/'
f'{esc(quote(worker, safe=""))}">{esc(label)}</a>')
def _live_for_address(pool, addr: str) -> list:
"""Currently-connected sessions for an address, read straight off the live
connections - no DB, so it works in solo mode too, and it never exposes an IP.
Keyed on the connection's parsed ``address`` (set in every mode), so it answers
"is this rig healthy right now". Resets on reconnect by design."""
now_f = time.time()
out = []
for c in pool.connections:
if getattr(c, "address", "") != addr or not addr:
continue
ls = getattr(c, "last_share", 0) or 0
vd = getattr(c, "vardiff", None)
out.append({
"worker": getattr(c, "worker_name", "") or "(default)",
"difficulty": vd.difficulty if vd else None,
"accepted": getattr(c, "accepted", 0),
"rejected": getattr(c, "rejected", 0),
"best": getattr(c, "best", 0.0),
# Coarsened (product + major.minor) - never the full fingerprinting agent.
"user_agent": short_agent(getattr(c, "user_agent", "")),
"last_share_ago": round(now_f - ls, 1) if ls else None,
})
return out
def _solo_detail(pool, addr: str) -> dict | None:
"""A live-only miner detail built from the connections (solo mode keeps no DB).
None if no rig is currently connected under that address. Money/share-history
fields are deliberately absent - the renderers treat ``solo`` as marker."""
live = _live_for_address(pool, addr)
if not live:
return None
best = max((w.get("best") or 0.0 for w in live), default=0.0)
return {"address": addr, "solo": True, "live": live, "best_share": best or None}
def block_link(height, base: str = "") -> str:
return f'<a href="{esc(base)}/block/{esc(quote(str(height), safe=""))}">{fmt_count(height)}</a>'
def _parse_height(h: str):
"""Parse a block-height path segment to an int, or None if invalid.
``str.isdigit()`` alone is not enough: it is True for non-ASCII digit
characters (``²``, ``③``) that ``int()`` rejects with ValueError, and a huge
all-digit string parses fine but overflows SQLite's signed 64-bit bind
(OverflowError). Both must fall through to the not-found path, not crash.
"""
if h.isascii() and h.isdigit():
n = int(h)
if 0 <= n < (1 << 63):
return n
return None
def luck_cell(pct):
"""(text, css_class) for a luck/effort %. <=100 = good (green), else amber."""
if pct is None:
return "—", "dim"
return f"{pct:.0f}%", ("luck-good" if pct <= 100 else "luck-bad")
# Liveness thresholds (seconds) for a worker's last share. ONLINE matches the
# active-miner window; testnet/low-hashrate rigs can be quiet for minutes, so the
# IDLE band is generous before a worker is called OFFLINE.
WORKER_ONLINE_S = 600
WORKER_IDLE_S = 1800
def worker_status_pill(last_seen, now) -> str:
"""An online/idle/offline pill from a worker's last-share timestamp."""
if not last_seen:
return '<span class="st st-offline">offline</span>'
age = now - last_seen
if age < WORKER_ONLINE_S:
return '<span class="st st-online">online</span>'
if age < WORKER_IDLE_S:
return '<span class="st st-idle">idle</span>'
return '<span class="st st-offline">offline</span>'
STATUS_CLASS = {"immature": "st-immature", "matured": "st-matured",
"orphaned": "st-orphaned", "stale": "st-stale"}
def status_pill(status, confs=None, maturity=None) -> str:
cls = STATUS_CLASS.get(status, "st-immature")
label = status
# For an immature block, show how close it is to paying out, e.g. "immature 30/100".
if status == "immature" and confs is not None and maturity:
label = f"immature {max(0, min(int(maturity), int(confs)))}/{int(maturity)}"
return f'<span class="st {cls}">{esc(label)}</span>'
def block_status_pill(block, snap) -> str:
"""status_pill for a found block, adding the maturity progress (confs / required) to an
immature one. confs = current tip height - the block's height (matches the maturity loop)."""
confs = maturity = None
if block.get("status") == "immature":
tip, h = snap.get("height"), block.get("height")
maturity = snap.get("payout", {}).get("maturity_confirmations", COINBASE_MATURITY)
if tip is not None and h is not None:
confs = tip - h
return status_pill(block.get("status"), confs, maturity)
def coin_ticker(coin, chain) -> str:
base = {"bitcoin": "BTC", "litecoin": "LTC", "monero": "XMR"}.get(coin, (coin or "?")[:3].upper())
chain = chain or ""
if chain.startswith("stage"): # Monero stagenet -> sXMR (distinct from testnet's tXMR)
return "s" + base
if chain.startswith(("test", "signet", "regtest")):
return "t" + base
return base
def chain_label(chain) -> str:
"""Human chain name for display: litecoin/bitcoin call testnet "test" and
mainnet "main" internally; show the full words instead."""
return {"test": "testnet", "main": "mainnet"}.get(chain, chain or "?")
# Friendly algorithm names for the UI (the cpuminer/xmrig command keeps the raw
# id: "sha256d"/"scrypt"/"rx/0"). sha256d is double-SHA256 - miners call it SHA-256.
ALGO_LABEL = {"sha256d": "SHA-256", "scrypt": "Scrypt", "randomx": "RandomX"}
def algo_label(algo) -> str:
return ALGO_LABEL.get(algo, algo or "?")
# Built-in block-explorer URL templates per coin+chain ("{hash}" is filled in), so
# block pages link out with zero config. A coin's explorer_url in config overrides
# its default. No entry (e.g. regtest) -> no link.
DEFAULT_EXPLORERS = {
("bitcoin", "main"): "https://mempool.space/block/{hash}",
("bitcoin", "test"): "https://mempool.space/testnet/block/{hash}",
("bitcoin", "testnet4"): "https://mempool.space/testnet4/block/{hash}",
("bitcoin", "signet"): "https://mempool.space/signet/block/{hash}",
("litecoin", "main"): "https://litecoinspace.org/block/{hash}",
("litecoin", "test"): "https://litecoinspace.org/testnet/block/{hash}",
("monero", "mainnet"): "https://xmrchain.net/block/{hash}",
("monero", "stagenet"): "https://stagenet.xmrchain.net/block/{hash}",
("monero", "testnet"): "https://testnet.xmrchain.com/block/{hash}",
}
def explorer_for(coin, chain, configured="") -> str:
"""Block-explorer URL template; a configured explorer_url overrides the built-in
per-coin/chain default. Empty for chains with no public explorer (regtest)."""
return configured or DEFAULT_EXPLORERS.get((coin, chain), "")
def _tx_explorer(block_explorer: str) -> str:
"""Best-effort tx-explorer template ('.../tx/{txid}') derived from a block-explorer
template ('.../block/{hash}'); '' when it can't be derived (then we just show txids)."""
if block_explorer and "/block/{hash}" in block_explorer:
return block_explorer.replace("/block/{hash}", "/tx/{txid}")
return ""
def tx_explorer_for(coin, chain, explorer_url="", explorer_tx_url="") -> str:
"""Resolve the tx-explorer template ('.../tx/{txid}'): an explicit explorer_tx_url wins,
otherwise derive it from the (configured or built-in) block explorer. '' when none."""
return explorer_tx_url or _tx_explorer(explorer_for(coin, chain, explorer_url))
def _txid_cell(txid, tx_tpl, head=12, tail=8) -> str:
"""A <td> with the (truncated) txid, linked to the block explorer's tx page when a
tx-template is available; plain monospace otherwise (regtest / no public explorer)."""
txid = str(txid or "")
short = esc(trunc(txid, head, tail)) if txid else "—"
if txid and tx_tpl:
url = esc(tx_tpl.replace("{txid}", quote(txid, safe="")))
return (f'<td class=mono><a href="{url}" target=_blank rel=noopener '
f'title="view transaction on block explorer">{short}</a></td>')
return f'<td class=mono>{short}</td>'
# --- dashboard (light + dark, OS-following) ---
# Color tokens per mode. Light is the default; the OS
# preference switches to dark via prefers-color-scheme, and data-theme on <html>
# forces a choice. Dim foregrounds clear WCAG AA on their surfaces in BOTH modes
# (guarded by tests/dashboard.py::test_contrast).
_LIGHT = {
"bg": "#f7f7f7", "card": "#ffffff", "surface": "#f4f5f7", "row-alt": "#f8f8f8",
"border": "#e5e5e5", "border2": "#cccccc",
"text": "#1b1d23", "soft": "#44474e", "muted": "#6b6b6b", "faint": "#686c75",
"accent": "#5271ff", "accent-soft": "#2f49c9", "accent-bg": "#eef1ff", "accent-dim": "#d7ddff",
"on-accent": "#ffffff", "btn": "#3f57e0", "nav-bg": "rgba(255,255,255,.85)",
"ok": "#2a8a4a", "warn": "#b5532a", "bad": "#b52a2a", "num": "#1b1d23", "scheme": "light",
}
_DARK = {
"bg": "#14161b", "card": "#1c1f27", "surface": "#232730", "row-alt": "#1f232b",
"border": "#2a2e37", "border2": "#3a3f4a",
"text": "#e6e8ec", "soft": "#c4c8d0", "muted": "#9aa0ab", "faint": "#8b919b",
"accent": "#6b86ff", "accent-soft": "#9db2ff", "accent-bg": "#1b2236", "accent-dim": "#2e3a5c",
"on-accent": "#0b1020", "btn": "#6b86ff", "nav-bg": "rgba(20,22,27,.86)",
"ok": "#4fbf75", "warn": "#e0894f", "bad": "#ef6b6b", "num": "#e6e8ec", "scheme": "dark",
}
_STATIC_VARS = (
"--font:'Inter',system-ui,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;"
"--mono:ui-monospace,'SF Mono','JetBrains Mono','DejaVu Sans Mono',Menlo,Consolas,'Liberation Mono',monospace;"
"--r:10px;--r-sm:7px;--pill:999px;--s1:4px;--s2:8px;--s3:12px;--s4:16px;--s5:24px;--s6:32px;"
)
def _vars(d: dict) -> str:
return "".join(f"--{k}:{v};" for k, v in d.items() if k != "scheme") + f"color-scheme:{d['scheme']};"
_ROOT_CSS = (
":root{" + _vars(_LIGHT) + _STATIC_VARS + "}"
'@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){' + _vars(_DARK) + "}}"
':root[data-theme="dark"]{' + _vars(_DARK) + "}"
)
_CSS = _ROOT_CSS + """
*{box-sizing:border-box}
html{background:var(--bg)}
body{margin:0;background:var(--bg);color:var(--text);
font:14px/1.5 var(--font);font-variant-numeric:tabular-nums;-webkit-font-smoothing:antialiased}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline;text-underline-offset:2px}
.ico{display:inline-flex;vertical-align:-2px}
.ico svg{width:15px;height:15px;display:block}
/* trailing "leaves the site" marker - small, dim, lifted toward the cap height */
.ext-ico{display:inline-flex;vertical-align:2px;margin-left:3px;opacity:.55}
.ext-ico svg{width:10px;height:10px;display:block}
a:hover .ext-ico{opacity:.9}
/* nav */
nav{position:sticky;top:0;z-index:50;display:flex;align-items:center;gap:var(--s4);
height:54px;padding:0 var(--s5);background:var(--nav-bg);
backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);border-bottom:1px solid var(--border)}
.brand{display:flex;align-items:center;gap:var(--s2);font-weight:700;color:var(--text);
letter-spacing:.3px;font-size:15px}
.brand:hover{text-decoration:none}
.brand-mark{display:flex} .brand-mark svg{width:24px;height:24px;display:block}
.nav-links{display:flex;gap:2px;flex-wrap:wrap}
.nav-links a{color:var(--soft);padding:6px 11px;border-radius:var(--r-sm);font-size:13px;font-weight:500}
.nav-links a:hover{color:var(--text);background:var(--surface);text-decoration:none}
.nav-links a.cur{color:var(--accent-soft);background:var(--accent-bg)} /* current page */
.navfind{display:inline-flex;align-items:center;gap:4px;margin-left:4px}
.navfind input{background:var(--card);border:1px solid var(--border2);color:var(--text);
border-radius:var(--r-sm);padding:5px 9px;font:13px var(--font);width:148px;min-width:96px}
.navfind input::placeholder{color:var(--faint)}
.navfind input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-bg)}
.navfind button{display:inline-flex;align-items:center;justify-content:center;cursor:pointer;
background:none;border:1px solid var(--border2);color:var(--muted);border-radius:var(--r-sm);padding:5px 7px}
.navfind button:hover{color:var(--text);border-color:var(--accent)}
.navfind button svg{width:15px;height:15px}
.theme-toggle{background:none;border:1px solid var(--border2);color:var(--muted);
border-radius:var(--r-sm);padding:5px 7px;cursor:pointer;display:inline-flex;
align-items:center;line-height:0;font:inherit}
.theme-toggle:hover{color:var(--text);border-color:var(--accent)}
.theme-toggle .ico-sun{display:none}
:root[data-theme="dark"] .theme-toggle .ico-sun{display:inline-flex}
:root[data-theme="dark"] .theme-toggle .ico-moon{display:none}
@media (prefers-color-scheme:dark){
:root:not([data-theme="light"]) .theme-toggle .ico-sun{display:inline-flex}
:root:not([data-theme="light"]) .theme-toggle .ico-moon{display:none}
}
.nav-right{margin-left:auto;display:flex;align-items:center;gap:var(--s3);
color:var(--muted);font-size:12px;font-family:var(--mono)}
.nav-stats{display:inline-flex;align-items:center;gap:var(--s3)}
.nav-stats .ns{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}
.nav-stats .ns .ico{color:var(--accent)} .nav-stats .ns svg{width:13px;height:13px}
.nav-stats .ns b{color:var(--soft);font-weight:600}
.live-status{display:inline-flex;align-items:center;gap:6px}
.live-dot{color:var(--ok);display:inline-flex;animation:pulse 2s ease-in-out infinite}
.live-dot svg{width:9px;height:9px}
.live-dot.stale{color:var(--warn);animation:none} /* API unreachable */
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.3}}
.chips{display:flex;flex-wrap:wrap;gap:8px;margin:4px 0 14px}
/* page */
.wrap{max-width:1180px;margin:0 auto;padding:var(--s5) var(--s5) var(--s6)}
/* coin context bar */
.coinbar{display:flex;align-items:center;flex-wrap:wrap;gap:var(--s2) var(--s3);margin-bottom:var(--s5)}
.coin-badge{display:inline-flex;align-items:center;gap:8px;font-weight:600;font-size:16px;color:var(--text)}
.coin-mark{display:inline-flex} .coin-mark svg{width:20px;height:20px;display:block;border-radius:50%}
.pill{display:inline-flex;align-items:center;gap:5px;padding:3px 9px;border-radius:var(--pill);
font-size:11px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;
background:var(--surface);border:1px solid var(--border2);color:var(--soft)}
.pill.accent{background:var(--accent-bg);border-color:var(--accent-dim);color:var(--accent-soft)}
.pill.faucet{background:rgba(79,191,117,.13);border-color:rgba(79,191,117,.4);color:var(--ok)}
/* hero KPI cards */
.hero{display:grid;gap:var(--s3);grid-template-columns:repeat(auto-fit,minmax(190px,1fr));margin-bottom:var(--s5)}
.kpi{background:var(--card);border:1px solid var(--border);border-radius:var(--r);padding:var(--s4)}
.kpi .top{display:flex;align-items:center;gap:7px;color:var(--muted);font-size:11px;
text-transform:uppercase;letter-spacing:.07em}
.kpi .top .ico{color:var(--accent)}
.kpi .val{margin-top:9px;font:600 26px/1.1 var(--mono);color:var(--num);white-space:nowrap}
.kpi .val .u{font-size:13px;color:var(--faint);font-weight:400;margin-left:4px}
.kpi .val.ok{color:var(--ok)} .kpi .val.warn{color:var(--warn)}
/* secondary stat grid */
/* Cells carry their own hairline (box-shadow), and the grid background matches the
card - so a partial last row leaves no highlighted empty tracks, it just blends. */
.stats{display:grid;gap:0;background:var(--card);border:1px solid var(--border);
border-radius:var(--r);overflow:hidden;margin-bottom:var(--s5);
grid-template-columns:repeat(auto-fit,minmax(168px,1fr))}
.stat{background:var(--card);padding:var(--s3) var(--s4);box-shadow:0 0 0 .5px var(--border)}
/* label wraps (icon stays top-aligned) instead of being clipped by the card's
overflow:hidden when it's wider than the column, e.g. "NETWORK DIFFICULTY". */
.stat .k{display:flex;align-items:flex-start;gap:6px;color:var(--faint);font-size:11px;
text-transform:uppercase;letter-spacing:.05em;line-height:1.3}
.stat .k .ico{flex:none;margin-top:1px}
.stat .k .ico svg{width:13px;height:13px}
.stat .v{margin-top:5px;font:500 16px/1.2 var(--mono);color:var(--soft);white-space:nowrap}
.stat .v .u{color:var(--faint);font-size:12px;margin-left:3px}
.stat .v a{color:var(--accent-soft);text-decoration:none}
.stat .v a:hover{text-decoration:underline}
.stat .v.good{color:var(--ok)} .stat .v.bad{color:var(--warn)}
/* section heading */
h2{display:flex;align-items:center;gap:8px;font-size:12px;font-weight:600;color:var(--muted);
text-transform:uppercase;letter-spacing:.09em;margin:40px 0 var(--s3);
padding-bottom:7px;border-bottom:1px solid var(--border);scroll-margin-top:64px}
h2 .ico{color:var(--accent)}
/* card-wrapped tables */
.card{background:var(--card);border:1px solid var(--border);border-radius:var(--r);
overflow:hidden;margin-bottom:var(--s2)}
.tablewrap{overflow-x:auto;-webkit-overflow-scrolling:touch}
table{border-collapse:collapse;width:100%;font-size:13px}
thead th{background:var(--surface);color:var(--faint);font-weight:600;text-transform:uppercase;
font-size:11px;letter-spacing:.04em;text-align:left;padding:9px 14px;white-space:nowrap;
border-bottom:1px solid var(--border)}
tbody td{padding:10px 14px;border-top:1px solid var(--border);white-space:nowrap;color:var(--soft)}
tbody tr:first-child td{border-top:none}
tbody tr:nth-child(even){background:var(--row-alt)}
tbody tr:hover td{background:var(--surface)}
.rowlink{cursor:pointer}
td.num,th.num{text-align:right;font-family:var(--mono);color:var(--num)}
.mono{font-family:var(--mono)}
td.mono{font-family:var(--mono);color:var(--muted)}
.faucet-addr{margin-top:7px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;
background:var(--bg);border:1px solid var(--border);border-radius:var(--r-sm);padding:8px 10px}
.faucet-addr .lbl{font-size:11px;text-transform:uppercase;letter-spacing:.04em;color:var(--faint);flex:none}
.faucet-addr a{font-family:var(--mono);font-size:13px;color:var(--accent)}
.faucet-addr .copy-btn{margin-left:auto}
td.dim{color:var(--faint)}
.empty{color:var(--faint);text-align:center;padding:var(--s5)}
/* status / luck */
.st{display:inline-block;padding:2px 8px;border-radius:var(--pill);font-size:10.5px;
font-weight:600;text-transform:uppercase;letter-spacing:.03em}
.st-matured{color:var(--ok);background:rgba(79,191,117,.13)}
.st-immature{color:var(--warn);background:rgba(224,137,79,.13)}
.st-orphaned{color:var(--bad);background:rgba(239,107,107,.13);text-decoration:line-through}
.st-stale{color:var(--faint);background:var(--surface);text-decoration:line-through}
.st-online{color:var(--ok);background:rgba(79,191,117,.13)}
.st-idle{color:var(--warn);background:rgba(224,137,79,.13)}
.st-offline{color:var(--faint);background:var(--surface)}
.luck-good{color:var(--ok)} .luck-bad{color:var(--warn)}
/* lookup */
.lookup{display:flex;gap:var(--s2);flex-wrap:wrap;margin-bottom:var(--s3)}
.lookup input{flex:1;min-width:260px;background:var(--card);color:var(--text);
border:1px solid var(--border2);border-radius:var(--r-sm);padding:9px 12px;font:13px var(--mono)}
.lookup input::placeholder{color:var(--faint)}
.lookup input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-bg)}
.lookup button{background:var(--btn);color:var(--on-accent);border:none;border-radius:var(--r-sm);
padding:9px 18px;font:600 13px var(--font);cursor:pointer}
.lookup button:hover{opacity:.9}
/* /find disambiguation list */
.find-cands{list-style:none;display:flex;flex-direction:column;gap:8px;margin:14px 0;max-width:440px}
.find-cands a{display:flex;align-items:center;gap:10px;background:var(--card);
border:1px solid var(--border);border-radius:var(--r);padding:12px 14px;color:var(--text)}
.find-cands a:hover{border-color:var(--accent);text-decoration:none}
.find-cands .coin-mark svg{width:22px;height:22px}
.find-cands .ch{color:var(--faint);font-size:12px}
/* miner detail */
.detail{background:var(--card);border:1px solid var(--border);border-radius:var(--r);
padding:var(--s4);margin-bottom:var(--s3)}
.detail .addr{color:var(--accent);font-family:var(--mono);word-break:break-all;
margin-bottom:var(--s3);font-size:13px}
.kv{display:grid;gap:1px;background:var(--border);border:1px solid var(--border);
border-radius:var(--r-sm);overflow:hidden;grid-template-columns:repeat(auto-fit,minmax(150px,1fr))}
.kv>div{background:var(--card);padding:var(--s2) var(--s3)}
.kv .k{color:var(--faint);font-size:11px;text-transform:uppercase}
.kv .v{margin-top:3px;font-family:var(--mono);color:var(--soft);font-size:13px}
.detail .card{margin-top:var(--s3);margin-bottom:0}
.notfound{color:var(--warn);margin-bottom:var(--s3)}
/* landing coin cell */
.coin-cell{display:flex;align-items:center;gap:9px}
.coin-cell .coin-mark svg{width:22px;height:22px}
.coin-cell b{color:var(--text)} .coin-cell .ch{color:var(--faint);font-weight:400}
/* footer */
footer{max-width:1180px;margin:var(--s6) auto 0;padding:var(--s4) var(--s5);
border-top:1px solid var(--border);display:flex;flex-wrap:wrap;align-items:center;
gap:var(--s2) var(--s4);color:var(--faint);font-size:12px}
footer a{color:var(--muted);display:inline-block;padding:6px 4px;margin:-4px 0}
footer a:hover{color:var(--text)}
footer .grow{margin-left:auto}
.disclaimer{max-width:760px;margin:var(--s2) auto var(--s5);padding:0 var(--s5);
color:var(--faint);font-size:11px;line-height:1.5;text-align:center}
/* keyboard focus: a visible, theme-matched ring on every header/footer control */
.brand:focus-visible,.nav-links a:focus-visible,.theme-toggle:focus-visible,footer a:focus-visible{
outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--r-sm)}
/* respect reduced-motion: stop the only looping animation (the live status dot) */
@media (prefers-reduced-motion:reduce){.live-dot{animation:none}.chart-tip{transition:none}}
/* charts (server-rendered inline SVG; instant JS tooltip + native <title> fallback) */
.chart-wrap{background:var(--card);border:1px solid var(--border);border-radius:var(--r);
padding:var(--s3) var(--s4) var(--s2);margin-bottom:var(--s5)}
.chart-title{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:11px;
text-transform:uppercase;letter-spacing:.07em;margin-bottom:var(--s2)}
.chart-title .ico{color:var(--accent)} .chart-title .sub{color:var(--faint);margin-left:auto;font-family:var(--mono);text-transform:none;letter-spacing:0}
.chart-tabs{margin-left:auto;display:inline-flex;gap:2px}
.chart-tabs a{color:var(--faint);font-family:var(--mono);text-transform:none;letter-spacing:0;
font-size:11px;padding:2px 7px;border-radius:var(--r-sm)}
.chart-tabs a:hover{color:var(--text);background:var(--surface);text-decoration:none}
.chart-tabs a.cur{color:var(--accent-soft);background:var(--accent-bg)}
.chart{width:100%;height:140px;display:block}
.chart rect:hover{fill:rgba(107,134,255,.12)}
.chart rect{cursor:crosshair}
.chart-tip{position:fixed;z-index:60;pointer-events:none;left:0;top:0;
transform:translate(-50%,calc(-100% - 10px));background:var(--card);color:var(--text);
border:1px solid var(--border2);border-radius:var(--r-sm);padding:5px 9px;
font:12px/1.2 var(--mono);white-space:nowrap;box-shadow:0 6px 18px rgba(0,0,0,.28);
opacity:0;transition:opacity .08s ease}
.chart-tip.show{opacity:1}
.chart-tip.below{transform:translate(-50%,12px)} /* flipped when near the top edge */
.chart-axis{display:flex;justify-content:space-between;color:var(--faint);font-size:11px;
font-family:var(--mono);margin-top:4px}
.chart-empty{color:var(--faint);text-align:center;padding:var(--s5);font-size:13px}
/* connect / getting-started */
.connect{display:grid;gap:var(--s3);grid-template-columns:repeat(auto-fit,minmax(320px,1fr));margin-bottom:var(--s4)}
.cc{background:var(--card);border:1px solid var(--border);border-radius:var(--r);overflow:hidden}
.cc-h{display:flex;align-items:center;gap:8px;padding:var(--s3) var(--s4);
border-bottom:1px solid var(--border);font-weight:600;background:var(--surface)}
.cc-b{padding:var(--s3) var(--s4)}
.cc-row{display:flex;gap:var(--s3);padding:6px 0;font-size:13px;align-items:baseline}
.cc-row .k{color:var(--faint);min-width:84px;font-size:11px;text-transform:uppercase;letter-spacing:.04em}
.cc-row .v{font-family:var(--mono);color:var(--soft);word-break:break-all;
display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.cc-row .v .dim{color:var(--faint)}
.copy-btn.mini{margin:0;padding:1px 8px;font-size:11px}
.cc-dash{display:inline-block;margin-top:var(--s3);font-size:12px;color:var(--accent)}
.cc-dash:hover{text-decoration:underline}
.cc-cli{margin-top:var(--s2)}
.cc-cli summary{cursor:pointer;color:var(--faint);font-size:11px;text-transform:uppercase;
letter-spacing:.04em;list-style:revert}
.cc-cli summary:hover{color:var(--muted)}
.cc-cfg{display:flex;gap:var(--s2);margin:var(--s2) 0 4px}
.cc-cfg input{flex:1;min-width:0;background:var(--card);color:var(--text);
border:1px solid var(--border2);border-radius:var(--r-sm);padding:7px 10px;font:13px var(--mono)}
.cc-cfg input::placeholder{color:var(--faint)}
.cc-cfg input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-bg)}
.cc-cli .code{position:relative;padding-right:52px}
.cc-cmdcopy{position:absolute;top:8px;right:8px;margin:0}
.cc-cli .code{margin-top:var(--s2)}
.code{background:var(--bg);border:1px solid var(--border);border-radius:var(--r-sm);padding:10px 12px;
font-family:var(--mono);font-size:12px;color:var(--accent-soft);white-space:pre-wrap;
word-break:break-all;line-height:1.6;margin-top:var(--s2)}
.note{color:var(--faint);font-size:12px;line-height:1.6}
/* donate */
.donate-intro{max-width:660px;color:var(--muted);line-height:1.6;margin:0 0 var(--s4);font-size:14px}
.legal{max-width:68ch;color:var(--soft);line-height:1.65;margin:0 0 var(--s3);font-size:14px}
.openalias{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;background:var(--accent-bg);
border:1px solid var(--accent-dim);border-radius:var(--r);padding:12px 16px;margin-bottom:var(--s5)}
.openalias .lbl{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.06em}
.openalias .oa{font-family:var(--mono);font-weight:700;color:var(--accent-soft);font-size:15px}
.openalias .note{margin-left:auto}
.dcards{display:grid;gap:var(--s3);grid-template-columns:repeat(auto-fit,minmax(300px,1fr));margin-bottom:var(--s4)}
.dcard{background:var(--card);border:1px solid var(--border);border-radius:var(--r);overflow:hidden}
.dcard-h{display:flex;align-items:center;gap:9px;padding:var(--s3) var(--s4);font-weight:600;
background:var(--surface);border-bottom:1px solid var(--border)}
.dcard-h .coin-mark svg{width:22px;height:22px}
.dcard-b{padding:var(--s3) var(--s4)}
.qr{display:block;width:168px;height:168px;margin:0 auto var(--s3);border-radius:var(--r-sm);
background:#fff;padding:8px;box-sizing:content-box}
.dcard .addr{font-family:var(--mono);font-size:12px;word-break:break-all;background:var(--bg);
border:1px solid var(--border);border-radius:var(--r-sm);padding:9px 11px;color:var(--soft)}
.copy-btn{margin-top:10px;cursor:pointer;border:1px solid var(--border2);background:var(--card);
color:var(--muted);border-radius:var(--r-sm);padding:6px 14px;font:13px var(--font);text-decoration:none}
.copy-btn:hover{color:var(--text);border-color:var(--accent)}
.copy-btn.copied{background:var(--ok);color:#fff;border-color:var(--ok)}
.dcard-actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
.hashrow{display:flex;align-items:center;gap:var(--s2);flex-wrap:wrap}
.btn-link{margin-top:10px;border:1px solid var(--border2);background:var(--card);color:var(--muted);
border-radius:var(--r-sm);padding:6px 14px;font-size:13px}
.btn-link:hover{color:var(--text);border-color:var(--accent);text-decoration:none}
/* miner / block detail pages */
.back{display:inline-flex;align-items:center;gap:5px;color:var(--muted);font-size:13px;margin-bottom:var(--s3)}
.back:hover{color:var(--text);text-decoration:none}
.big-addr{font-family:var(--mono);color:var(--accent);word-break:break-all;font-size:15px;margin:0 0 var(--s4)}
td a,.cc-row a{color:var(--accent)}
/* responsive */
@media (max-width:760px){
nav{height:auto;flex-wrap:wrap;gap:8px 12px;padding:10px 14px;position:static}
.nav-links{order:3;width:100%}
.nav-stats .ns:not(:first-child){display:none} /* keep only hashrate; avoid wrap */
.wrap{padding:var(--s4) var(--s3) var(--s5)}
.hero{grid-template-columns:repeat(2,1fr)}
.kpi .val{font-size:22px}
}
@media (max-width:560px){
.nav-stats{display:none} /* phones: drop the strip entirely */
.connect,.dcards{grid-template-columns:1fr} /* 300-320px min would force page h-scroll */
.lookup input{min-width:0} /* let the search field shrink instead of overflowing */
}
@media (max-width:440px){.hero{grid-template-columns:1fr}}
"""
_THEME_TOGGLE = (
'<button class=theme-toggle id=theme-toggle type=button '
'title="Toggle light / dark" aria-label="Toggle theme">'
+ assets.icon("sun", "ico ico-sun") + assets.icon("moon", "ico ico-moon")
+ "</button>"
)
def _nav(links_html: str, right_html: str, brand_href: str = ".", stats_html: str = "") -> str:
"""Sticky top nav: brand lockup + section links + (coin-page) live stat strip +
theme toggle + status."""
return (
f'<nav><a class=brand href="{esc(brand_href)}">'
f'<span class=brand-mark aria-hidden="true">{assets.LOGO_SVG}</span>TestnetPool</a>'
f'<div class=nav-links>{links_html}</div>'
f'<div class=nav-right>{stats_html}{_THEME_TOGGLE}{right_html}</div></nav>'
)
def _nav_stats(snap) -> str:
"""Always-visible compact figures in the nav on coin pages (pool hashrate,
active miners, tip height), wired to the live-refresh mechanism."""
hr5 = (snap.get("pool_hashrate") or {}).get("5m") or snap.get("pool_hashrate_hs")
active = snap.get("active_miners")
if active is None:
active = snap.get("connected_miners")
height = snap.get("height")
items = [
("hashrate", "pool hashrate (5m)", fmt_hashrate(hr5), "pool_hashrate.5m", "hashrate"),
("miners", "active miners", str(active) if active is not None else "—", "active_miners", ""),
("height", "tip height", str(height) if height is not None else "—", "height", ""),
]
out = "".join(
f'<span class=ns title="{esc(ttl)}">{assets.icon(ic)}'
f'<b{_live_attrs(live, fmt)}>{esc(val)}</b></span>'
for ic, ttl, val, live, fmt in items)
return f'<span class=nav-stats aria-hidden="true">{out}</span>'
def _live(now_utc: str) -> str:
# The freshness ticker repaints every second; announcing it would spam screen