library / AI and blockchain / Anomaly detection / SI0080
Program traffic anomaly alerts
You get a script that scores one program's signature rate and failure share against its own median and spread, with the network's transaction rate divided out, and prints each window's rates and one ALERT or ok verdict for the newest window.
A program inside the network's activity
A program's traffic is one slice of the network's activity, and the slice moves with the whole. When the chain speeds up for an hour, nearly every program speeds up with it. An alert on a program's own rate fires on that hour and says nothing about the program. This script reads the network's rate and the program's rate over the same windows, divides the network's movement out of the program's rate, and scores what is left.
The network side comes from getRecentPerformanceSamples. Each sample covers 60 seconds and carries the slot it ended at, the number of slots it spans and numTransactions. With votes off the chain since Alpenglow, numTransactions counts only user and program transactions, so dividing it by 60 gives transactions a second.
The program side comes from getSignaturesForAddress, which lists the signatures of transactions that name the program, newest first, each with its slot and an err that is null for a success. Both sides speak in slots, so a signature belongs to the sample whose slot range holds it.
A push feed in place of a poll
The script polls, and a window closes once a minute. Subscribe with `logsSubscribe` by mention and bucket each notification by its slot. A logsNotification carries the signature, err and log lines, and its context holds the slot. It has no blockTime, so the slot is the bucket key. Keep a count of notifications and failures per slot. When a new performance sample appears on the next getRecentPerformanceSamples poll, add up the slots in its range, and the totals are the window numbers the polled run builds, so the same scoring applies.
Subscribe at confirmed. At processed, a notification can come from a fork the cluster later drops, and its slot would then add to a window that never contained it.
Median and spread scoring
Every score has one form: how far the newest window sits from the median of the earlier windows, in units of spread. The spread is the median absolute deviation times 1.4826, which matches a standard deviation on bell-shaped data. A mean and standard deviation let one outlier window raise both, and the next outlier then hides inside the inflated spread. With the median, up to half the windows can be outliers before either number can be dragged arbitrarily far, because each outlier still moves the median by one position. A score past 3.5 alerts, a common cutoff for this score.
| Series | Baseline | Spread floor |
|---|---|---|
| Network rate, transactions a second | median of the earlier windows | 1 / WINDOW |
| Program rate, signatures a second, network-adjusted | median of the earlier adjusted windows | 1 / WINDOW |
| Failure share of the window's signatures | median of earlier windows that had signatures | 0.02 |
The adjustment is one multiplication. Each window's program rate is multiplied by the baseline network median and divided by that window's network rate. The result is the rate the program would have shown if the network had run at its median. If the network ran 20% above its median and the program ran 20% above its own, the adjusted rate sits on the baseline and scores near zero. The network score prints beside it, so a large program score with a small network score points at the program, and a large network score with a small program score points at the chain.
The script
Run it with node main.ts and an optional program address. The default is the Address Lookup Table program, a public address with steady traffic. Set CARBIUM_KEY first; the file exits with a message when it is missing, and CARBIUM_RPC_URL overrides the endpoint.
// SI0080 · Program traffic anomaly alerts// https://carbium.sh/library/si/program-traffic-anomaly-alerts// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Program traffic anomaly alerts. Run: CARBIUM_KEY=... node main.ts [programAddress]import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type Signature } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1);}const rpcUrl = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: rpcUrl, headers: { "x-api-key": key } }));// Default: the Address Lookup Table program, a public address with steady traffic.const program = address(process.argv[2] ?? "AddressLookupTab1e1111111111111111111111111");const THRESHOLD = 3.5; // alert past this many spreads from the baseline medianconst MIN_SIGS = 20; // fewest signatures in the newest window for a failure scoreconst PAGES = 4;const errText = (e: unknown) => (e instanceof Error ? e.message : String(e));const r = (x: number, d = 2) => Number(x.toFixed(d));const med = (xs: number[]) => { const s = [...xs].sort((a, b) => a - b); const h = s.length >> 1; return s.length % 2 ? (s[h] ?? 0) : ((s[h - 1] ?? 0) + (s[h] ?? 0)) / 2;};// Distance from the baseline median in spreads (1.4826 * median absolute deviation), spread floored.const score = (x: number, base: number[], floor: number) => { const m = med(base); return (x - m) / Math.max(1.4826 * med(base.map((b) => Math.abs(b - m))), floor);};// The samples and the first signature page go out together; each result is read on its own.const [perf, first] = await Promise.allSettled([ rpc.getRecentPerformanceSamples(10).send(), rpc.getSignaturesForAddress(program, { limit: 1000, commitment: "confirmed" }).send(),]);if (perf.status === "rejected" || first.status === "rejected") { if (perf.status === "rejected") console.error("samples failed:", errText(perf.reason)); if (first.status === "rejected") console.error("signatures failed:", errText(first.reason)); process.exit(1);}const WINDOW = Number(perf.value[0]?.samplePeriodSecs ?? 60);const samples = perf.value.map((s) => ({ end: Number(s.slot), start: Number(s.slot) - Number(s.numSlots), tx: Number(s.numTransactions) }));const rows: { slot: number; failed: boolean }[] = [];const state: { cursor?: Signature; more: boolean } = { more: true };const take = (page: readonly { signature: Signature; slot: bigint; err: unknown }[]) => { for (const x of page) rows.push({ slot: Number(x.slot), failed: x.err !== null }); state.cursor = page[page.length - 1]?.signature; state.more = page.length === 1000;};const oldestRow = () => rows[rows.length - 1]?.slot ?? 0;take(first.value);const oldestStart = Math.min(...samples.map((s) => s.start));for (let i = 1; i < PAGES && state.more && oldestRow() > oldestStart; i++) { try { take(await rpc.getSignaturesForAddress(program, { limit: 1000, before: state.cursor, commitment: "confirmed" }).send()); } catch (e) { console.error("older page failed:", errText(e)); break; }}// Newest first. Only windows the pages cover completely: a cut-off window would look quiet.const floorSlot = state.more ? oldestRow() : 0;type Win = { n: number; p: number; f: number; count: number };const wins: Win[] = samples .filter((s) => s.start >= floorSlot) .map((s) => { const inside = rows.filter((x) => x.slot > s.start && x.slot <= s.end); const failed = inside.filter((x) => x.failed).length; return { n: s.tx / WINDOW, p: inside.length / WINDOW, f: inside.length ? failed / inside.length : 0, count: inside.length }; });const cur = wins[0];const base = wins.slice(1);if (!cur || wins.length < 6) { console.log(JSON.stringify({ program, windows: wins.length, note: "fewer than 6 whole windows in the pages read; pass a quieter program" })); process.exit(0);}// Program rate as if the network had run at its median: a chain-wide swing divides out.const mn = med(base.map((w) => w.n));const adj = (w: Win) => (w.n > 0 ? (w.p * mn) / w.n : w.p);const floor = 1 / WINDOW;const netScore = score(cur.n, base.map((w) => w.n), floor);const progScore = score(adj(cur), base.map(adj), floor);const failScore = cur.count >= MIN_SIGS ? score(cur.f, base.filter((w) => w.count > 0).map((w) => w.f), 0.02) : 0;const fired = [Math.abs(progScore) >= THRESHOLD ? "program rate" : "", failScore >= THRESHOLD ? "failure share" : ""].filter(Boolean);wins.forEach((w, i) => console.log(`window ${i}: network ${r(w.n, 0)} tx/s, program ${r(w.p, 3)} sig/s, ${w.count} signatures, failed ${r(w.f, 3)}`));console.log(JSON.stringify({ program, windows: wins.length, networkTxPerSec: r(cur.n, 0), programSigPerSec: r(cur.p, 3), failShare: r(cur.f, 3), networkScore: r(netScore), programScore: r(progScore), failScore: r(failScore), verdict: fired.length ? `ALERT ${fired.join(", ")}` : "ok" }));
run: node main.ts
The samples call and the first signature page go out together and are settled one by one, so a failure prints which call failed. The script then reads older pages, up to four of 1000 signatures at confirmed commitment, until a page reaches back past the start of the oldest sample or the program's history runs out. A page costs 50 cells, so four cost 200, inside the 1,024-cell burst a rate class absorbs. Only windows the pages cover completely are scored, because a window cut off at its old end would look quiet. With fewer than 6 whole windows the script prints that and stops.
The output is one line per window, newest first, with the network rate, the program rate, the signature count and the failure share. A JSON line follows with both rates, the failure share, the network, program and failure scores, and a verdict of ok or ALERT with the rule that fired.
Floors for quiet programs
A quiet program has a flat baseline, and a spread of zero turns any change into an infinite score. The floors stop that. The rate floor is 1 / WINDOW, one signature in a window. Against a flat baseline one extra signature scores 1, and the score reaches 3.5 at four. Tie the floor to the window length: a shorter window makes one signature worth more, so a floor fixed at a constant would alert on single signatures.
The failure floor is 0.02. Against a baseline of zero failures, one failure in 20 signatures is a share of 0.05 and scores 2.5, and two failures score 5. The failure score runs only when the newest window holds at least 20 signatures, so a window of five signatures with one failure cannot alert by itself.
Where it ends
- The baseline is the earlier windows of one run, up to 9 minutes. A program with a daily cycle alerts at its own turn of the day. Ask the samples call for more windows, up to its limit, to cover a longer stretch.
- A program that fills 4000 signatures in under six windows leaves too few whole windows. The script says so and stops. Pass a quieter program or raise the page count, at 50 cells a page. The address index behind the pages keeps up to 30 days, far beyond a few minutes.
- The adjustment assumes the program's traffic moves in proportion to the network's. A program with its own cycle, such as a daily batch, moves on its own, and its score will show it.
- The failure score alerts on a rise only. A program whose failures fall to zero prints no alert.
- The program count is signatures that name the program, and the network count is all transactions, so the two are different units. Only the ratio between windows matters to the score.
- The script prints a verdict and delivers nothing. Run it once a minute, since a window closes each minute, and send the ALERT lines where you read them. Wallet anomaly alerts scores a single wallet the same way, and Prometheus program activity counters turns program activity into counters.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The script prints that fewer than 6 whole windows were read. | The program is too busy for four pages, or an older page failed. Pass a quieter program, or raise the page count in the script. |
| A quiet program alerts on a handful of signatures. | Raise the rate floor from 1 / WINDOW to 3 / WINDOW so a flat baseline needs about ten more signatures in the window before the score reaches 3.5. |
| The failure score alerts on a small window. | Raise the minimum of 20 signatures or the 0.02 floor, so a single failure in a thin window stays under 3.5. |
| An older page answers 429. | The script prints the message and scores the whole windows it has. Wait for the cells to refill and run again, or pass a quieter program that needs fewer pages. |
| The same program alerts at the same time every day. | The baseline is too short to see the daily cycle. Read more samples, or keep yesterday's score at that hour and compare against it. |
Questions
Which RPC provider is the most reliable for monitoring network activity in real time?
One run cannot rank providers. An ALERT flags a window whose rate left the program's own median and spread, and it names no cause, so a quiet run says nothing about an endpoint. Keep the failed calls, 429s and gaps in your own feed over days and judge from that.
Why not alert when the program's rate doubles?
A fixed ratio fires on every chain-wide swing and on every fluke of a quiet program. A score against the program's own median and spread, with the network divided out, adapts to each program.
Can I bucket by blockTime instead of slot?
getSignaturesForAddress returns a blockTime, but performance samples carry only slots, so bucketing by time would break the pairing with the network rate. Stay on slots, which logsNotification also carries.
What does one run cost?
One samples call and up to four pages of getSignaturesForAddress, at 50 cells a page, so 200 cells for the pages.