Spaces:
Paused
Paused
Fix Play: Gradio Plot drops Plotly frames; drive playback server-side with gr.Timer
ca3826f verified Download app.py from Optitransfer/trusted-swarms: direct link, hf CLI and curl.
- Browser
- Download file 26.3 kB
-
https://huggingface.co/spaces/Optitransfer/trusted-swarms/resolve/main/app.py
- Command line
-
hf download hf://spaces/Optitransfer/trusted-swarms/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Optitransfer/trusted-swarms/resolve/main/app.py
26.3 kB
| # SPDX-License-Identifier: BUSL-1.1 | |
| # Copyright 2026 Ryan Gillespie / Optitransfer | |
| """Trusted Swarms: leaderless shared mission state for unmanned swarms. Gradio UI; every number in section 3 is | |
| produced live by swarm.py on each run. Side-by-side animated comparison: WITH trusted solution vs WITHOUT (leader-based).""" | |
| import json, tempfile | |
| import gradio as gr | |
| import numpy as np | |
| import plotly.graph_objects as go | |
| from plotly.subplots import make_subplots | |
| import swarm as S | |
| REPO = "https://github.com/mgillr/trusted-swarms" | |
| CRDT = "https://pypi.org/project/crdt-merge/" | |
| ACFA = "https://github.com/mgillr/acfa-rs" | |
| CSS = """ | |
| .sec h2 {border-left: 6px solid #1f6feb; padding-left: 10px;} | |
| .kpi {font-size: 1.05em} | |
| .compare-note {background: #f0f6ff; border: 1px solid #c8d9f5; border-radius: 10px; padding: 10px 14px; margin: 6px 0 12px 0;} | |
| footer {visibility: hidden} | |
| """ | |
| HEADER = f""" | |
| # Trusted Swarms | |
| ### A shared mission picture for drone and robot swarms, with no leader to lose and no member able to poison it. | |
| This page goes in order: **(1)** how swarm trust works today, **(2)** the problem, **(3)** the solution running live, | |
| **(4)** the venture, **(5)** the potential, **(6)** the markets. | |
| > **Read this first.** Section 3 is a **software simulation** that runs on this server. It uses the real engine | |
| > ([crdt-merge]({CRDT}) for the shared state and its E4 trust layer for dropping bad members), with Ed25519 signatures. | |
| > There are **no real drones, radios or autopilots** here. Hardware is a later milestone. Everything else on this page | |
| > marked *measured* comes from my own runs, which nobody has independently re-run yet. | |
| """ | |
| S1 = """ | |
| ## 1 · How swarm trust works today | |
| Most swarms in service or in trials today rely on **one point that everyone trusts**: | |
| - a **lead drone** that collects what the others see and tells them what to do, or | |
| - a **ground control station** that every drone reports to. | |
| The swarm's *shared picture* (where the target is, which areas are clear, who's doing what) lives in that one place. | |
| The other members trust it because they have to: they usually can't check it themselves. | |
| """ | |
| S2 = """ | |
| ## 2 · The problem | |
| That single point of trust fails in three ways: | |
| | What happens | What the swarm loses | | |
| |---|---| | |
| | **The leader is lost** (shot down, jammed, out of range, battery) | The shared picture. Members fall back to acting alone, or stop. | | |
| | **One member is captured or faulty** and sends false reports | The leader averages the lie into everyone's picture. One bad member skews the whole swarm. | | |
| | **A member tells different peers different things** | Peers end up with different pictures and can't tell who lied. | | |
| Adding more drones doesn't fix it. More members means more chances that one of them is compromised, and the leader is | |
| still a single target. | |
| """ | |
| S3_INTRO = """ | |
| ## 3 · The solution, running live | |
| Every drone keeps **its own copy** of the shared mission picture. Copies are merged peer to peer, with no leader, in any order | |
| and with lost messages. The merge rules guarantee that everyone who has heard the same reports ends up with the | |
| **identical** picture, bit for bit. Every report is **signed**, so a drone can't speak for another. A drone that lies is caught by | |
| evidence every honest drone can check for itself, then **dropped automatically**. The rest keep going, and each round | |
| ends with a **receipt** that a quorum of drones co-signs and anyone can check afterwards. | |
| **Watch the mission.** Press **Run mission**, then hit **▶ Play** above the animation. Left = **WITH** Trusted Swarms (converges, attackers dropped). Right = **WITHOUT** — leader-based (poisoned picture, then blank when the leader is lost). | |
| """ | |
| S4 = f""" | |
| ## 4 · The venture | |
| **Trusted Swarms** is a venture we're exploring: this engine as the trust layer inside unmanned swarm systems. | |
| - **Where it stands.** The core works in software and has formal proofs behind its merge and quorum rules. It hasn't run on drones yet. | |
| - **The next step is a design partner**: an operator, integrator or OEM with a real swarm and a real mission, so we can prove it on their systems. | |
| - **The proposed path,** where each step is done only when its evidence contract passes: | |
| 1. **Align**: roles, scope, IP approach, first export-control check. | |
| 2. **Captured-drone simulation**: a bad drone is dropped and the swarm continues, re-run independently. | |
| 3. **Design partner or pilot agreed.** | |
| 4. **Hardware**: radio mesh and autopilot integration on 5 to 10 drones. | |
| 5. **First paid or sponsored pilot.** | |
| 6. **Scale** beyond what has been measured, over radio-style links. | |
| - **Lean by design.** Nothing gets spent or hired until it's needed to unblock the next step. | |
| **Are you a design partner?** If you operate or build swarms and this problem is yours, the plan is in the [repository]({REPO}) (private, ask for access). | |
| """ | |
| S5 = """ | |
| ## 5 · The potential | |
| **Measured so far** (my own runs; independent re-runs come at step 2): | |
| | Measured | Result | | |
| |---|---| | |
| | Same result on different chips | Identical on **ARM** and **x86** | | |
| | Conflicting reports from one member | Convicted in about **0.2 s** | | |
| | Lost messages | Still agrees with **30%** of messages lost | | |
| | Network split | Heals in **under a second** | | |
| | 100-member software run with attackers | Correct decisions, **2 of 2** attackers convicted, **0** honest members wrongly convicted | | |
| | Formal proofs (engine core) | **46** Lean proofs, **none** unfinished | | |
| **Honest limits today:** it works well at **tens** of members and was correct at 100. It strains from around **200** and doesn't | |
| reach agreement at **500**. Messages currently go through a relay server, not radio-to-radio. It needs an **honest majority** | |
| and can't catch a member that lies *consistently and plausibly* without other sensors to cross-check. There's one known bug, | |
| with the fix identified: an honest member that sends twice in a round can be wrongly convicted. | |
| **What it could become (goals, not results):** a trust layer any swarm can adopt, whatever the airframe, autopilot or radio, | |
| so that mixed fleets from different vendors can share one picture they all trust. | |
| """ | |
| S6 = """ | |
| ## 6 · The markets | |
| Wherever many unmanned systems have to agree on one picture without a single point of trust: | |
| | Market | What a shared, unpoisonable picture gives | | |
| |---|---| | |
| | **ISR** (surveillance and reconnaissance) | One picture of the area that survives losing any drone, and can't be skewed by a captured one | | |
| | **Counter-drone** | Interceptor and sensor swarms that agree on track data even while under attack | | |
| | **Search and rescue** | Searched-or-clear area maps that stay consistent when drones drop out or links fail | | |
| | **Infrastructure inspection** (power lines, pipelines, rail, wind) | Fleets that split up the work and keep a verifiable record of what was inspected | | |
| | **Ground and maritime robotics** | The same engine for UGVs, USVs and mixed fleets, in ports, at sea, in mines and logistics yards | | |
| Defence is the clearest example because the attacker is real. The same need appears wherever a fleet must keep working | |
| when members fail or can't be trusted. These are the markets we're targeting; none is a signed customer yet. | |
| """ | |
| FOOT = f""" | |
| --- | |
| Simulation only, with throwaway keys made at runtime and no secrets. Engine: [crdt-merge]({CRDT}) (shared state and E4 trust). | |
| The receipt format follows the same idea as [acfa-rs]({ACFA}), simplified here. | |
| © 2026 Ryan Gillespie / Optitransfer. BUSL-1.1. | |
| """ | |
| COL = {"honest": "#2a9d55", "poisoner": "#d62828", "equivocator": "#f77f00", "impersonator": "#9d4edd"} | |
| ROLE_MARK = {"honest": "triangle-up", "poisoner": "diamond", "equivocator": "diamond", "impersonator": "diamond"} | |
| def _patrol(pos0, rnd, i): | |
| """Display-only patrol offset so drones drift over rounds (does not affect the simulation).""" | |
| ang = 0.35 * rnd + 0.7 * i | |
| return pos0 + np.array([18 * np.cos(ang), 18 * np.sin(ang)]) | |
| def _story(sw): | |
| rs = sw.rounds | |
| attackers = {d.id for d in sw.drones if d.role != "honest"} | |
| first = {} | |
| for e in sw.evidence: | |
| if e["who"] in attackers: | |
| first.setdefault(e["who"], e["round"]) | |
| lost = next((r["round"] for r in rs if r["lead_pic"] is None), None) | |
| te = [r["trusted_err"] for r in rs if r["trusted_err"] is not None] | |
| le = [r["lead_err"] for r in rs if r["lead_err"] is not None] | |
| lines = [ | |
| "### Mission story (press **Play** on the animation)", | |
| "", | |
| f"- **Left — WITH Trusted Swarms:** shared picture stays on the true track" | |
| + (f" (avg error **{np.mean(te):.1f} m**)" if te else "") | |
| + ". Attackers are **dropped** and stop poisoning.", | |
| f"- **Right — WITHOUT (leader-based):** the leader averages in the lies" | |
| + (f" (avg error **{np.mean(le):.1f} m** while alive)" if le else "") | |
| + (f", then the picture **goes blank** when D00 is lost in round {lost}." if lost else "."), | |
| ] | |
| if first: | |
| caught = ", ".join(f"{k} in round {v}" for k, v in sorted(first.items())) | |
| lines.append(f"- **Attackers caught:** {caught}.") | |
| lines.append( | |
| "- ★ black = true target · blue trail = trusted picture · red dashed = leader picture · " | |
| "✕ / grey = dropped or lost." | |
| ) | |
| return "\n".join(lines) | |
| def _axis_range(sw): | |
| pts = [np.array(r["target"]) for r in sw.rounds] | |
| for d in sw.drones: | |
| pts.append(d.pos) | |
| for r in sw.rounds: | |
| if r["receipt"] and r["receipt"].get("fused"): | |
| pts.append(np.array(r["receipt"]["fused"])) | |
| if r["lead_pic"] is not None: | |
| pts.append(np.array(r["lead_pic"])) | |
| a = np.stack(pts) | |
| pad = 80 | |
| return [float(a[:, 0].min() - pad), float(a[:, 0].max() + pad)], [float(a[:, 1].min() - pad), float(a[:, 1].max() + pad)] | |
| def _drone_traces(sw, rnd_idx, side): | |
| """Build drone marker traces for one panel at a given round index (0-based).""" | |
| r = sw.rounds[rnd_idx] | |
| quar = set(r["quarantined"]) | |
| traces = [] | |
| lead_lost = r["lead_pic"] is None | |
| for i, d in enumerate(sw.drones): | |
| pos = _patrol(d.pos, r["round"], i) | |
| if side == "trusted": | |
| if not d.alive: | |
| st, color, sym, size = "lost", "#999", "x-thin-open", 12 | |
| elif d.id in quar: | |
| st, color, sym, size = "dropped", "#555", "circle-x", 13 | |
| else: | |
| st, color, sym, size = "flying", COL[d.role], ROLE_MARK[d.role], 14 | |
| else: | |
| # Leader-based: attackers stay "in" and keep poisoning until the leader is gone | |
| if d.id == "D00" and lead_lost: | |
| st, color, sym, size = "leader lost", "#999", "x-thin-open", 14 | |
| elif not d.alive and d.id == "D00": | |
| st, color, sym, size = "leader lost", "#999", "x-thin-open", 14 | |
| elif lead_lost: | |
| st, color, sym, size = "no picture", "#bbb", "circle-open", 10 | |
| else: | |
| st, color, sym, size = ("poisoning" if d.role != "honest" else "reporting"), COL[d.role], ROLE_MARK[d.role], 14 | |
| traces.append(go.Scatter( | |
| x=[float(pos[0])], y=[float(pos[1])], mode="markers+text", | |
| text=[d.id], textposition="top center", textfont=dict(size=9), | |
| name=d.id, showlegend=False, | |
| hovertext=f"{d.id} · {d.role} · {st}", hoverinfo="text", | |
| marker=dict(size=size, symbol=sym, color=color, line=dict(width=1, color="#222")), | |
| )) | |
| return traces | |
| def _frame_traces(sw, upto): | |
| """Traces for both panels after `upto` rounds have completed (1..N).""" | |
| rs = sw.rounds[:upto] | |
| last = rs[-1] | |
| xr, yr = _axis_range(sw) | |
| # True target track (both sides) | |
| tgt = np.array([r["target"] for r in rs]) | |
| true_l = go.Scatter(x=tgt[:, 0], y=tgt[:, 1], mode="lines+markers", name="True target", | |
| line=dict(color="#111", width=2), marker=dict(symbol="star", size=10, color="#111"), | |
| legendgroup="true", showlegend=True) | |
| true_r = go.Scatter(x=tgt[:, 0], y=tgt[:, 1], mode="lines+markers", name="True target", | |
| line=dict(color="#111", width=2), marker=dict(symbol="star", size=10, color="#111"), | |
| legendgroup="true", showlegend=False) | |
| # Trusted fused trail | |
| fused = [(r["round"], r["receipt"]["fused"]) for r in rs if r["accepted"] and r["receipt"] and r["receipt"].get("fused")] | |
| if fused: | |
| fa = np.array([p for _, p in fused]) | |
| trust_tr = go.Scatter(x=fa[:, 0], y=fa[:, 1], mode="lines+markers", name="Trusted picture", | |
| line=dict(color="#1f6feb", width=3), marker=dict(size=8, color="#1f6feb"), | |
| legendgroup="trust", showlegend=True) | |
| else: | |
| trust_tr = go.Scatter(x=[], y=[], mode="lines", name="Trusted picture", line=dict(color="#1f6feb"), | |
| legendgroup="trust", showlegend=True) | |
| # Leader trail | |
| lead = [(r["round"], r["lead_pic"]) for r in rs if r["lead_pic"] is not None] | |
| if lead: | |
| la = np.array([p for _, p in lead]) | |
| lead_tr = go.Scatter(x=la[:, 0], y=la[:, 1], mode="lines+markers", name="Leader picture", | |
| line=dict(color="#d62828", width=2.5, dash="dash"), | |
| marker=dict(symbol="x", size=9, color="#d62828"), | |
| legendgroup="lead", showlegend=True) | |
| else: | |
| lead_tr = go.Scatter(x=[], y=[], mode="lines", name="Leader picture", | |
| line=dict(color="#d62828", dash="dash"), legendgroup="lead", showlegend=True) | |
| # Status annotations as invisible hover anchors + title text via layout | |
| te = last["trusted_err"] | |
| le = last["lead_err"] | |
| n_drop = len(last["quarantined"]) | |
| left_note = f"Round {last['round']} · error {te:.1f} m · attackers dropped: {n_drop}" if te is not None else f"Round {last['round']} · no picture" | |
| if le is not None: | |
| right_note = f"Round {last['round']} · error {le:.1f} m · attackers still in · picture poisoned" | |
| else: | |
| right_note = f"Round {last['round']} · NO PICTURE · leader lost" | |
| drones_l = _drone_traces(sw, upto - 1, "trusted") | |
| drones_r = _drone_traces(sw, upto - 1, "leader") | |
| # annotation markers (corners) carrying status text via hover | |
| note_l = go.Scatter(x=[xr[0] + 5], y=[yr[1] - 5], mode="text", text=[left_note], | |
| textposition="bottom right", textfont=dict(size=11, color="#1f6feb", family="Arial"), | |
| showlegend=False, hoverinfo="skip") | |
| note_r = go.Scatter(x=[xr[0] + 5], y=[yr[1] - 5], mode="text", text=[right_note], | |
| textposition="bottom right", textfont=dict(size=11, color="#d62828", family="Arial"), | |
| showlegend=False, hoverinfo="skip") | |
| left = [true_l, trust_tr, note_l] + drones_l | |
| right = [true_r, lead_tr, note_r] + drones_r | |
| return left, right, left_note, right_note | |
| def _anim_compare(sw, upto=None): | |
| """Side-by-side mission at round `upto` (1..N): WITH trusted vs WITHOUT leader-based. | |
| Gradio's Plot component drops Plotly `frames`, so playback is driven server-side by gr.Timer.""" | |
| n_rounds = len(sw.rounds) | |
| upto = n_rounds if upto is None else max(1, min(int(upto), n_rounds)) | |
| xr, yr = _axis_range(sw) | |
| fig = make_subplots( | |
| rows=1, cols=2, shared_xaxes=False, shared_yaxes=True, | |
| subplot_titles=( | |
| "WITH Trusted Swarms — converges, attackers dropped", | |
| "WITHOUT — leader-based — poisoned, then blank", | |
| ), | |
| horizontal_spacing=0.06, | |
| ) | |
| left, right, _, _ = _frame_traces(sw, upto) | |
| for tr in left: | |
| fig.add_trace(tr, row=1, col=1) | |
| for tr in right: | |
| fig.add_trace(tr, row=1, col=2) | |
| fig.update_layout( | |
| title=dict(text=f"Mission · round {upto} of {n_rounds}", x=0.02, xanchor="left"), | |
| height=560, margin=dict(l=40, r=20, t=90, b=40), | |
| template="plotly_white", | |
| legend=dict(orientation="h", y=1.12, x=0), | |
| uirevision="mission", | |
| ) | |
| fig.update_xaxes(title_text="metres east", range=xr, row=1, col=1) | |
| fig.update_xaxes(title_text="metres east", range=xr, row=1, col=2) | |
| fig.update_yaxes(title_text="metres north", range=yr, scaleanchor="x", scaleratio=1, row=1, col=1) | |
| fig.update_yaxes(range=yr, scaleanchor="x2", scaleratio=1, row=1, col=2) | |
| for ann in fig.layout.annotations: | |
| if "WITHOUT" in (ann.text or ""): | |
| ann.font = dict(size=13, color="#d62828") | |
| elif "WITH" in (ann.text or ""): | |
| ann.font = dict(size=13, color="#1f6feb") | |
| return fig | |
| def _err_anim(sw, upto=None): | |
| """Error bars built up to round `upto`.""" | |
| n_rounds = len(sw.rounds) | |
| upto = n_rounds if upto is None else max(1, min(int(upto), n_rounds)) | |
| xs = [r["round"] for r in sw.rounds] | |
| te = [r["trusted_err"] if r["trusted_err"] is not None else 0 for r in sw.rounds] | |
| le = [r["lead_err"] if r["lead_err"] is not None else 0 for r in sw.rounds] | |
| lead_miss = [r["lead_err"] is None for r in sw.rounds] | |
| te_v = te[:upto] + [0] * (n_rounds - upto) | |
| le_v = le[:upto] + [0] * (n_rounds - upto) | |
| texts = ["leader lost" if (i < upto and lead_miss[i]) else "" for i in range(n_rounds)] | |
| ymax = max(te + le + [1]) * 1.2 | |
| fig = go.Figure(data=[ | |
| go.Bar(x=xs, y=te_v, name="Trusted (WITH)", marker_color="#1f6feb"), | |
| go.Bar(x=xs, y=le_v, name="Leader-based (WITHOUT)", marker_color="#d62828", | |
| text=texts, textposition="outside"), | |
| ]) | |
| fig.update_layout( | |
| barmode="group", | |
| title=f"Error from truth, rounds 1–{upto} (metres; lower is better)", | |
| height=340, margin=dict(l=40, r=20, t=60, b=40), template="plotly_white", | |
| xaxis=dict(title="round", dtick=1, range=[0.5, n_rounds + 0.5]), | |
| yaxis=dict(title="error (m)", range=[0, ymax]), | |
| legend=dict(orientation="h", y=-0.22), | |
| uirevision="err", | |
| ) | |
| return fig | |
| def _render(sw, rnd): | |
| if sw is None: | |
| return gr.update(), gr.update() | |
| return _anim_compare(sw, rnd), _err_anim(sw, rnd) | |
| def play(sw, rnd): | |
| if sw is None: | |
| return gr.update(), gr.update(), gr.update(), gr.Timer(active=False) | |
| n_rounds = len(sw.rounds) | |
| rnd = int(rnd or 1) | |
| if rnd >= n_rounds: # at the end: start over | |
| rnd = 1 | |
| a, e = _render(sw, rnd) | |
| return a, e, gr.update(value=rnd, maximum=n_rounds), gr.Timer(active=True) | |
| def tick(sw, rnd): | |
| if sw is None: | |
| return gr.update(), gr.update(), gr.update(), gr.Timer(active=False) | |
| n_rounds = len(sw.rounds) | |
| rnd = min(int(rnd or 0) + 1, n_rounds) | |
| a, e = _render(sw, rnd) | |
| return a, e, gr.update(value=rnd), gr.Timer(active=rnd < n_rounds) | |
| def pause(): | |
| return gr.Timer(active=False) | |
| def restart(sw): | |
| if sw is None: | |
| return gr.update(), gr.update(), gr.update(), gr.Timer(active=False) | |
| a, e = _render(sw, 1) | |
| return a, e, gr.update(value=1), gr.Timer(active=False) | |
| def scrub(sw, rnd): | |
| a, e = _render(sw, rnd) | |
| return a, e, gr.Timer(active=False) | |
| def _kpis(sw, n, att): | |
| rs = sw.rounds; acc = sum(r["accepted"] for r in rs) | |
| te = [r["trusted_err"] for r in rs if r["trusted_err"] is not None] | |
| le = [r["lead_err"] for r in rs if r["lead_err"] is not None] | |
| lost_lead = sum(r["lead_pic"] is None for r in rs) | |
| attackers = {d.id for d in sw.drones if d.role != "honest"} | |
| quar = sw.quarantined(); wrong = quar - attackers | |
| first = {} | |
| for e in sw.evidence: | |
| first.setdefault(e["who"], e["round"]) | |
| split = max(max(r["net"]["distinct_views"]) for r in rs) | |
| msgs = sum(r["net"]["sent"] for r in rs); lost = sum(r["net"]["lost"] for r in rs) | |
| return f""" | |
| ### What this run just measured | |
| | | Trusted swarm (WITH) | Leader-based (WITHOUT) | | |
| |---|---|---| | |
| | Rounds with a usable shared picture | **{acc} / {len(rs)}** | **{len(rs) - lost_lead} / {len(rs)}** | | |
| | Average error from the true target | {f"**{np.mean(te):.1f} m**" if te else "n/a"} | {f"**{np.mean(le):.1f} m**" if le else "n/a"} | | |
| - **Attackers in the swarm:** {len(attackers)} of {n} ({", ".join(sorted(f"{d.id} = {d.role}" for d in sw.drones if d.role != "honest")) or "none"}). | |
| - **Dropped by every honest drone:** {len(quar & attackers)} of {len(attackers)} attackers{" (first caught: " + ", ".join(f"{k} in round {v}" for k, v in sorted(first.items()) if k in attackers) + ")" if first else ""}. **Honest drones wrongly dropped: {len(wrong)}.** | |
| - **Identical picture on every honest drone:** {"yes, every round (same state hash)" if all(r["net"]["converged"] for r in rs) else "not in every round"}. Up to {split} different views existed mid-gossip before they merged. | |
| - **Network:** {msgs} messages sent, {lost} lost on purpose ({lost / max(msgs,1):.0%}), random order, no leader, no server. | |
| - **Receipts:** {acc} rounds co-signed by a quorum (2Q > n + f, so two different receipts can't both be accepted). Only one receipt per round was ever produced: {"yes" if all(r["distinct_receipts"] == 1 for r in rs) else "no"}. | |
| """ | |
| def run(n, poisoner, equivocator, impersonator, loss, lose_lead, rounds, seed): | |
| att = tuple(a for a, on in (("poisoner", poisoner), ("equivocator", equivocator), ("impersonator", impersonator)) if on) | |
| n = int(n) | |
| if len(att) * 3 >= n: | |
| raise gr.Error("Too many attackers for this swarm size: it needs fewer than a third bad. That's a real limit, not a demo limit.") | |
| sw = S.Swarm(n=n, attackers=att, loss=float(loss) / 100, lose_lead_at=int(lose_lead) if lose_lead else 0, seed=int(seed)) | |
| for _ in range(int(rounds)): sw.step() | |
| log = "\n".join(e for r in sw.rounds for e in r["events"]) or "No incidents: every drone behaved." | |
| last = sw.rounds[-1] | |
| rec = {"receipt": last["receipt"], "receipt_hash": last["receipt_hash"], "quorum": last["quorum"], | |
| "cosigners": last["cosigners"], "cosignatures": last["cosignatures"], "public_keys": sw.pki} | |
| path = tempfile.NamedTemporaryFile("w", suffix="-receipt.json", delete=False).name | |
| json.dump(rec, open(path, "w"), indent=2) | |
| nr = len(sw.rounds) | |
| return (_story(sw), _kpis(sw, n, att), _anim_compare(sw, nr), _err_anim(sw, nr), sw.trust_table(), log, rec, path, sw, | |
| "Receipt not yet checked. Press **Verify the last receipt**.", | |
| gr.update(value=nr, maximum=nr), gr.Timer(active=False)) | |
| def verify(sw): | |
| if sw is None: return "Run a mission first." | |
| ok, lines = S.verify_receipt(sw, sw.rounds[-1]) | |
| return ("### ✅ Receipt verified\n" if ok else "### ❌ Receipt failed\n") + "\n".join(f"- {l}" for l in lines) + \ | |
| "\n\nThis check uses only the receipt, the co-signatures and the public keys pinned before launch. You don't have to trust any one drone." | |
| with gr.Blocks(title="Trusted Swarms: leaderless, poison-proof shared mission state", css=CSS, theme=gr.themes.Soft()) as demo: | |
| gr.Markdown(HEADER) | |
| with gr.Column(elem_classes="sec"): | |
| gr.Markdown(S1); gr.Markdown(S2); gr.Markdown(S3_INTRO) | |
| with gr.Row(): | |
| with gr.Column(scale=1, min_width=260): | |
| n = gr.Slider(6, 40, value=12, step=1, label="Drones in the swarm") | |
| p = gr.Checkbox(True, label="Poisoner: a captured drone sends signed but false target reports") | |
| e = gr.Checkbox(True, label="Equivocator: tells half the swarm one thing and the other half another") | |
| i = gr.Checkbox(True, label="Impersonator: forges reports in another drone's name") | |
| loss = gr.Slider(0, 40, value=25, step=5, label="Messages lost in the network (%)") | |
| ll = gr.Slider(0, 8, value=3, step=1, label="Round the lead drone D00 is lost (0 = never)") | |
| rounds = gr.Slider(3, 12, value=8, step=1, label="Mission rounds") | |
| seed = gr.Number(7, label="Random seed", precision=0) | |
| go_btn = gr.Button("Run mission", variant="primary") | |
| with gr.Column(scale=3): | |
| story = gr.Markdown() | |
| kpis = gr.Markdown() | |
| with gr.Row(equal_height=True): | |
| play_btn = gr.Button("▶ Play", variant="primary", scale=1, min_width=100) | |
| pause_btn = gr.Button("⏸ Pause", scale=1, min_width=100) | |
| restart_btn = gr.Button("⟲ Restart", scale=1, min_width=100) | |
| rnd = gr.Slider(1, 8, value=8, step=1, label="Round (drag to scrub)", scale=4) | |
| timer = gr.Timer(0.9, active=False) | |
| with gr.Row(): | |
| anim = gr.Plot(label="Side-by-side mission animation", show_label=False) | |
| with gr.Row(): | |
| er = gr.Plot(label="Error over rounds", show_label=False) | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("**Trust in each drone** (E4 trust layer; ≤ 0.1 in any dimension = dropped by every honest drone)") | |
| tt = gr.Dataframe(headers=["drone", "role (hidden from the swarm)", "status", "lowest trust", "swarm verdict"], wrap=True) | |
| with gr.Column(): | |
| gr.Markdown("**Incident log**: evidence each honest drone checked for itself") | |
| lg = gr.Textbox(lines=10, show_label=False) | |
| with gr.Row(): | |
| with gr.Column(): | |
| vb = gr.Button("Verify the last receipt", variant="secondary") | |
| vo = gr.Markdown() | |
| fl = gr.File(label="Download the receipt and check it yourself") | |
| with gr.Column(): | |
| rj = gr.JSON(label="Last round's receipt") | |
| state = gr.State() | |
| with gr.Column(elem_classes="sec"): | |
| gr.Markdown(S4); gr.Markdown(S5); gr.Markdown(S6); gr.Markdown(FOOT) | |
| ins = [n, p, e, i, loss, ll, rounds, seed] | |
| outs = [story, kpis, anim, er, tt, lg, rj, fl, state, vo, rnd, timer] | |
| go_btn.click(run, ins, outs) | |
| play_btn.click(play, [state, rnd], [anim, er, rnd, timer], show_progress="hidden") | |
| timer.tick(tick, [state, rnd], [anim, er, rnd, timer], show_progress="hidden") | |
| pause_btn.click(pause, None, timer, show_progress="hidden") | |
| restart_btn.click(restart, state, [anim, er, rnd, timer], show_progress="hidden") | |
| rnd.release(scrub, [state, rnd], [anim, er, timer], show_progress="hidden") | |
| vb.click(verify, state, vo) | |
| demo.load(run, ins, outs) | |
| if __name__ == "__main__": | |
| demo.queue(default_concurrency_limit=8).launch(server_name="0.0.0.0", server_port=7860) | |