library / Blockchain ideas / BI0034
Blockhash relay for offline signers
Solana has no blockhash subscription, so a relay builds one: each slotSubscribe tick triggers getLatestBlockhash at confirmed, and the result lands in a file with its expiry height, ready to carry to a signer that has no network.
Subscribing to a blockhash
The standard WebSocket methods cover slots, accounts, logs, signatures and programs. A blockhash has no subscription of its own, and the optional blockSubscribe, which most nodes leave off, would carry each block's hash at a much heavier cost, so the slot tick stays the light choice. A tick is slotSubscribe: it sends one notification per slot, and each notification is a cue to ask getLatestBlockhash for the newest value. The relay below does exactly that and writes what it learns to a file.
Since the Alpenglow switch a slot is about 200 ms, so the stream can tick five times a second and the blockhash changes nearly as often. A signer rarely needs that rate, so the relay fetches at most once per interval (one second by default) and ignores the ticks in between. The ticks still do real work: they keep the relay tied to the chain's own pace, and a stream that goes silent shows up as update lines that stop coming.
The builders who want this are the ones with a signing key on a machine that cannot reach the network: a hardware wallet driven from an air-gapped laptop, a treasury signer in a locked segment, a kiosk that only reads QR codes. Every transaction they sign needs a recent blockhash inside the message, and the signer cannot fetch one. The networked side can. The relay sits there and keeps a fresh value on disk.
What the signer gets
Each update replaces one small JSON file. The signing side reads it, checks the age, builds the message and signs.
| Field | Where it comes from | What the signer does with it |
|---|---|---|
| blockhash | value.blockhash from getLatestBlockhash | goes into the transaction message as its lifetime |
| lastValidBlockHeight | value.lastValidBlockHeight from the same call | the last block height at which the transaction can still land |
| blockHeight | getBlockHeight, called in the same round | where the chain was when the relay looked |
| blocksLeft | lastValidBlockHeight minus blockHeight | the signer's budget for carrying the message back |
| slot | the context slot of the blockhash reply | a cross-check against a clock or a second relay |
| fetchedAt | the relay's clock when the file was written | the age check the signer runs before it signs |
A blockhash stays usable for about 150 blocks. At 200 ms a block that is roughly half a minute, and blocksLeft starts a little under that. The two calls in a round land at slightly different moments, so blocksLeft is an estimate that can be off by a block or two.
The build
The relay is one file on @solana/kit and what Node 24 ships. It is read-only: no private key, nothing sent.
- Open one WebSocket to wss://services.carbium.sh with the key as ?api-key= and send slotSubscribe. The reply carries the subscription id, or an error when the subscription is refused.
- On each slotNotification, count it and check the clock. If less than one interval has passed since the last fetch, or a fetch is still running, do nothing.
- Otherwise call getLatestBlockhash and getBlockHeight together over https://services.carbium.sh, with the key in x-api-key. Both settle on their own, so one failing call does not hide the other.
- When the blockhash differs from the last one written, build the record, write it to latest.json.tmp and rename it over latest.json. A reader never sees half a file.
- Print one line per update with the blockhash, the slot, the blocks left, the ticks seen and the MiB received.
- When the socket closes, print its close code and reason, reconnect after two seconds and subscribe again.
// BI0034 · Blockhash relay for offline signers// https://carbium.sh/library/blockchainideas/blockhash-relay-for-offline-signers// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";import { renameSync, writeFileSync } from "node:fs";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1);}const OUT = process.env.RELAY_FILE ?? "latest.json";const EVERY_MS = Number(process.env.RELAY_EVERY_MS ?? 1000); // at most one fetch round per intervalconst WS_URL = `${process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh"}/?api-key=${key}`;const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);let busy = false;let lastFetch = 0;let lastHash = "";let ticks = 0;let bytes = 0;const why = (e: unknown) => (e instanceof Error ? e.message : String(e));async function publish(): Promise<void> { busy = true; try { const [hash, height] = await Promise.allSettled([ rpc.getLatestBlockhash({ commitment: "confirmed" }).send(), rpc.getBlockHeight({ commitment: "confirmed" }).send(), ]); if (hash.status === "rejected") { console.error("getLatestBlockhash failed:", why(hash.reason)); return; } if (height.status === "rejected") console.error("getBlockHeight failed:", why(height.reason)); const { blockhash, lastValidBlockHeight } = hash.value.value; if (blockhash === lastHash) return; lastHash = blockhash; const now = height.status === "fulfilled" ? height.value : null; const record = { blockhash, lastValidBlockHeight: String(lastValidBlockHeight), blockHeight: now === null ? null : String(now), blocksLeft: now === null ? null : Number(lastValidBlockHeight - now), slot: String(hash.value.context.slot), fetchedAt: new Date().toISOString(), }; writeFileSync(`${OUT}.tmp`, JSON.stringify(record)); renameSync(`${OUT}.tmp`, OUT); // a reader never sees half a file console.log(`${record.fetchedAt} ${blockhash} slot ${record.slot} blocks left ${record.blocksLeft} (${ticks} ticks, ${(bytes / 2 ** 20).toFixed(3)} MiB)`); } finally { busy = false; }}function connect(): void { const ws = new WebSocket(WS_URL); ws.onopen = () => ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "slotSubscribe" })); ws.onmessage = (ev) => { const text = String(ev.data); bytes += Buffer.byteLength(text); const msg = JSON.parse(text); if (msg.id === 1) { console.log(msg.error ? `subscribe refused: ${msg.error.message}` : `subscribed, id ${msg.result}`); return; } if (msg.method !== "slotNotification") return; ticks++; if (busy || Date.now() - lastFetch < EVERY_MS) return; lastFetch = Date.now(); void publish(); }; ws.onerror = (ev) => console.error("socket error:", "message" in ev ? String(ev.message) : "no detail"); ws.onclose = (ev) => { console.error(`socket closed, code ${ev.code}, reason "${ev.reason}"; reconnecting in 2 s`); setTimeout(connect, 2000); };}connect();
run: CARBIUM_KEY=<YOUR_KEY> node main.ts
The relay asks for confirmed in both calls, which suits a 150-block window because the value is as fresh as the signer can use. Solana commitment levels covers the defaults and the three levels in detail.
One slot can be skipped without a notification, so the tick count has gaps. The interval check absorbs that: the next tick after a gap triggers the fetch as usual. If the stream stops entirely, the file keeps its last value and fetchedAt stops moving, which is what the signer's age check catches.
Carrying it across the gap
The relay ends at a file. How the file reaches the signer decides how many blocks are left when signing starts.
- A QR code shown on the networked machine and scanned by the signer. Seconds, and no storage on the signer.
- A USB stick or SD card. Tens of seconds if someone walks it over, which is already most of the window.
- A serial or one-way data link into the signer's segment. Fast and automatable, and the relay file is the only thing that crosses.
- A shared folder that a one-way sync copies into the locked segment. The sync lag adds to the age, so read fetchedAt on arrival.
Whatever the channel, the signer subtracts the record's age (now minus fetchedAt, divided by about 200 ms) from blocksLeft and refuses the record when what is left is fewer blocks than signing and the return trip need. It signs, and the signed bytes travel the opposite way to a networked machine, which submits them through any RPC. sendTransaction costs 20 cells without preflight and 70 with it. After submission, Transaction status check shows how to follow the signature to its result.
What it costs
The subscription is billed in credits. A slot subscription opens at 5 credits, the lightest tier, then costs 20 credits per MiB sent. The relay prints the MiB it has received, so the real figure is on screen after a minute of running. Every update also makes two RPC calls, and those draw on the same account budget as everything else under your keys.
| RELAY_EVERY_MS | Update rounds per hour | RPC calls per hour |
|---|---|---|
| 1000 (default) | up to 3,600 | up to 7,200 |
| 2000 | up to 1,800 | up to 3,600 |
| 5000 | up to 720 | up to 1,440 |
Rounds are an upper bound because the relay waits for a tick, and a tick can arrive up to a slot late, so the relay's own update lines come out about 1.1 s apart at the default interval. An unchanged blockhash skips only the file write: both calls are still made. A slow signing workflow does not need the one-second default, so pick the interval from how many blocks the signer needs left when it starts signing.
Limits are per account, so other tools on the same keys share the budget. Free carries 5 sockets and the relay uses one. The relay prints a failed call and tries again on the next tick, and the previous file stays in place, so a signer sees an older but honest fetchedAt.
Where it ends
- The window is about half a minute. The relay keeps the value fresh and cannot stretch it. A handoff that takes minutes or hours needs a durable nonce account: its stored nonce replaces the blockhash, the first instruction advances it, and the value is read with getAccountInfo at 10 cells a call.
- A blockhash at confirmed can, in rare cases, belong to a block on a fork that is dropped. A transaction built on it is then rejected as unknown. The fix is to sign again with the next value.
- blocksLeft comes from two calls at two instants, so it is an estimate within a block or two.
- One relay serves any number of signers because it holds one value, but every signer that takes the same blockhash signs transactions with the same lifetime. That is fine for transactions that differ in content and wrong for two copies of one transaction, where the second is dropped as already processed.
- The file proves nothing about itself. The cluster checks the blockhash when the transaction lands, and the signer has no way to confirm the value is genuine other than comparing two relays.
- The relay is read-only and has no signing or sending in it. Submitting the signed bytes is a separate job on a networked machine.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The subscribe reply is an error, or the socket closes straight away. | Check CARBIUM_KEY and that the account is under its socket cap (Free carries 5). A refused attempt costs nothing. An unknown key gets a 401 at the door, so attach the whole key. The relay prints the close code and reason before each reconnect, so the failure shows on the console. |
| latest.json stops changing but the relay is still running. | The socket may have died quietly or the calls are failing. Read the console: the relay prints each failed call, and the tick count in the update line should grow. Restart it if the ticks stopped. |
| The signed transaction is rejected as a blockhash not found. | The signer took longer than the window. Check blocksLeft at signing time, shorten the carry path or move to a durable nonce account, and sign again with a fresh record. |
| getLatestBlockhash answers 429. | Widen RELAY_EVERY_MS and check what else on the account is calling, since the limit is shared across its keys. The relay keeps the last good file and tries again on the next tick. |
| A second copy of one transaction is dropped as already processed. | Both copies had the same message, the same blockhash and the same signing key, so they carry the same signature. Add something that differs, such as a memo, or give each signer its own transaction content. |
Questions
Is there a WebSocket method that pushes the latest blockhash?
No. Solana has no blockhash subscription. The relay uses slotSubscribe as the tick and fetches the blockhash with getLatestBlockhash when a tick arrives.
How long does a blockhash stay valid?
About 150 blocks, which at 200 ms a block is roughly half a minute. The lastValidBlockHeight field gives the exact last block height at which a transaction using it can still land.
Can I use finalized instead of confirmed?
Yes, change the commitment in both calls. Finalized now sits at most a block behind confirmed, so you lose little freshness, and the signer's budget shrinks by about that much.
Do I need a relay if the signer can reach the network once?
No. A signer that can make one call just calls getLatestBlockhash itself. The relay is for signers that never touch the network, where something else must bring the value to them.
Can I serve the file over HTTP instead of carrying it?
Yes, add a small HTTP server on the networked side, but a signer that fetches over HTTP is no longer offline. For a signer that must stay offline, let the server feed a one-way push, such as a data diode or a serial sender, into the locked segment. The relay writes the file and does not care what reads it.