---
id: UC0043
title: "Signed webhook audit trail"
url: https://carbium.sh/library/usecase/signed-webhook-audit-trail
collection: Use cases
category: Compliance, risk and monitoring
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Signed webhook audit trail

A compliance team wants one record per request and signed payloads. A Node wrapper writes every Solana RPC call into a tamper-evident SQLite chain, with a signature check for webhook-style payloads and the procurement questions a script cannot answer.

## What the trail holds

A per-request audit trail answers four questions about any call your system made to a Solana endpoint: what was asked, when, what came back, and whether anyone changed the record since. The provider keeps its own logs of its side. The record you can hand an auditor without opening a ticket is the one you write yourself, at the single point every call passes through.

The trail here has two parts. The first is one row per request: a timestamp, the method name, a SHA-256 of the params, the outcome and the elapsed milliseconds. Params go in as a hash, so the trail never stores wallet addresses or amounts a reviewer has no need to see, and an auditor who holds the original request can still prove it matches the row.

The second part is a signature. Each row carries an HMAC-SHA256 over its own fields and the previous row's HMAC, so the rows form a chain. Editing or deleting a row changes every HMAC after it, and a verification pass finds the first break.

## One place every call passes

@solana/kit builds an RPC client from a transport, a function that takes the JSON-RPC payload and returns the response. `createDefaultRpcTransport` makes the HTTPS one, with headers set once: the key rides in the [x-api-key header](https://carbium.sh/docs#auth) on calls to the [RPC endpoint](https://carbium.sh/docs#endpoints) `https://services.carbium.sh`. The script wraps that transport in a function of the same type that times the call, writes a row and hands the result back untouched. Every client built on the wrapper is audited without touching its call sites.

Three outcomes are recorded. `ok` is a normal answer. `rpc_error` carries the JSON-RPC code, such as -32601 for a method that is not served, which is final and [should never be retried](https://carbium.sh/docs#errors). `transport_error` carries the HTTP status when the call itself failed, such as 429, and the error name when there is no status. A 429 lands as a `transport_error` row, and a retry is a new request with its own row, so an auditor sees two attempts for one logical call.

The key never reaches a row. It lives in the transport's header, and a row holds only the method, the params hash, the outcome and the timing. The kit client sends one call per request. A JSON-RPC batch of up to 100 calls is one HTTP request, so the wrapper writes it as one row named `batch`, with a hash over the whole batch payload; split the batch if your auditors want a row per call.

## A script in one file

Run it with an optional address; the default is a busy program account. It sends `getSlot`, `getEpochInfo` and `getBalance` through the audited client, settles each call so one failure does not hide the others, then walks the whole table and verifies the chain. It reads `CARBIUM_KEY` for the RPC key and `AUDIT_HMAC_KEY` for the signing secret, and exits with a message when either is unset. It signs and sends no transaction.

`main.ts` (run: `CARBIUM_KEY=$CARBIUM_KEY AUDIT_HMAC_KEY=$AUDIT_HMAC_KEY node main.ts [address]`)

```ts
// UC0043 · Signed webhook audit trail
// https://carbium.sh/library/usecase/signed-webhook-audit-trail
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only: every RPC request leaves an HMAC-signed, hash-chained audit row in SQLite.
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { DatabaseSync } from "node:sqlite";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } 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 secret = process.env.AUDIT_HMAC_KEY;
if (!secret) { console.error("Set AUDIT_HMAC_KEY to the secret that signs audit rows."); process.exit(1); }
const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const subject = process.argv[2] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";

const hmac = (s: string) => createHmac("sha256", secret).update(s).digest("hex");
const sha = (s: string) => createHash("sha256").update(s).digest("hex");
// Delivered payloads use a key derived from the chain secret, so a receiver cannot re-sign the chain.
const deliveryKey = createHmac("sha256", secret).update("delivery").digest();
const dmac = (s: string) => createHmac("sha256", deliveryKey).update(s).digest("hex");

const db = new DatabaseSync("audit.db");
db.exec("CREATE TABLE IF NOT EXISTS audit (seq INTEGER PRIMARY KEY, ts TEXT, method TEXT, params_sha TEXT, outcome TEXT, ms INTEGER, prev TEXT, mac TEXT)");
type Row = { ts: string; method: string; params_sha: string; outcome: string; ms: number; prev: string; mac: string };
const fields = (r: Omit<Row, "mac">) => [r.ts, r.method, r.params_sha, r.outcome, r.ms, r.prev].join("|");
const insert = db.prepare("INSERT INTO audit (ts, method, params_sha, outcome, ms, prev, mac) VALUES (?,?,?,?,?,?,?)");
const last = db.prepare("SELECT mac FROM audit ORDER BY seq DESC LIMIT 1").get() as unknown as { mac: string } | undefined;
let prev = last?.mac ?? "genesis";

// One wrapper around the transport: every call through it is recorded, params as a hash only.
const inner = createDefaultRpcTransport({ url, headers: { "x-api-key": key } });
const transport: typeof inner = async <TResponse>(config: Parameters<typeof inner>[0]): Promise<TResponse> => {
  const p = config.payload as { method?: string; params?: unknown };
  const method = Array.isArray(config.payload) ? "batch" : String(p.method);
  const t0 = Date.now();
  let outcome = "ok";
  try {
    const res = await inner<TResponse>(config);
    const code = (res as unknown as { error?: { code?: number } } | null)?.error?.code;
    if (code !== undefined) outcome = `rpc_error ${code}`;
    return res;
  } catch (e) {
    outcome = `transport_error ${(e as { context?: { statusCode?: number } }).context?.statusCode ?? (e as Error).name}`;
    throw e;
  } finally {
    const hashed = Array.isArray(config.payload) ? config.payload : (p.params ?? null);
    const row = { ts: new Date().toISOString(), method, params_sha: sha(JSON.stringify(hashed)), outcome, ms: Date.now() - t0, prev };
    const mac = hmac(fields(row));
    insert.run(row.ts, row.method, row.params_sha, row.outcome, row.ms, row.prev, mac);
    prev = mac;
  }
};

// Webhook-style signature: t=<unix>,v1=<hex of HMAC over "t.payload"> under the delivery key.
const sign = (t: number, payload: string) => `t=${t},v1=${dmac(`${t}.${payload}`)}`;
const verify = (header: string, payload: string) => {
  const [t = "", v = ""] = header.split(",").map((s) => s.slice(s.indexOf("=") + 1));
  const want = Buffer.from(dmac(`${t}.${payload}`));
  const got = Buffer.from(v);
  return Math.abs(Date.now() / 1000 - Number(t)) < 300 && want.length === got.length && timingSafeEqual(want, got);
};

const rpc = createSolanaRpcFromTransport(transport);
const names = ["getSlot", "getEpochInfo", "getBalance"];
const calls = await Promise.allSettled([
  rpc.getSlot().send(),
  rpc.getEpochInfo().send(),
  rpc.getBalance(address(subject)).send(),
]);
calls.forEach((c, i) => console.log(names[i], c.status === "fulfilled" ? "ok" : `failed: ${(c.reason as Error).message}`));

// Verify the chain: each row links to the MAC before it and its own MAC recomputes.
const rows = db.prepare("SELECT * FROM audit ORDER BY seq").all() as unknown as (Row & { seq: number })[];
let link = "genesis";
const broken = rows.filter((r) => { const bad = r.prev !== link || r.mac !== hmac(fields(r)); link = r.mac; return bad; });
console.log(`audit rows ${rows.length}, broken ${broken.length}${broken[0] ? `, first at seq ${broken[0].seq}` : ""}`);

const head = rows[rows.length - 1];
if (head) {
  const payload = JSON.stringify({ method: head.method, outcome: head.outcome, mac: head.mac });
  const header = sign(Math.floor(Date.now() / 1000), payload);
  console.log("signed payload verifies:", verify(header, payload));
  console.log("changed payload verifies:", verify(header, payload.replace(head.outcome, "edited")));
}
```

The calls leave commitment out, so kit fills in confirmed, while the JSON-RPC server's own default is finalized. Kit writes that commitment into the params it sends, so the params hash in each row covers it. The script keeps the database in `audit.db` next to where it runs; point it at persistent storage in production.

## Signing rows and payloads

Verification recomputes every HMAC from the stored fields and checks that each row's `prev` equals the MAC before it. An auditor needs the table, the secret and the field order `ts|method|params_sha|outcome|ms|prev`, and nothing from your application. Keep `AUDIT_HMAC_KEY` apart from the Carbium key: they guard different things and rotate on different schedules.

Payloads you push to a log pipeline or to an auditor's endpoint are signed with a separate key derived from the chain secret, the HMAC-SHA256 of the word `delivery`, so a receiver who can check a payload cannot re-sign the chain. The header is `t=<unix seconds>,v1=<hex>`, where the hex is an HMAC over `t.payload` under that derived key. The receiver recomputes it from the raw body bytes, compares in constant time, and rejects a timestamp more than 300 seconds old, which stops a captured delivery from being replayed later. The script prints the check passing for the original payload and failing for one with a changed outcome.

That header format is this script's own convention. When a sender signs deliveries to you, verify them by the format the sender documents, with the same three habits: raw body, timestamp window, constant-time compare. For receiving address events, [Address transaction webhooks](https://carbium.sh/library/howsolana/address-transaction-webhooks) covers the receiver side. [Credits meter RPC, WebSocket, stream and webhook work alike](https://carbium.sh/docs#limits), so count webhook traffic in the same budget view as your audit rows.

## SOC 2, peering and residency

SOC 2, VPC peering and regional data residency are contract matters. A script cannot supply them, and they belong in your vendor file with the provider's written answer. Put the same questions to every provider you compare:

- SOC 2: ask for the Type II report, its audit period and its scope. Check that the scope names the RPC service you call.
- Private connectivity: ask whether VPC peering or a private link exists, or whether traffic crosses the public internet over TLS. Carbium serves RPC, WebSocket, the stream and quotes from [one domain under one key](https://carbium.sh/docs#overview), `services.carbium.sh`. Any network-level control beyond that is a question to ask in writing.
- Residency: ask where requests are processed and where the provider keeps its own request logs and key metadata. Chain data is public, so the sensitive material is your request pattern and your keys. Your audit trail sits wherever your database sits, so you choose its region.
- Signed deliveries and retention: ask which headers a webhook carries, how long the provider keeps request logs, and how you get an export for an audit window.

## Where it ends

- Your side only: the trail proves what you sent and received, and says nothing about what happened inside the provider.
- Symmetric key: whoever holds `AUDIT_HMAC_KEY` can rewrite the whole chain and sign it again. Send the latest MAC to a store outside the application's control on a schedule, such as an append-only bucket or the auditor's mailbox.
- Truncation: deleting the newest rows leaves a valid shorter chain. Compare the head and the row count against the externally stored copy.
- Hashed params: a hash proves a match only when you kept the original request. If the audit needs the params themselves, store them in a separate encrypted table keyed by row.
- One writer: two processes on one SQLite file need a single writer or one chain per process. The timestamp comes from the application's clock.
- Chain evidence: to show what a request touched on chain, `getSignaturesForAddress` [reaches back 30 days at most](https://carbium.sh/docs#migrate) from Carbium's own address index, and an empty page past that is the index's age limit. Each signature then costs a `getTransaction`, and both cost [50 cells](https://carbium.sh/docs#rpc). Pass `maxSupportedTransactionVersion: 1` or a v1 transaction answers -32015.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Some calls leave no row in the trail. | A second client was built without the wrapper. Create every client from one factory function, and add a test that makes N calls and counts N new rows. |
| Verification reports a break at the first row after a restart or a deploy. | AUDIT_HMAC_KEY changed since those rows were signed, so the first old row no longer verifies. A replaced or empty database file starts a fresh chain that verifies clean, so a break at the first row points to the secret. Restore the old key, and rotate by starting a new chain with the old head archived. |
| Valid webhook deliveries fail verification. | The receiver verified a parsed and re-serialized body. Sign and verify the raw bytes exactly as received, before any JSON parsing. |
| A receiver rejects every delivery after a host change. | The host clock drifted past the 300 second window. Sync the clock with NTP and log the timestamp difference on each rejection. |
| A burst of transport_error rows appears with 429. | The key went over its rate. Wait the retry-after value, retry once, and cache repeat reads. [The rate-limit watcher](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) tracks these. |
| An evidence fetch answers -32015 or null. | Send maxSupportedTransactionVersion: 1 to getTransaction. A null on an older signature from the address index is expected, so handle it and prove the flow on the newest signatures. |

## Questions

### Does the trail store the API key?

No. The key sits in the transport header and a row holds the method, the params hash, the outcome and the timing. Keep the key out of any extra column you add.

### Can an auditor check the chain without our application?

Yes. With the table, the secret and the field order ts|method|params_sha|outcome|ms|prev, any language can recompute each HMAC and compare it to the stored one.

### Do separate keys per service give separate budgets?

No. Limits are per account and its keys share one budget. Add a service column filled from your own config so the trail attributes each call.

### Is an HMAC enough, or do we need a public-key signature?

An HMAC shows tampering to anyone who holds the secret. For proof to a third party, sign the chain head on a schedule with an asymmetric key kept in a separate system.

### Should rows hold the params in clear?

Hash by default. When an auditor needs the original, store it in a separate encrypted table keyed by the row, so the hash still lets you prove the two belong together.

## Related

- [Address transaction webhooks](https://carbium.sh/library/howsolana/address-transaction-webhooks) (How to use Solana, HS0018)
- [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) (Use cases, UC0001)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
- [carbium.sh/docs#webhooks](https://carbium.sh/docs#webhooks)
- [carbium.sh/docs#overview](https://carbium.sh/docs#overview)
