pingerplot 1.6.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.
pingerplot/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """PingerPlot — a continuous traceroute / latency monitor (MTR-style).
2
+
3
+ Zero third-party dependencies. IPv4. No administrator rights, raw sockets or
4
+ Npcap are required for ICMP: Windows uses the IP Helper API via ctypes, and
5
+ Linux/macOS use unprivileged SOCK_DGRAM ICMP sockets (see icmp_posix).
6
+ """
7
+
8
+ __version__ = "1.6.0"
pingerplot/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Entry point for ``python -m pingerplot`` — launches the GUI."""
2
+ from .launch import main
3
+
4
+ if __name__ == "__main__":
5
+ main()
pingerplot/appicon.py ADDED
@@ -0,0 +1,144 @@
1
+ """Procedurally-rendered application icon (pure standard library).
2
+
3
+ Replaces Tk's default feather in the title bar / taskbar with a themed mark:
4
+ "signal ripples" — concentric arcs radiating from a node, the universal cue for
5
+ ping / reachability — in the app's accent blue on a dark rounded tile.
6
+
7
+ It is drawn from math and encoded to a PNG in memory (a tiny stdlib PNG writer),
8
+ so there is no third-party dependency (no Pillow) and no binary asset committed
9
+ to the repo. The result is returned as base64 PNG text for
10
+ ``tkinter.PhotoImage(data=...)``. Edges are anti-aliased by supersampling and
11
+ correct (premultiplied) alpha downsampling, so the rounded corners and arcs stay
12
+ smooth at any title-bar size.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import base64
17
+ import math
18
+ import struct
19
+ import zlib
20
+
21
+ # palette (matches the GUI's dark theme accent)
22
+ _TILE = (26, 34, 46) # dark navy tile
23
+ _BORDER = (60, 74, 92) # subtle lighter rim
24
+ _ARC = (74, 163, 223) # accent blue (COLORS["line"])
25
+ _DOT = (152, 212, 255) # bright node
26
+
27
+ # Tray states: the same mark, greyed out when nothing is being monitored, and
28
+ # with a red badge while any target is alerting.
29
+ STATES = {
30
+ "normal": dict(arc=_ARC, dot=_DOT, badge=None),
31
+ "idle": dict(arc=(138, 148, 160), dot=(186, 192, 200), badge=None),
32
+ "alert": dict(arc=_ARC, dot=_DOT, badge=(232, 72, 72)),
33
+ }
34
+
35
+
36
+ def _in_round_rect(x: float, y: float, lo: float, hi: float, r: float) -> bool:
37
+ if x < lo or x > hi or y < lo or y > hi:
38
+ return False
39
+ cx = lo + r if x < lo + r else (hi - r if x > hi - r else None)
40
+ cy = lo + r if y < lo + r else (hi - r if y > hi - r else None)
41
+ if cx is not None and cy is not None:
42
+ return (x - cx) ** 2 + (y - cy) ** 2 <= r * r
43
+ return True
44
+
45
+
46
+ def _render(n: int = 64, ss: int = 3, arc=_ARC, dot=_DOT, badge=None) -> bytes:
47
+ """Return ``n*n`` RGBA bytes (top-to-bottom) for the icon, supersampled by
48
+ ``ss`` and downsampled with premultiplied alpha for clean anti-aliasing.
49
+ ``badge`` adds a status dot in the lower-right corner, ringed in the
50
+ tile's colour so it reads at 16 px."""
51
+ b = n * ss
52
+ bxc, byc, br = 0.76 * b, 0.76 * b, 0.20 * b # badge centre and radius
53
+ ring = 0.06 * b
54
+ x0, y0 = 0.30 * b, 0.74 * b # ripple origin (lower-left)
55
+ radii = ((0.21 * b, 255), (0.35 * b, 225), (0.49 * b, 185)) # (radius, alpha)
56
+ half_t = 0.038 * b # arc half-thickness
57
+ dot_r = 0.085 * b
58
+ corner = 0.16 * b
59
+ bw = 0.022 * b # rim width
60
+ lo, hi = 0.05 * b, b - 0.05 * b
61
+ qx, qy = -0.06 * b, 0.06 * b # keep arcs to the upper-right quadrant
62
+
63
+ pr = [0.0] * (n * n); pg = [0.0] * (n * n)
64
+ pb = [0.0] * (n * n); pa = [0.0] * (n * n)
65
+
66
+ for by in range(b):
67
+ row = (by // ss) * n
68
+ py = by + 0.5
69
+ for bx in range(b):
70
+ px = bx + 0.5
71
+ if not _in_round_rect(px, py, lo, hi, corner):
72
+ continue
73
+ if not _in_round_rect(px, py, lo + bw, hi - bw, corner - bw):
74
+ r, g, bl, a = _BORDER[0], _BORDER[1], _BORDER[2], 255
75
+ else:
76
+ r, g, bl, a = _TILE[0], _TILE[1], _TILE[2], 255
77
+ dx, dy = px - x0, py - y0
78
+ d = math.hypot(dx, dy)
79
+ if dx >= qx and dy <= qy:
80
+ for rr, aa in radii:
81
+ if abs(d - rr) <= half_t:
82
+ r, g, bl, a = arc[0], arc[1], arc[2], aa
83
+ break
84
+ if d <= dot_r:
85
+ r, g, bl, a = dot[0], dot[1], dot[2], 255
86
+ if badge is not None:
87
+ bd = math.hypot(px - bxc, py - byc)
88
+ if bd <= br:
89
+ r, g, bl, a = badge[0], badge[1], badge[2], 255
90
+ elif bd <= br + ring:
91
+ r, g, bl, a = _TILE[0], _TILE[1], _TILE[2], 255
92
+ idx = row + (bx // ss)
93
+ f = a / 255.0
94
+ pr[idx] += r * f; pg[idx] += g * f; pb[idx] += bl * f; pa[idx] += a
95
+
96
+ n2 = ss * ss
97
+ out = bytearray(n * n * 4)
98
+ for i in range(n * n):
99
+ a_sum = pa[i]
100
+ if a_sum <= 0:
101
+ continue # transparent (already zeroed)
102
+ j = i * 4
103
+ out[j] = min(255, int(pr[i] * 255 / a_sum + 0.5))
104
+ out[j + 1] = min(255, int(pg[i] * 255 / a_sum + 0.5))
105
+ out[j + 2] = min(255, int(pb[i] * 255 / a_sum + 0.5))
106
+ out[j + 3] = min(255, int(a_sum / n2 + 0.5))
107
+ return bytes(out)
108
+
109
+
110
+ def _png(rgba: bytes, w: int, h: int) -> bytes:
111
+ """Encode raw RGBA (8-bit, top-to-bottom) as a PNG. Stdlib only."""
112
+ def chunk(tag: bytes, data: bytes) -> bytes:
113
+ body = tag + data
114
+ return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF)
115
+
116
+ stride = w * 4
117
+ raw = bytearray()
118
+ for y in range(h):
119
+ raw.append(0) # filter type 0 (None) per scanline
120
+ raw.extend(rgba[y * stride:(y + 1) * stride])
121
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0) # 8-bit, colour type 6 (RGBA)
122
+ return (b"\x89PNG\r\n\x1a\n"
123
+ + chunk(b"IHDR", ihdr)
124
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9))
125
+ + chunk(b"IEND", b""))
126
+
127
+
128
+ def png_bytes(size: int = 64, state: str = "normal") -> bytes:
129
+ """The icon as PNG bytes; ``state`` is one of STATES (the tray's)."""
130
+ return _png(_render(size, **STATES[state]), size, size)
131
+
132
+
133
+ def png_base64(size: int = 64) -> str:
134
+ """The icon as base64 PNG text, for ``tkinter.PhotoImage(data=...)``."""
135
+ return base64.b64encode(png_bytes(size)).decode("ascii")
136
+
137
+
138
+ if __name__ == "__main__": # render a preview file: python -m pingerplot.appicon out.png
139
+ import sys
140
+ path = sys.argv[1] if len(sys.argv) > 1 else "appicon_preview.png"
141
+ size = int(sys.argv[2]) if len(sys.argv) > 2 else 256
142
+ with open(path, "wb") as fh:
143
+ fh.write(png_bytes(size))
144
+ print(f"wrote {path} ({size}x{size})")
pingerplot/compare.py ADDED
@@ -0,0 +1,257 @@
1
+ """Compare a live run (or a saved session) against an earlier one.
2
+
3
+ The tool could always tell you what a path looks like *now*. It could not tell
4
+ you whether that is different from last Tuesday — which is the question people
5
+ actually arrive with. "Is it slower since the circuit was cut over?" "Did the
6
+ firewall change make hop 4 start dropping?" You had two exports and an eyeball.
7
+
8
+ Hops are keyed by TTL, because that is the only stable identity a traceroute
9
+ has. A TTL whose responding address changed is *not* the same router, so its
10
+ latency delta is meaningless — it gets its own verdict rather than being
11
+ reported as a regression. Conflating those two would produce the most
12
+ misleading output this module could emit: "hop 4 got 80 ms slower" when hop 4
13
+ is simply a different box now.
14
+
15
+ Pure standard library, no Tk, so the same comparison drives the GUI dialog, the
16
+ headless report, and the tests.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from dataclasses import dataclass
21
+ from typing import Dict, List, Optional
22
+
23
+ from .model import Hop, hop_from_session, mos
24
+
25
+ # What counts as a real change rather than noise.
26
+ LOSS_DELTA_PTS = 5.0 # percentage points of packet loss
27
+ LATENCY_DELTA_PCT = 20.0 # relative latency change...
28
+ LATENCY_DELTA_MS = 5.0 # ...that must ALSO clear this, so 1.0 -> 1.3 ms is
29
+ # not reported as a 30% regression. Both must hold.
30
+ MOS_DELTA = 0.1 # MOS is shown to one decimal; a smaller move is noise
31
+
32
+ SAME = "same"
33
+ WORSE = "worse"
34
+ BETTER = "better"
35
+ REROUTED = "rerouted" # this TTL is a different router now
36
+ NEW = "new" # the path got longer; this TTL had no baseline
37
+ GONE = "gone" # the path got shorter; this TTL is no longer probed
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class HopStats:
42
+ """The subset of a hop's numbers a comparison needs."""
43
+
44
+ ttl: int
45
+ address: Optional[str]
46
+ hostname: Optional[str]
47
+ sent: int
48
+ loss_pct: float
49
+ avg: Optional[float]
50
+ jitter: Optional[float]
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class HopDelta:
55
+ ttl: int
56
+ verdict: str
57
+ base: Optional[HopStats]
58
+ now: Optional[HopStats]
59
+
60
+ @property
61
+ def d_avg(self) -> Optional[float]:
62
+ """Latency change in ms. None when either side has no measurement, or
63
+ when the TTL is a different router and the number would be nonsense."""
64
+ if self.verdict in (REROUTED, NEW, GONE):
65
+ return None
66
+ if self.base is None or self.now is None:
67
+ return None
68
+ if self.base.avg is None or self.now.avg is None:
69
+ return None
70
+ return self.now.avg - self.base.avg
71
+
72
+ @property
73
+ def d_loss(self) -> Optional[float]:
74
+ if self.verdict in (REROUTED, NEW, GONE):
75
+ return None
76
+ if self.base is None or self.now is None:
77
+ return None
78
+ return self.now.loss_pct - self.base.loss_pct
79
+
80
+ @property
81
+ def address(self) -> Optional[str]:
82
+ side = self.now or self.base
83
+ return side.address if side else None
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class Comparison:
88
+ target: str
89
+ rows: List[HopDelta]
90
+ base_hops: int
91
+ now_hops: int
92
+ base_mos: Optional[float]
93
+ now_mos: Optional[float]
94
+
95
+ @property
96
+ def route_changed(self) -> bool:
97
+ return self.base_hops != self.now_hops or any(
98
+ r.verdict in (REROUTED, NEW, GONE) for r in self.rows)
99
+
100
+ @property
101
+ def regressions(self) -> List[HopDelta]:
102
+ return [r for r in self.rows if r.verdict == WORSE]
103
+
104
+ @property
105
+ def improvements(self) -> List[HopDelta]:
106
+ return [r for r in self.rows if r.verdict == BETTER]
107
+
108
+ def summary(self) -> str:
109
+ """One line for a status bar or the top of a report."""
110
+ parts = []
111
+ if self.base_hops != self.now_hops:
112
+ parts.append(f"route {self.base_hops} -> {self.now_hops} hops")
113
+ rerouted = [r for r in self.rows if r.verdict == REROUTED]
114
+ if rerouted:
115
+ parts.append(f"{len(rerouted)} hop{'s' if len(rerouted) != 1 else ''} rerouted")
116
+ if self.regressions:
117
+ parts.append(f"{len(self.regressions)} worse")
118
+ if self.improvements:
119
+ parts.append(f"{len(self.improvements)} better")
120
+ # Only when it actually moved: "MOS 4.4 -> 4.4" is not information, and
121
+ # a summary that always has something in it stops being read.
122
+ if (self.base_mos is not None and self.now_mos is not None
123
+ and abs(self.now_mos - self.base_mos) >= MOS_DELTA):
124
+ parts.append(f"MOS {self.base_mos:.1f} -> {self.now_mos:.1f}")
125
+ return "; ".join(parts) if parts else "no significant change"
126
+
127
+
128
+ def stats_from_hop(hop: Hop) -> HopStats:
129
+ """Stats from a Hop the caller owns outright.
130
+
131
+ Safe for a hop rebuilt from a saved session, which nothing else touches.
132
+ NOT safe for a hop belonging to a running Monitor -- compute() iterates
133
+ hop.samples, and iterating a deque another thread is appending to raises
134
+ "deque mutated during iteration". Use stats_from_views(monitor.snapshot())
135
+ for anything live.
136
+ """
137
+ sent, _recv, loss, _cur, avg, _best, _worst, jitter = hop.compute()
138
+ return HopStats(hop.ttl, hop.address, hop.hostname, sent, loss, avg, jitter)
139
+
140
+
141
+ def stats_from_views(views) -> List[HopStats]:
142
+ """Stats from a Monitor.snapshot(), which is taken under the lock.
143
+
144
+ The safe way to summarise a monitor that is still probing, and the only
145
+ construction both the GUI's compare dialog and headless's --baseline use.
146
+ """
147
+ return [HopStats(v.ttl, v.address, v.hostname, v.sent, v.loss_pct,
148
+ v.avg, v.jitter) for v in views]
149
+
150
+
151
+ def stats_from_session(data: dict) -> List[HopStats]:
152
+ """Per-hop stats from a saved session dict (what Monitor.to_dict produces).
153
+
154
+ Rebuilds Hop objects and reuses compute(), rather than re-deriving the
155
+ statistics here, so a baseline and a live run can never be summarised by
156
+ two subtly different formulas.
157
+ """
158
+ if not isinstance(data, dict):
159
+ return []
160
+ hops = data.get("hops")
161
+ # The same parser as Load session, so a malformed entry is skipped by
162
+ # both rather than crashing one of them.
163
+ return [stats_from_hop(h) for h in map(hop_from_session, hops if isinstance(hops, list) else [])
164
+ if h is not None]
165
+
166
+
167
+ def _verdict(base: HopStats, now: HopStats) -> str:
168
+ if base.address and now.address and base.address != now.address:
169
+ return REROUTED
170
+ d_loss = now.loss_pct - base.loss_pct
171
+ if d_loss >= LOSS_DELTA_PTS:
172
+ return WORSE
173
+ if d_loss <= -LOSS_DELTA_PTS:
174
+ return BETTER
175
+ if base.avg is None or now.avg is None:
176
+ return SAME
177
+ d_ms = now.avg - base.avg
178
+ if abs(d_ms) < LATENCY_DELTA_MS:
179
+ return SAME
180
+ # Relative as well as absolute, so a 6 ms move on a 300 ms satellite path
181
+ # is not reported as a regression while the same 6 ms on a 2 ms LAN hop is.
182
+ if base.avg > 0 and abs(d_ms) / base.avg * 100.0 < LATENCY_DELTA_PCT:
183
+ return SAME
184
+ return WORSE if d_ms > 0 else BETTER
185
+
186
+
187
+ def compare(baseline: List[HopStats], current: List[HopStats],
188
+ target: str = "") -> Comparison:
189
+ """Diff two runs of the same path, hop by hop."""
190
+ by_ttl_base: Dict[int, HopStats] = {h.ttl: h for h in baseline}
191
+ by_ttl_now: Dict[int, HopStats] = {h.ttl: h for h in current}
192
+ rows: List[HopDelta] = []
193
+ for ttl in sorted(set(by_ttl_base) | set(by_ttl_now)):
194
+ b, n = by_ttl_base.get(ttl), by_ttl_now.get(ttl)
195
+ if b is None:
196
+ rows.append(HopDelta(ttl, NEW, None, n))
197
+ elif n is None:
198
+ rows.append(HopDelta(ttl, GONE, b, None))
199
+ else:
200
+ rows.append(HopDelta(ttl, _verdict(b, n), b, n))
201
+
202
+ def _dest_mos(hops: List[HopStats]) -> Optional[float]:
203
+ if not hops:
204
+ return None
205
+ d = hops[-1]
206
+ return mos(d.avg, d.jitter, d.loss_pct)
207
+
208
+ return Comparison(
209
+ target=target,
210
+ rows=rows,
211
+ base_hops=len(baseline),
212
+ now_hops=len(current),
213
+ base_mos=_dest_mos(baseline),
214
+ now_mos=_dest_mos(current),
215
+ )
216
+
217
+
218
+ def _fmt(v: Optional[float], places: int = 1, width: int = 7) -> str:
219
+ return f"{'-':>{width}}" if v is None else f"{v:>{width}.{places}f}"
220
+
221
+
222
+ def _fmt_delta(v: Optional[float], places: int = 1, width: int = 8) -> str:
223
+ """Signed, so the direction is readable at a glance in a wall of numbers."""
224
+ if v is None:
225
+ return f"{'':>{width}}"
226
+ return f"{v:>+{width}.{places}f}"
227
+
228
+
229
+ def format_comparison(cmp_: Comparison, baseline_label: str = "baseline") -> List[str]:
230
+ """A text table of the diff, for the console report or a ticket.
231
+
232
+ Deliberately ASCII-only. This goes to stdout, and a Windows console still
233
+ defaults to cp1252 or cp437, neither of which has a delta sign — printing
234
+ one raises UnicodeEncodeError and takes the whole report with it. The Tk
235
+ dialog renders the same data and can use the nicer glyphs, because Tk is
236
+ Unicode all the way down.
237
+ """
238
+ lines = [
239
+ "",
240
+ f"{cmp_.target or 'path'}: now vs {baseline_label}",
241
+ f" {cmp_.summary()}",
242
+ f" {'Hop':>3} {'Address':<16} {'Loss%':>7}{'+/-':>8} "
243
+ f"{'Avg ms':>7}{'+/-':>8} Verdict",
244
+ " " + "-" * 74,
245
+ ]
246
+ for r in cmp_.rows:
247
+ side = r.now or r.base
248
+ loss = side.loss_pct if side else None
249
+ avg = side.avg if side else None
250
+ note = r.verdict
251
+ if r.verdict == REROUTED and r.base and r.now:
252
+ note = f"rerouted {r.base.address} -> {r.now.address}"
253
+ lines.append(
254
+ f" {r.ttl:>3} {(r.address or '*'):<16} {_fmt(loss)}{_fmt_delta(r.d_loss)} "
255
+ f"{_fmt(avg)}{_fmt_delta(r.d_avg)} {note}"
256
+ )
257
+ return lines
pingerplot/ed25519.py ADDED
@@ -0,0 +1,145 @@
1
+ """Ed25519 (RFC 8032), pure Python: verification for the updater, and signing
2
+ for the release build.
3
+
4
+ The updater needs one operation, checking a release manifest's signature
5
+ against the public key built into the app; doing it here keeps the app free of
6
+ a compiled crypto dependency. Verification handles only public data, so timing
7
+ side channels don't apply to it.
8
+
9
+ Signing is here too, so that building a release needs nothing beyond the
10
+ standard library either (UniFi Stock Watcher signs with the ``cryptography``
11
+ package; this project's release job installs only hash-pinned build tools).
12
+ Hand-written signing code is usually avoided because Python's big-integer
13
+ arithmetic isn't constant-time; that matters when an attacker can time many
14
+ signatures. A release is signed once, by a CI job on a throwaway machine or on
15
+ the maintainer's PC, so nobody can. The implementation is checked against the
16
+ RFC's test vectors and against ``cryptography`` (tests/test_updater.py).
17
+
18
+ Strict where the RFC is: a non-canonical S (>= L) or a point that does not
19
+ decode is a failed verification, not an exception.
20
+
21
+ Verification adapted from UniFi Stock Watcher, a sibling project.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import hashlib
26
+
27
+ __all__ = ["verify", "sign", "public_key"]
28
+
29
+ _P = 2 ** 255 - 19
30
+ _L = 2 ** 252 + 27742317777372353535851937790883648493
31
+ _D = -121665 * pow(121666, _P - 2, _P) % _P
32
+ _SQRT_M1 = pow(2, (_P - 1) // 4, _P)
33
+
34
+
35
+ def _recover_x(y, sign):
36
+ if y >= _P:
37
+ return None
38
+ x2 = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P) % _P
39
+ if x2 == 0:
40
+ return None if sign else 0
41
+ x = pow(x2, (_P + 3) // 8, _P)
42
+ if (x * x - x2) % _P:
43
+ x = x * _SQRT_M1 % _P
44
+ if (x * x - x2) % _P:
45
+ return None
46
+ if (x & 1) != sign:
47
+ x = _P - x
48
+ return x
49
+
50
+
51
+ # Points in extended homogeneous coordinates (X, Y, Z, T): x = X/Z, y = Y/Z,
52
+ # x*y = T/Z.
53
+
54
+ def _add(p, q):
55
+ a = (p[1] - p[0]) * (q[1] - q[0]) % _P
56
+ b = (p[1] + p[0]) * (q[1] + q[0]) % _P
57
+ c = 2 * p[3] * q[3] * _D % _P
58
+ d = 2 * p[2] * q[2] % _P
59
+ e, f, g, h = b - a, d - c, d + c, b + a
60
+ return (e * f % _P, g * h % _P, f * g % _P, e * h % _P)
61
+
62
+
63
+ def _mul(s, p):
64
+ q = (0, 1, 1, 0) # neutral element
65
+ while s:
66
+ if s & 1:
67
+ q = _add(q, p)
68
+ p = _add(p, p)
69
+ s >>= 1
70
+ return q
71
+
72
+
73
+ def _equal(p, q):
74
+ return ((p[0] * q[2] - q[0] * p[2]) % _P == 0
75
+ and (p[1] * q[2] - q[1] * p[2]) % _P == 0)
76
+
77
+
78
+ def _compress(p):
79
+ zinv = pow(p[2], _P - 2, _P)
80
+ x, y = p[0] * zinv % _P, p[1] * zinv % _P
81
+ return int.to_bytes(y | ((x & 1) << 255), 32, "little")
82
+
83
+
84
+ def _decompress(b):
85
+ if len(b) != 32:
86
+ return None
87
+ y = int.from_bytes(b, "little")
88
+ sign = y >> 255
89
+ y &= (1 << 255) - 1
90
+ x = _recover_x(y, sign)
91
+ if x is None:
92
+ return None
93
+ return (x, y, 1, x * y % _P)
94
+
95
+
96
+ _GY = 4 * pow(5, _P - 2, _P) % _P
97
+ _GX = _recover_x(_GY, 0)
98
+ _G = (_GX, _GY, 1, _GX * _GY % _P)
99
+
100
+
101
+ def _expand(seed: bytes):
102
+ if not (isinstance(seed, (bytes, bytearray)) and len(seed) == 32):
103
+ raise ValueError("an Ed25519 private key is 32 bytes")
104
+ h = hashlib.sha512(bytes(seed)).digest()
105
+ a = int.from_bytes(h[:32], "little")
106
+ a &= (1 << 254) - 8 # clear the low 3 bits and the top bit
107
+ a |= 1 << 254 # set bit 254
108
+ return a, h[32:]
109
+
110
+
111
+ def public_key(seed: bytes) -> bytes:
112
+ """The 32-byte public key for a 32-byte private key (seed)."""
113
+ a, _prefix = _expand(seed)
114
+ return _compress(_mul(a, _G))
115
+
116
+
117
+ def sign(seed: bytes, message: bytes) -> bytes:
118
+ """The 64-byte Ed25519 signature of ``message`` (RFC 8032, 5.1.6)."""
119
+ a, prefix = _expand(seed)
120
+ pub = _compress(_mul(a, _G))
121
+ r = int.from_bytes(hashlib.sha512(prefix + bytes(message)).digest(), "little") % _L
122
+ big_r = _compress(_mul(r, _G))
123
+ h = int.from_bytes(hashlib.sha512(big_r + pub + bytes(message)).digest(), "little") % _L
124
+ s = (r + h * a) % _L
125
+ return big_r + int.to_bytes(s, 32, "little")
126
+
127
+
128
+ def verify(public_key: bytes, message: bytes, signature: bytes) -> bool:
129
+ """True if ``signature`` is a valid Ed25519 signature of ``message``."""
130
+ if not (isinstance(public_key, (bytes, bytearray)) and len(public_key) == 32):
131
+ return False
132
+ if not (isinstance(signature, (bytes, bytearray)) and len(signature) == 64):
133
+ return False
134
+ a = _decompress(bytes(public_key))
135
+ r_bytes = bytes(signature[:32])
136
+ r = _decompress(r_bytes)
137
+ if a is None or r is None:
138
+ return False
139
+ s = int.from_bytes(signature[32:], "little")
140
+ if s >= _L:
141
+ return False
142
+ h = int.from_bytes(
143
+ hashlib.sha512(r_bytes + bytes(public_key) + bytes(message)).digest(),
144
+ "little") % _L
145
+ return _equal(_mul(s, _G), _add(r, _mul(h, a)))