Header sync from a CDN
This page shows how to give a new install its block headers without waiting for peers: from a checkpoint your app ships, from a CDN, or both. It also shows how to report the sync’s progress and outcome.
A wallet needs the block header chain to check merkle proofs (SPV). Over P2P, a fresh install fetches it 2,000 headers per round trip, which takes tens of minutes. libspiffy has two faster ways:
- A CDN (
cdnBaseUrl). libspiffy downloads the headers as pre-built 80-byte binary chunks, validates them and bulk-imports them. P2P then fetches only the blocks the CDN does not have yet. - A header checkpoint (
headerCheckpoint, since 5.17.0). Your app ships the network’s newest headers in one file. A fresh install starts its chain there, so it only catches up from the checkpoint’s newest header. With a CDN as well, the older headers are filled in later, in the background.
Turn it on
Section titled “Turn it on”Pass cdnBaseUrl to initialize(), with the two optional callbacks:
// Sketch: storage, ARC and secure-storage arguments omitted.import 'package:libspiffy/libspiffy.dart';
final system = LibSpiffyActorSystem();
await system.initialize( networkType: 'main', enableP2P: true, cdnBaseUrl: 'https://headers.example.com', onHeaderSyncProgress: (int current, int total, CdnSyncPhase phase) { print('headers: ${phase.name} $current/$total'); }, onHeaderSyncResult: (CdnSyncResult result) { if (!result.success) { print('CDN not used (${result.error}); peers supply the headers'); } },);libspiffy builds the URLs from the base URL and the network’s canonical name (NetworkName.canonical):
mainnet, testnet or regtest.
https://headers.example.com/mainnet/manifest.jsonhttps://headers.example.com/mainnet/headers_0000001_0050000.binhttps://headers.example.com/mainnet/headers_0050001_0100000.bin...The base URL must be https. initialize() does not accept a plain http CDN: the sync fails with an
ArgumentError before any request, onHeaderSyncResult reports it, and the headers come from peers.
libspiffy has no default CDN. If you leave cdnBaseUrl out, onHeaderSyncResult is still called
once, with success: false and the error No header CDN configured.
What happens at startup
Section titled “What happens at startup”initialize() runs the CDN sync alongside the rest of its startup
(lib/src/actors/libspiffy_actor_system.dart):
- It opens storage and the header chain, then starts the header sync in the background: first the checkpoint’s headers if you passed one, then the CDN sync.
- It registers event types, starts the projections and spawns the actors.
- It completes
system.ready. From here the coordinator takes commands. - It waits for the header sync to finish.
- If the chain starts at a checkpoint and you passed
cdnBaseUrl, it starts filling in the older headers in the background. - If
enableP2Pis true, it starts P2P. Header sync over P2P continues from the tip of the stored chain. ThestartHeightparameter does not change that: it is only the height this node reports to peers in its version handshake. initialize()returns.
On a first install, step 4 can take minutes. Creating or importing a wallet needs no header chain, so
don’t wait for initialize() to return before you send commands. Wait for ready:
// Sketch: start libspiffy without blocking the caller on the header sync.final started = system.initialize(cdnBaseUrl: cdnUrl, networkType: 'main');await system.ready; // actors take commands// ... create wallets, show the UI ...await started; // CDN sync done, P2P startedA payment whose block header has not arrived yet waits for it in the SPV actor.
system.isReady reads the same state synchronously.
Retries and fallback
Section titled “Retries and fallback”Each chunk download has a 30-second timeout and up to 3 attempts. If a pass still fails, the actor system
starts another pass on a fresh HTTP client, up to three passes in all. Each pass resumes from the tip of
the stored chain, so it does not download again what it already imported. After the third failed pass,
onHeaderSyncResult reports the error and P2P fetches the remaining headers.
A failed CDN sync never fails initialize().
Chunk cache
Section titled “Chunk cache”Chunks are downloaded one at a time: download, validate, import, then the next. If you pass
dataDirectory to initialize(), libspiffy uses it as the chunk cache directory, so a chunk downloaded
before the app was killed is not downloaded again. Without dataDirectory, chunks are held in memory only.
When you pass your own isar, libspiffy uses dataDirectory for nothing else.
Progress and result
Section titled “Progress and result”onHeaderSyncProgress has the type CdnSyncProgressCallback:
void Function(int current, int total, CdnSyncPhase phase). total is the manifest’s total header
count, and current counts headers already in storage, so a resumed sync does not restart at zero.
CdnSyncPhase |
Reported when |
|---|---|
fetchingManifest |
Before manifest.json is fetched (current and total are 0). |
downloadingChunks |
Before each chunk is downloaded or read from the cache. |
validatingChunks |
Before each chunk is validated. |
importingHeaders |
Before each chunk is written to storage. |
complete |
The pass imported every chunk it needed. |
fallbackToP2P |
The pass failed. total is 0. Another pass may follow. |
When storage already holds every header the manifest lists, the pass reports only fetchingManifest and
returns success with 0 headers imported.
onHeaderSyncResult gets one CdnSyncResult for the whole startup sync:
| Field | Type | Meaning |
|---|---|---|
success |
bool |
The last pass imported everything it needed. |
headersImported |
int |
Headers imported by the last pass. |
finalHeight |
int |
Height of the stored chain’s tip afterwards. |
elapsed |
Duration |
Time the last pass took. |
error |
String? |
Why the sync ended without success. |
After startup, system.headerChain.bestHeight is the local tip and system.networkHeight is the highest
height connected peers reported (0 with no peer connected). Compare the two to show “synced”.
Start from a header checkpoint
Section titled “Start from a header checkpoint”Since 5.17.0 you can ship the network’s newest headers with your app and pass them to initialize() as
headerCheckpoint. The file is in libspiffy’s .svhc format; build it with
tool/build_header_checkpoint.dart.
// Sketch: a Flutter app that ships the checkpoint as an asset.import 'package:flutter/services.dart' show rootBundle;import 'package:libspiffy/libspiffy.dart';
final checkpoint = (await rootBundle.load('assets/headers/mainnet.svhc')).buffer.asUint8List();
await system.initialize( networkType: 'main', headerCheckpoint: checkpoint, cdnBaseUrl: 'https://headers.example.com', // optional: fills in the older headers);The lowest header in the file is the checkpoint. What initialize() does with it depends on the header
store (BlockHeaderChain.chooseAnchor):
| Header store | Chain starts at |
|---|---|
| Empty (a fresh install) | The checkpoint. Every header in the file is stored, then the CDN and peers continue from the file’s newest header. |
| Holds the checkpoint’s header at its height | The checkpoint. An install seeded from this file, or an older one, carries on. |
| Holds a header at height 0 | Genesis. An install that synced from genesis keeps its chain. If it has fallen behind the file’s newest header, the file brings it up to there (BlockHeaderChain.extendFromWindow). |
Without headerCheckpoint, the chain starts at genesis, as before 5.17.0.
Storing the file’s headers runs in the background, before the CDN and peers are asked for anything.
HeaderCheckpoint.load decodes and checks the file on another isolate, which takes about a second for
200,000 headers on a laptop. A start that is stopped part way through carries on from the stored tip at
the next start. If the file’s headers can’t be stored, the error is logged and the CDN and peers carry
on from the chain’s stored tip.
The file is trusted as the built-in genesis block is: it ships inside your app. libspiffy still checks that it is whole: the network matches, every header meets its own proof of work, and the last header hashes to the hash written at the end of the file. A file whose first header is at height 0 must start with the network’s genesis block.
What waits for older headers
Section titled “What waits for older headers”A chain that starts at a checkpoint holds no header below it until those headers are filled in. Anything whose merkle proof names an older block waits for its header:
- A received payment whose proof is older than the checkpoint is parked. It is checked when the wallet holds the header at every height its proofs need.
- A restored coin, found by a wallet import or an address scan, is available at once only if its proof checks against a header the wallet holds. Otherwise it is pending, with no height, and its transaction is recorded with its proof but no height. The coin becomes available and the transaction confirmed when the header arrives.
A wallet restored on a fresh install can therefore show older coins as pending until the fill reaches their blocks. Without a CDN to fill them in, they stay pending.
Fill in the headers below the checkpoint
Section titled “Fill in the headers below the checkpoint”With both headerCheckpoint and cdnBaseUrl, once the startup sync is done libspiffy fills in the headers
below the checkpoint from the CDN, newest first, down to genesis. Peers can’t help here: they hand out
headers upwards from a block you know, never down.
Each step fetches the CDN chunk right below the lowest header held: about 50,000 headers, 4 MB. On mainnet that is some 125 MB in all, so let the user decide when it runs:
// Sketch: onWifi() and showBackfill() are your app's own.await system.initialize( networkType: 'main', headerCheckpoint: checkpoint, cdnBaseUrl: 'https://headers.example.com', mayBackfillHeaders: () async => await onWifi(), onHeaderBackfillProgress: (int lowestHeight, int checkpointHeight) { // lowestHeight == 0: every header down to genesis is held. showBackfill(done: checkpointHeight - lowestHeight, of: checkpointHeight); },);initialize() parameter |
Default | Meaning |
|---|---|---|
mayBackfillHeaders |
always allowed | Asked before each step. While it answers false, it is asked again every 5 minutes. |
onHeaderBackfillProgress |
none | Called at the start of the fill and after each step with the lowest height held and the checkpoint’s height. lowestHeight 0 means complete. |
- Retries. A step that fails (no network, the CDN down, a chunk that does not check out) is tried again after 1 minute, doubling up to 30 minutes.
- Restarts. Where the fill stopped is read back from storage, so a restart carries on. Once height 0 is held, the next start anchors the chain at genesis.
- Shutdown ends the fill and any wait.
- Payments. After each step, the SPV actor checks the proofs and parked payments that were waiting for those headers, restored coins among them.
- The tip of the chain is never touched.
The CDN is not trusted. The header you hold names the hash of the one below it, so each run of headers must end on that hash and link all the way down. Every header must meet its own proof of work, and height 0 must be the network’s genesis block. A run that fails a check stores nothing.
If you run the fill yourself, the parts are public: CdnHeaderSyncService.backfillNext() does one step and
returns a CdnBackfillStep, HeaderBackfillRunner repeats it with the waits above, and
BlockHeaderChain.lowestHeldHeight() and BlockHeaderChain.storeBelow(headers, startHeight) read and
extend the chain downwards.
What libspiffy checks
Section titled “What libspiffy checks”The CDN is treated as untrusted transport. Before it writes anything from a chunk, libspiffy checks:
- Integrity: the chunk’s SHA-256 matches the manifest.
- Anchoring: on an empty store without a checkpoint, the first header is the network’s genesis block,
built into the code (
NetworkParams). Otherwise the first new header links to the stored tip. - Continuity: each header’s
prevBlockis the hash of the one before it. - Proof of work: each header’s hash meets its own target, and that target is no easier than the
network’s
powLimit. - Checkpoints: block hashes match the manifest’s checkpoints. These come from the same server as the headers, so a match proves nothing alone; a mismatch rejects the chunk.
A CDN can’t make the wallet accept headers that peers would not.
Configuration reference
Section titled “Configuration reference”initialize() builds a CdnHeaderSyncConfig itself, with the default values below. You can’t pass one
to initialize(). The class matters when you run CdnHeaderSyncService yourself
(lib/src/spv/cdn_header_sync_config.dart).
| Parameter | Default | Meaning |
|---|---|---|
baseUrl |
required | CDN base URL. |
network |
required | testnet, mainnet or regtest. Also selects genesis and powLimit. |
downloadTimeout |
30 s | Timeout per chunk download. |
maxRetries |
3 | Attempts per chunk. |
validateProofOfWork |
true |
Check each header’s proof of work. Turn off only for synthetic test data. |
verifyCheckpoints |
true |
Compare against the manifest’s checkpoints. |
allowInsecureHttp |
false |
Allow an http base URL, for a local test CDN. |
onProgress |
null |
Progress callback. |
cacheDirectory |
null |
Directory for the chunk cache. |
libspiffy 5.0.0 removed concurrentDownloads, which nothing read: chunks are validated in sequence.
Drop it from any CdnHeaderSyncConfig you build.
Build the CDN files
Section titled “Build the CDN files”libspiffy’s repository has two tools in tool/. Both write the same layout: manifest.json plus
headers_SSSSSSS_EEEEEEE.bin chunks of 50,000 headers by default. Chunks start at height 1, since the
genesis block is built into the library.
From WhatsOnChain’s published header files:
dart run tool/fetch_woc_headers_to_cdn.dart \ --network mainnet \ --output /path/to/cdn/mainnetIt also takes --cache (default <output>/.woc-cache), --chunk-size and --reorg-margin (default 100).
It checks genesis, linkage and proof of work before it writes, and leaves out the newest --reorg-margin
blocks so a tip that is later reorganised away never reaches the CDN.
From a block_headers.json backup file:
dart run tool/export_headers_to_cdn.dart \ --source /path/to/block_headers.json \ --output /path/to/cdn/testnet \ --network testnet \ --chunk-size 50000This one writes a checkpoint every 100,000 blocks into the manifest.
Upload the output directory to any static file server under <base>/<network>/. Each .bin file is raw
80-byte headers back to back. A CDN that is a few days behind is fine: peers supply the rest. Rebuild and
upload to keep the P2P catch-up short.
Build a checkpoint file
Section titled “Build a checkpoint file”tool/build_header_checkpoint.dart builds a .svhc file from the CDN files above:
dart run tool/build_header_checkpoint.dart \ --cdn /path/to/cdn/mainnet \ --network mainnet \ --output build/checkpoint/mainnet.svhc \ --window 200000Before it writes anything, it checks the whole chain from the genesis block built into the library: each
chunk’s SHA-256 against the manifest, the link from every header to the one before it, and every header’s
proof of work. It then writes the newest --window headers (default 200,000). A fresh install that starts
from the file trusts exactly what an install that synced from genesis would have.
The file stores the first header whole and each later header in 48 bytes, since prevBlock is rebuilt
from the header before it. 200,000 mainnet headers take 9.6 MB. The CDN files leave out the newest
--reorg-margin blocks, so the file’s newest header is already buried; the app catches up from it over
P2P. Rebuild the file for each release of your app to keep that catch-up short.
Regtest
Section titled “Regtest”For a regtest chain (such as localnet-teranode) you usually leave
cdnBaseUrl unset and let peers supply the short chain. If your app picks its settings from the
network, pass null for cdnBaseUrl whenever NetworkName.isRegtest(networkType) is true.
See also
Section titled “See also”- Running libspiffy in a background isolate: forwarding progress to the UI.
- Network, ARC and peers:
startHeight, peers and seeds. - API reference:
CdnHeaderSyncService.