flop-guild 0.2.9 → 0.2.10
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.
- package/dist/cli.js +23 -1
- package/dist/server.js +11 -4
- package/dist/testnet.js +356 -0
- package/package.json +3 -2
package/dist/cli.js
CHANGED
|
@@ -27,6 +27,10 @@ Setup (idempotent; never overwrites keys or files)
|
|
|
27
27
|
setup [name] [--network devnet|testnet] [--dry-run] [--presets stocks,privacy,memes]
|
|
28
28
|
[--budget 0.2] [--cap 0.01] [--flow wallet|did] [--until claim] [--no-announce]
|
|
29
29
|
|
|
30
|
+
Testnet (read-only; never changes networks.json)
|
|
31
|
+
testnet-status [--check] [--verify] print the testnet candidate the watcher saved; --check fetches Flop's pages now;
|
|
32
|
+
--verify asks the candidate RPC for block 0 and compares it with the candidate genesis
|
|
33
|
+
|
|
30
34
|
Miners (read-only, no key)
|
|
31
35
|
miners [--limit 10] [--pages 10] rank miners by settled sessions and settlement rate
|
|
32
36
|
|
|
@@ -39,7 +43,7 @@ Secrets live in ~/.flop-guild (or FLOP_GUILD_HOME), mode 600, and are never prin
|
|
|
39
43
|
function parse(argv) {
|
|
40
44
|
const pos = [];
|
|
41
45
|
const opt = {};
|
|
42
|
-
const flags = new Set(["json", "yes", "help", "dry-run", "no-announce"]);
|
|
46
|
+
const flags = new Set(["json", "yes", "help", "dry-run", "no-announce", "check", "verify"]);
|
|
43
47
|
for (let i = 0; i < argv.length; i++) {
|
|
44
48
|
const a = argv[i];
|
|
45
49
|
if (a.startsWith("--")) {
|
|
@@ -191,6 +195,24 @@ async function main() {
|
|
|
191
195
|
});
|
|
192
196
|
break;
|
|
193
197
|
}
|
|
198
|
+
case "testnet-status": {
|
|
199
|
+
const t = await import("./testnet.js");
|
|
200
|
+
if (get("check") === "true")
|
|
201
|
+
await t.checkOnce({ log: () => { } });
|
|
202
|
+
const { existsSync, readFileSync } = await import("node:fs");
|
|
203
|
+
const st = t.status();
|
|
204
|
+
const cand = existsSync(t.candidatePath()) ? readFileSync(t.candidatePath(), "utf8").trim() : "no candidate saved yet (the watcher runs inside the site server; or use --check)";
|
|
205
|
+
out = `testnet published: ${st.published}\nlast checked: ${st.lastChecked ?? "never"}\nlast changed: ${st.lastChanged ?? "never"}${st.lastError ? `\nlast error: ${st.lastError}` : ""}\ncandidate (${t.candidatePath()}):\n${cand}`;
|
|
206
|
+
if (get("verify") === "true") {
|
|
207
|
+
const v = await t.verifyCandidate();
|
|
208
|
+
out += v.error
|
|
209
|
+
? `\nverify: NOT VERIFIED: ${v.error}`
|
|
210
|
+
: `\nverify: ${v.match ? "MATCH" : "MISMATCH"}\n rpc: ${v.rpc}\n candidate: ${v.expected}\n rpc says: ${v.actual}`;
|
|
211
|
+
if (!v.match)
|
|
212
|
+
process.exitCode = 1;
|
|
213
|
+
}
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
194
216
|
case "miners": {
|
|
195
217
|
const { miners } = await import("./miners.js");
|
|
196
218
|
out = await miners(network, num("limit") ?? 10, num("pages") ?? 10);
|
package/dist/server.js
CHANGED
|
@@ -300,10 +300,12 @@ async function homeStats() {
|
|
|
300
300
|
const faucet = Number.isFinite(cap) && cap > 0
|
|
301
301
|
? stat(ICONS.faucet, "Faucet daily limit", `${cap.toLocaleString("en-US")} FLOP`, `whole faucet per day${Number.isFinite(grant) && grant > 0 ? `, ${grant} FLOP per address${Number.isFinite(hours) && hours > 0 ? ` every ${hours} h` : ""}` : ""} ${devnet}`, "on", "LIVE")
|
|
302
302
|
: stat(ICONS.faucet, "Faucet daily limit", DASH, `faucet did not answer ${devnet}`, "off", "NO DATA");
|
|
303
|
-
|
|
304
|
-
const
|
|
305
|
-
|
|
306
|
-
|
|
303
|
+
void nets;
|
|
304
|
+
const tn = (await import("./testnet.js")).status();
|
|
305
|
+
const when = (iso) => (iso ? `${iso.slice(0, 16).replace("T", " ")} UTC` : "");
|
|
306
|
+
const testnet = tn.published
|
|
307
|
+
? stat(ICONS.clock, "Testnet status", "Endpoints published, not yet enabled in the kit", `seen on Flop's testnet page since ${when(tn.lastChanged)}`, "on", "LIVE", true)
|
|
308
|
+
: stat(ICONS.clock, "Testnet status", "Waiting for Flop endpoints", tn.lastChecked ? `Flop's testnet page checked ${when(tn.lastChecked)}; not yet published: ${tn.missing.join(", ")}` : "first check of Flop's testnet page pending", "off", "WATCHING", true);
|
|
307
309
|
return `<div class="stats">${miners}${validators}${faucet}${testnet}</div>`;
|
|
308
310
|
}
|
|
309
311
|
// ---------- HTTP ----------
|
|
@@ -370,6 +372,7 @@ async function mcp(req, res) {
|
|
|
370
372
|
}
|
|
371
373
|
export function startServer(port, host = "0.0.0.0") {
|
|
372
374
|
publicHost(); // fail fast on a bad PUBLIC_HOST
|
|
375
|
+
void import("./testnet.js").then((t) => t.startWatcher());
|
|
373
376
|
const server = createServer(async (req, res) => {
|
|
374
377
|
try {
|
|
375
378
|
const path = new URL(req.url ?? "/", "http://x").pathname.replace(/\/+$/, "") || "/";
|
|
@@ -377,6 +380,10 @@ export function startServer(port, host = "0.0.0.0") {
|
|
|
377
380
|
return await mcp(req, res);
|
|
378
381
|
if (req.method !== "GET" && req.method !== "HEAD")
|
|
379
382
|
return send(res, 405, "text/plain", "method not allowed\n", { allow: "GET, HEAD" });
|
|
383
|
+
if (path === "/api/status") {
|
|
384
|
+
const { status } = await import("./testnet.js");
|
|
385
|
+
return send(res, 200, "application/json", JSON.stringify(status(), null, 2), { "cache-control": "no-store" });
|
|
386
|
+
}
|
|
380
387
|
if (path === "/healthz")
|
|
381
388
|
return send(res, 200, "text/plain", "ok\n", { "cache-control": "no-store" });
|
|
382
389
|
if (path === "/start") {
|
package/dist/testnet.js
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
// Testnet watcher. Reads Flop's official pages, extracts the testnet endpoints and keeps them as a
|
|
2
|
+
// candidate for a human to review. It never writes networks.json and never points the kit at them.
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { homeDir } from "./identity.js";
|
|
6
|
+
import { networksPath } from "./net.js";
|
|
7
|
+
export const SOURCES = {
|
|
8
|
+
docs: "https://docs.flop.network/networks/testnet",
|
|
9
|
+
releases: "https://flop.network/releases.json",
|
|
10
|
+
};
|
|
11
|
+
export const INTERVAL_MS = 5 * 60 * 1000;
|
|
12
|
+
export const FIELDS = ["rpc", "gateway", "faucet", "genesis", "chainId"];
|
|
13
|
+
// ---------- validation ----------
|
|
14
|
+
const isHttps = (u) => !!u && /^https:\/\/[a-z0-9.-]+(:\d+)?(\/\S*)?$/i.test(u);
|
|
15
|
+
const isRpc = (u) => !!u && /^(wss|https):\/\/[a-z0-9.-]+(:\d+)?(\/\S*)?$/i.test(u);
|
|
16
|
+
const VALID = {
|
|
17
|
+
rpc: isRpc, // the kit talks to the chain over WebSocket; an https RPC is accepted too
|
|
18
|
+
gateway: isHttps,
|
|
19
|
+
faucet: isHttps,
|
|
20
|
+
genesis: (v) => !!v && /^0x[0-9a-f]{64}$/i.test(v),
|
|
21
|
+
chainId: (v) => !!v && /^[a-z0-9][a-z0-9_-]{2,63}$/i.test(v),
|
|
22
|
+
};
|
|
23
|
+
export function missingFields(c) {
|
|
24
|
+
return FIELDS.filter((f) => !VALID[f](c[f]));
|
|
25
|
+
}
|
|
26
|
+
// ---------- extraction ----------
|
|
27
|
+
/** Hosts the kit already uses for devnet. A testnet field may not reuse one of them from prose. */
|
|
28
|
+
function devnetHosts() {
|
|
29
|
+
try {
|
|
30
|
+
const d = JSON.parse(readFileSync(networksPath(), "utf8")).devnet ?? {};
|
|
31
|
+
return new Set(Object.values(d).filter((v) => typeof v === "string" && /^[a-z]+:\/\//.test(v)).map((v) => new URL(v).host));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return new Set();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** HTML to plain text, keeping link targets as "text (url)". */
|
|
38
|
+
export function pageText(html) {
|
|
39
|
+
return html
|
|
40
|
+
.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>/gi, " ")
|
|
41
|
+
.replace(/<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi, (_m, href, t) => `${t} (${href})`)
|
|
42
|
+
.replace(/<[^>]+>/g, " ")
|
|
43
|
+
.replace(/&/g, "&")
|
|
44
|
+
.replace(/</g, "<")
|
|
45
|
+
.replace(/>/g, ">")
|
|
46
|
+
.replace(/"/g, '"')
|
|
47
|
+
.replace(/'|'/g, "'")
|
|
48
|
+
.replace(/\s+/g, " ")
|
|
49
|
+
.trim();
|
|
50
|
+
}
|
|
51
|
+
const KEYWORDS = {
|
|
52
|
+
rpc: /\bRPC\b/,
|
|
53
|
+
gateway: /\bgateway\b/i,
|
|
54
|
+
faucet: /\bfaucet\b/i,
|
|
55
|
+
};
|
|
56
|
+
/** Hosts that are never endpoints: package registries, code hosting, block explorers. */
|
|
57
|
+
const NOT_ENDPOINT = /(^|\.)(npmjs\.org|npmjs\.com|github\.com|githubusercontent\.com)$|scan\b|explorer/i;
|
|
58
|
+
const NEAR = 60; // max characters between the keyword and the URL, with no other URL in between
|
|
59
|
+
/**
|
|
60
|
+
* From the docs page: a URL counts for a field only when it is close to a word naming the field,
|
|
61
|
+
* in a sentence that does not mention devnet, and its host is neither a devnet host of the kit nor
|
|
62
|
+
* a registry, code host or explorer. For the RPC a wss:// URL wins over https://.
|
|
63
|
+
*/
|
|
64
|
+
export function fromDocs(html, devHosts = devnetHosts()) {
|
|
65
|
+
const text = pageText(html);
|
|
66
|
+
const c = {};
|
|
67
|
+
const sentences = text.split(/(?<=[.?!])\s+(?=[A-Z])/);
|
|
68
|
+
for (const field of ["rpc", "gateway", "faucet"]) {
|
|
69
|
+
const found = [];
|
|
70
|
+
for (const s of sentences) {
|
|
71
|
+
if (/devnet/i.test(s))
|
|
72
|
+
continue;
|
|
73
|
+
const urls = [...s.matchAll(/\b(?:https|wss):\/\/[^\s()<>"',]+/g)].map((m) => ({ u: m[0].replace(/[.;:]+$/, ""), at: m.index, end: m.index + m[0].length }));
|
|
74
|
+
const keys = [...s.matchAll(new RegExp(KEYWORDS[field].source, KEYWORDS[field].flags.includes("i") ? "gi" : "g"))].map((m) => ({ at: m.index, end: m.index + m[0].length }));
|
|
75
|
+
for (const x of urls) {
|
|
76
|
+
let host;
|
|
77
|
+
try {
|
|
78
|
+
host = new URL(x.u).host;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (devHosts.has(host) || NOT_ENDPOINT.test(host))
|
|
84
|
+
continue;
|
|
85
|
+
if (!(field === "rpc" ? isRpc(x.u) : isHttps(x.u)))
|
|
86
|
+
continue;
|
|
87
|
+
const near = keys.some((k) => {
|
|
88
|
+
const [from, to] = k.at >= x.end ? [x.end, k.at] : [k.end, x.at];
|
|
89
|
+
if (to - from > NEAR || to < from)
|
|
90
|
+
return false;
|
|
91
|
+
return !urls.some((o) => o !== x && o.at >= from && o.end <= to);
|
|
92
|
+
});
|
|
93
|
+
if (near)
|
|
94
|
+
found.push(x.u);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const pick = field === "rpc" ? (found.find((u) => u.startsWith("wss:")) ?? found[0]) : found[0];
|
|
98
|
+
if (pick)
|
|
99
|
+
c[field] = pick;
|
|
100
|
+
}
|
|
101
|
+
const g = text.match(/genesis[^.]{0,80}?\b(0x[0-9a-fA-F]{64})\b/i);
|
|
102
|
+
if (g)
|
|
103
|
+
c.genesis = g[1].toLowerCase();
|
|
104
|
+
const id = text.match(/chain ID (?:is|:)\s*`?([A-Za-z0-9][A-Za-z0-9_-]{2,63})/i);
|
|
105
|
+
if (id)
|
|
106
|
+
c.chainId = id[1];
|
|
107
|
+
return c;
|
|
108
|
+
}
|
|
109
|
+
/** From releases.json: any object that names itself testnet (or sits under a "testnet" key) and carries endpoint fields. */
|
|
110
|
+
export function fromReleases(json) {
|
|
111
|
+
const c = {};
|
|
112
|
+
const pick = (o) => {
|
|
113
|
+
const get = (...keys) => keys.map((k) => o[k]).find((v) => typeof v === "string");
|
|
114
|
+
c.rpc ??= get("rpc", "rpcUrl", "rpc_url", "ws", "wss");
|
|
115
|
+
c.gateway ??= get("gateway", "gatewayUrl", "gateway_url", "api");
|
|
116
|
+
c.faucet ??= get("faucet", "faucetUrl", "faucet_url");
|
|
117
|
+
c.genesis ??= get("genesis", "genesisHash", "genesis_hash")?.toLowerCase();
|
|
118
|
+
c.chainId ??= get("chainId", "chain_id", "chainID");
|
|
119
|
+
};
|
|
120
|
+
const walk = (v, underTestnet, depth) => {
|
|
121
|
+
if (!v || typeof v !== "object" || depth > 8)
|
|
122
|
+
return;
|
|
123
|
+
if (Array.isArray(v))
|
|
124
|
+
return v.forEach((x) => walk(x, underTestnet, depth + 1));
|
|
125
|
+
const o = v;
|
|
126
|
+
const named = [o.network, o.name, o.id].some((x) => typeof x === "string" && x.toLowerCase() === "testnet");
|
|
127
|
+
if (underTestnet || named)
|
|
128
|
+
pick(o);
|
|
129
|
+
for (const [k, x] of Object.entries(o))
|
|
130
|
+
walk(x, underTestnet || named || k.toLowerCase() === "testnet", depth + 1);
|
|
131
|
+
};
|
|
132
|
+
walk(json, false, 0);
|
|
133
|
+
for (const f of FIELDS)
|
|
134
|
+
if (c[f] === undefined)
|
|
135
|
+
delete c[f];
|
|
136
|
+
return c;
|
|
137
|
+
}
|
|
138
|
+
/** Merge both sources: releases.json (structured) wins over prose for any field it has. */
|
|
139
|
+
export function extract(docsHtml, releasesJson, devHosts = devnetHosts()) {
|
|
140
|
+
const d = docsHtml ? fromDocs(docsHtml, devHosts) : {};
|
|
141
|
+
const r = releasesJson ? fromReleases(releasesJson) : {};
|
|
142
|
+
const candidate = {};
|
|
143
|
+
const sources = {};
|
|
144
|
+
for (const f of FIELDS) {
|
|
145
|
+
if (VALID[f](r[f]))
|
|
146
|
+
(candidate[f] = r[f]), (sources[f] = SOURCES.releases);
|
|
147
|
+
else if (VALID[f](d[f]))
|
|
148
|
+
(candidate[f] = d[f]), (sources[f] = SOURCES.docs);
|
|
149
|
+
}
|
|
150
|
+
const missing = missingFields(candidate);
|
|
151
|
+
return { candidate, sources, missing, published: missing.length === 0 };
|
|
152
|
+
}
|
|
153
|
+
// ---------- state ----------
|
|
154
|
+
export const statePath = () => join(homeDir(), "testnet-watch.json");
|
|
155
|
+
export const candidatePath = () => join(homeDir(), "testnet-candidate.json");
|
|
156
|
+
export function loadState() {
|
|
157
|
+
try {
|
|
158
|
+
return JSON.parse(readFileSync(statePath(), "utf8"));
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
return { published: false, candidate: {}, missing: [...FIELDS], sources: {} };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function writeJson(path, v) {
|
|
165
|
+
mkdirSync(homeDir(), { recursive: true, mode: 0o700 });
|
|
166
|
+
writeFileSync(path + ".tmp", JSON.stringify(v, null, 2) + "\n", { mode: 0o600 });
|
|
167
|
+
renameSync(path + ".tmp", path);
|
|
168
|
+
}
|
|
169
|
+
const fingerprint = (s) => JSON.stringify([s.published, FIELDS.map((f) => s.candidate[f] ?? null)]);
|
|
170
|
+
let warnedNoTelegram = false;
|
|
171
|
+
/** Telegram via FLOP_TG_TOKEN and FLOP_TG_CHAT. Unset: log once and skip. The token is never logged. */
|
|
172
|
+
export async function notify(text, log, fetcher = fetch) {
|
|
173
|
+
const token = process.env.FLOP_TG_TOKEN;
|
|
174
|
+
const chat = process.env.FLOP_TG_CHAT;
|
|
175
|
+
if (!token || !chat) {
|
|
176
|
+
if (!warnedNoTelegram)
|
|
177
|
+
log("testnet watcher: FLOP_TG_TOKEN or FLOP_TG_CHAT not set, Telegram messages skipped");
|
|
178
|
+
warnedNoTelegram = true;
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
const f = fetcher;
|
|
183
|
+
const r = await f(`https://api.telegram.org/bot${token}/sendMessage`, {
|
|
184
|
+
method: "POST",
|
|
185
|
+
headers: { "content-type": "application/json" },
|
|
186
|
+
body: JSON.stringify({ chat_id: chat, text, disable_web_page_preview: true }),
|
|
187
|
+
signal: AbortSignal.timeout(15_000),
|
|
188
|
+
});
|
|
189
|
+
if (!r.ok)
|
|
190
|
+
log(`testnet watcher: Telegram answered HTTP ${r.status}`);
|
|
191
|
+
return r.ok;
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
log(`testnet watcher: Telegram failed: ${e.name}`); // never the URL: it holds the token
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function message(s, first) {
|
|
199
|
+
const lines = FIELDS.map((f) => `${f}: ${s.candidate[f] ?? "missing"}`);
|
|
200
|
+
const head = first
|
|
201
|
+
? "flop-guild: Flop testnet endpoints are published. Not enabled in the kit; review testnet-candidate.json."
|
|
202
|
+
: `flop-guild: testnet candidate changed (${s.published ? "published" : "no longer complete"}). Not enabled in the kit.`;
|
|
203
|
+
return [head, ...lines, `source: ${SOURCES.docs}`].join("\n");
|
|
204
|
+
}
|
|
205
|
+
/** One check. Fetch errors keep the last state and record the error. */
|
|
206
|
+
export async function checkOnce(o = {}) {
|
|
207
|
+
const fetcher = o.fetcher ?? ((u) => fetch(u, { headers: { "user-agent": "flop-guild-testnet-watch" }, signal: AbortSignal.timeout(20_000) }));
|
|
208
|
+
const now = (o.now ?? (() => new Date()))().toISOString();
|
|
209
|
+
const log = o.log ?? ((s) => process.stderr.write(s + "\n"));
|
|
210
|
+
const prev = loadState();
|
|
211
|
+
const get = async (u) => {
|
|
212
|
+
const r = await fetcher(u);
|
|
213
|
+
if (!r.ok)
|
|
214
|
+
throw new Error(`${u}: HTTP ${r.status}`);
|
|
215
|
+
return r.text();
|
|
216
|
+
};
|
|
217
|
+
const [docs, rel] = await Promise.allSettled([get(SOURCES.docs), get(SOURCES.releases)]);
|
|
218
|
+
if (docs.status === "rejected" && rel.status === "rejected") {
|
|
219
|
+
const next = { ...prev, lastChecked: now, lastError: `${docs.reason?.message}; ${rel.reason?.message}` };
|
|
220
|
+
writeJson(statePath(), next);
|
|
221
|
+
return next;
|
|
222
|
+
}
|
|
223
|
+
let relJson;
|
|
224
|
+
try {
|
|
225
|
+
relJson = rel.status === "fulfilled" ? JSON.parse(rel.value) : undefined;
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
relJson = undefined;
|
|
229
|
+
}
|
|
230
|
+
const x = extract(docs.status === "fulfilled" ? docs.value : undefined, relJson, o.devHosts);
|
|
231
|
+
const next = {
|
|
232
|
+
published: x.published,
|
|
233
|
+
lastChecked: now,
|
|
234
|
+
lastChanged: prev.lastChanged,
|
|
235
|
+
firstPublishedAt: prev.firstPublishedAt,
|
|
236
|
+
candidate: x.candidate,
|
|
237
|
+
missing: x.missing,
|
|
238
|
+
sources: x.sources,
|
|
239
|
+
lastError: [docs, rel].filter((p) => p.status === "rejected").map((p) => p.reason?.message).join("; ") || undefined,
|
|
240
|
+
};
|
|
241
|
+
const changed = fingerprint(prev) !== fingerprint(next) || !existsSync(statePath());
|
|
242
|
+
if (changed)
|
|
243
|
+
next.lastChanged = now;
|
|
244
|
+
const firstFlip = next.published && !prev.firstPublishedAt;
|
|
245
|
+
if (firstFlip)
|
|
246
|
+
next.firstPublishedAt = now;
|
|
247
|
+
writeJson(statePath(), next);
|
|
248
|
+
if (changed) {
|
|
249
|
+
writeJson(candidatePath(), { note: "Candidate only. Not used by the kit and not written to networks.json. Review before enabling.", published: next.published, checked: now, missing: next.missing, ...next.candidate, sources: next.sources });
|
|
250
|
+
log(`testnet watcher: ${next.published ? "published" : `waiting (missing: ${next.missing.join(", ")})`}`);
|
|
251
|
+
}
|
|
252
|
+
// Telegram on the first flip, and on any change after that.
|
|
253
|
+
if (firstFlip || (changed && prev.firstPublishedAt))
|
|
254
|
+
await notify(message(next, firstFlip), log);
|
|
255
|
+
return next;
|
|
256
|
+
}
|
|
257
|
+
/** Public summary for /api/status and the home page card. */
|
|
258
|
+
export function status() {
|
|
259
|
+
const s = loadState();
|
|
260
|
+
return {
|
|
261
|
+
published: s.published,
|
|
262
|
+
lastChecked: s.lastChecked ?? null,
|
|
263
|
+
lastChanged: s.lastChanged ?? null,
|
|
264
|
+
missing: s.missing,
|
|
265
|
+
lastError: s.lastError ?? null,
|
|
266
|
+
note: "Endpoints are never enabled in the kit automatically.",
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
let timer;
|
|
270
|
+
/** Start the 5-minute loop inside the site server. TESTNET_WATCH=0 turns it off. */
|
|
271
|
+
export function startWatcher(log = (s) => process.stderr.write(s + "\n")) {
|
|
272
|
+
if (timer || process.env.TESTNET_WATCH === "0")
|
|
273
|
+
return;
|
|
274
|
+
const run = () => checkOnce({ log }).catch((e) => log(`testnet watcher: ${e.message}`));
|
|
275
|
+
void run();
|
|
276
|
+
timer = setInterval(run, INTERVAL_MS);
|
|
277
|
+
timer.unref();
|
|
278
|
+
}
|
|
279
|
+
/** Ask an RPC for the hash of block 0 with one JSON-RPC call. Read-only: no keys, no writes. */
|
|
280
|
+
export async function genesisFromRpc(rpc, timeoutMs = 20_000) {
|
|
281
|
+
const req = { jsonrpc: "2.0", id: 1, method: "chain_getBlockHash", params: [0] };
|
|
282
|
+
const read = (j) => {
|
|
283
|
+
if (j?.error)
|
|
284
|
+
throw new Error(`RPC error: ${j.error.message ?? JSON.stringify(j.error)}`);
|
|
285
|
+
if (typeof j?.result !== "string")
|
|
286
|
+
throw new Error("RPC answer has no block hash");
|
|
287
|
+
return j.result.toLowerCase();
|
|
288
|
+
};
|
|
289
|
+
if (/^https:/i.test(rpc)) {
|
|
290
|
+
const r = await fetch(rpc, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(req), signal: AbortSignal.timeout(timeoutMs) });
|
|
291
|
+
if (!r.ok)
|
|
292
|
+
throw new Error(`RPC HTTP ${r.status}`);
|
|
293
|
+
return read(await r.json());
|
|
294
|
+
}
|
|
295
|
+
if (!/^wss:/i.test(rpc))
|
|
296
|
+
throw new Error(`not a wss:// or https:// RPC: ${rpc}`);
|
|
297
|
+
const { default: WS } = await import("ws");
|
|
298
|
+
return new Promise((resolve, reject) => {
|
|
299
|
+
const ws = new WS(rpc, { headers: { "user-agent": "flop-guild-testnet-verify" }, handshakeTimeout: timeoutMs });
|
|
300
|
+
let settled = false;
|
|
301
|
+
const timer = setTimeout(() => done(new Error(`no answer from ${rpc} within ${timeoutMs / 1000} s`)), timeoutMs);
|
|
302
|
+
const done = (err, v) => {
|
|
303
|
+
if (settled)
|
|
304
|
+
return; // terminate() can emit again; settle once
|
|
305
|
+
settled = true;
|
|
306
|
+
clearTimeout(timer);
|
|
307
|
+
try {
|
|
308
|
+
ws.terminate();
|
|
309
|
+
}
|
|
310
|
+
catch { }
|
|
311
|
+
err ? reject(err) : resolve(v);
|
|
312
|
+
};
|
|
313
|
+
ws.on("open", () => ws.send(JSON.stringify(req)));
|
|
314
|
+
ws.on("message", (data) => {
|
|
315
|
+
try {
|
|
316
|
+
const j = JSON.parse(String(data));
|
|
317
|
+
if (j.id === 1)
|
|
318
|
+
done(undefined, read(j));
|
|
319
|
+
}
|
|
320
|
+
catch (e) {
|
|
321
|
+
done(e);
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
ws.on("unexpected-response", (_req, res) => done(new Error(`${rpc} refused the connection: HTTP ${res.statusCode}${res.statusCode === 429 ? " (rate limited, try again later)" : ""}`)));
|
|
325
|
+
ws.on("error", (e) => done(new Error(`could not connect to ${rpc}: ${e.message}`)));
|
|
326
|
+
ws.on("close", () => done(new Error(`connection to ${rpc} closed before an answer`)));
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
/** Compare the candidate's genesis with what the candidate RPC reports. Reads the candidate file only. */
|
|
330
|
+
export async function verifyCandidate() {
|
|
331
|
+
let c = {};
|
|
332
|
+
try {
|
|
333
|
+
c = JSON.parse(readFileSync(candidatePath(), "utf8"));
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
c = loadState().candidate ?? {};
|
|
337
|
+
}
|
|
338
|
+
if (!c.rpc || !VALID.rpc(c.rpc))
|
|
339
|
+
return { rpc: c.rpc ?? "", expected: c.genesis ?? "", match: false, error: "the candidate has no valid RPC" };
|
|
340
|
+
if (!c.genesis || !VALID.genesis(c.genesis))
|
|
341
|
+
return { rpc: c.rpc, expected: c.genesis ?? "", match: false, error: "the candidate has no valid genesis hash" };
|
|
342
|
+
// A public RPC can rate-limit (HTTP 429) right after launch: try three times, 5 s then 15 s apart.
|
|
343
|
+
let last = "";
|
|
344
|
+
for (const wait of [0, 5_000, 15_000]) {
|
|
345
|
+
if (wait)
|
|
346
|
+
await new Promise((r) => setTimeout(r, wait));
|
|
347
|
+
try {
|
|
348
|
+
const actual = await genesisFromRpc(c.rpc);
|
|
349
|
+
return { rpc: c.rpc, expected: c.genesis.toLowerCase(), actual, match: actual === c.genesis.toLowerCase() };
|
|
350
|
+
}
|
|
351
|
+
catch (e) {
|
|
352
|
+
last = e.message;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return { rpc: c.rpc, expected: c.genesis, match: false, error: `${last} (3 attempts)` };
|
|
356
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "flop-guild",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.10",
|
|
4
4
|
"description": "Technocore guild kit: Ed25519 did:key signing CLI for technocore.chat rooms, plus an agent identity scaffold.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -43,7 +43,8 @@
|
|
|
43
43
|
"@polkadot/api": "17.0.2",
|
|
44
44
|
"@polkadot/keyring": "14.0.3",
|
|
45
45
|
"@polkadot/util": "14.0.3",
|
|
46
|
-
"@polkadot/util-crypto": "14.0.3"
|
|
46
|
+
"@polkadot/util-crypto": "14.0.3",
|
|
47
|
+
"ws": "8.23.0"
|
|
47
48
|
},
|
|
48
49
|
"devDependencies": {
|
|
49
50
|
"@noble/ed25519": "3.2.0",
|