How to make one instance hold both chains, store the shared prefix once, build one filter per body and one canonical UTXO set for the pre-fork history, and split the fill into a download phase and a processing phase.
This is the execution plan for the two design sections in docs/PLAN.md, "The
second copy of every block" and "Sync, then process". It is not a restatement of
them: it names the files to change, the order to change them in, and the test
that proves each step.
Executed. All six phases are in main, with the gates below run against
nodes; docs/STATUS.md carries what each one measured. The section "Where this
landed" at the end records every point where the implementation differs from
what this document first said, and why. The document is left in its original
form above that section except where a statement was wrong about the system
rather than about the work, which is corrected in place and marked.
The two chains share 961,631 of 984,346 blocks. Today a data directory holds one chain, keyed by network magic, so running both chains costs two copies of that prefix in bodies, two full walks for the UTXO spine, and two instances to serve. The blocks are identical bytes with identical hashes, so the second copy is pure duplication. At the derived sizes that is 555.8 GB, 98 checkpoint rebuilds and the whole spine walk, spent twice.
A body is identified by its hash, and by nothing else. A block's height is a property of a chain, not of the block: the same body has one height on btc and one on xbt, and after the fork a chain has heights no other chain has. So the block store keeps bodies by hash, and every height-to-hash mapping lives in that chain's header store, which already exists and already holds exactly that.
Verification is not part of the download. Bytes arriving from a peer are untrusted; they become a stored block only when a separate pass has hashes them against the header chain. Until then they sit in a staging log that nothing serves. This lets the network run at line rate and puts all hashing, indexing, filtering and UTXO work in a second pass that is restartable and movable.
<data>/
blocks/
00000000.blk .. append-only bodies, 4-byte length prefix each
00000000.bidx .. hash -> (file, offset, length), 44 bytes per record
tail.dat newest durable index record
format the on-disk version, currently 1
staging/ phase-1 append log and its (height, hash) claims
headers/
btc/ headers.dat fheaders.dat the chain, and its filter-header fold
xbt/ headers.dat fheaders.dat
filters/
by-block/ filter bytes keyed by block hash, shared by both chains
utxo/
canonical/ one canonical set per checkpoint height, shared prefix
spent-btc/ spent-xbt/ per-chain spent index
post-btc/ post-xbt/ post-fork sets
diff/ checkpoint diffs that are served
headers/<chain>/ and utxo/<chain>/ are per chain. blocks/ and
filters/by-block/ are shared, because their keys are block hashes and a block
hash names the same bytes on either chain.
The change is small and everything else depends on it.
What changes in `internal/store/blockstore.go`:
blockHdrSize goes from 8 to 4: the record header keeps the length and dropsthe network field. A store that holds both chains cannot stamp one magic on every record, and the magic was only ever a guard against mixing, which the hash already provides.
NewBlockStore(dir string, network uint32) becomes NewBlockStore(dir string). The callers are cmd/btcd-lited, cmd/btcd-lite-serve, cmd/btcd-lite and
internal/fetch; each drops the argument.
PutBlock(hash, raw, height) becomes PutBlock(hash, raw) and stops recording a height. The heights map[int32]chainhash.Hash and the order
slice go with it.
GetBlockByHeight(height int32) is deleted. Callers that need a block at a height resolve it through the header store: hashAt(height) already exists in
internal/filler and internal/serve needs the same three lines.
Point 4 fixes a latent bug rather than introducing a change. GetBlockByHeight
resolves through s.order[height] after a reopen, because loadIndex sets every
block's Height to -1. order is append order, so the fallback is only
correct when one chain appended in height order. In a shared store it is wrong,
and it is already wrong today for an interrupted fill that resumed out of order.
Migration. A store written before this change has 8-byte record headers and a network in every one. Two options, and the plan takes the second (it is what the code does):
new one. Correct, and it touches 570 GB for the privilege.
peers, the flag -allow-old-blockstore does not exist, and a store that
silently misreads a record header is worse than one that says so. The refusal
names the version it found and the one this build writes.
The store's open path gains a version byte in a format file, and refuses a
directory whose version is not the current one, naming the reason.
Gate 1. TestOneStoreTwoChains: fill heights 0..20 of btc and 0..20 of xbt
into one directory; assert BlockStore.Len() is 21, not 42; assert that height
10 resolves to the same hash from both header stores; assert that a reopen finds
21 blocks and both chains' tips.
Corrected premise. Two independent regtest nodes cannot share a prefix: they
agree on genesis and on nothing above it, so a fixture that started two from
scratch would hold two bodies at every height and would prove nothing about the
store. The gate starts the second node with -connect so it syncs the first
one's 21 heights, fills the first chain to that tip, and only then mines the
second node's own block, which the second chain carries and the first does not.
That is a real shared prefix: 21 shared heights, 22 bodies.
What changes:
cmd/btcd-lited and cmd/btcd-lite-serve open headers/<chain> instead of headers, and take -chains btc,xbt (default both) instead of a single
-chain. -chain stays as an alias for a single-entry list.
internal/serve's View stops carrying one Chain string. It carries a map of chain name to *store.HeaderStore, one shared *store.BlockStore, and a
per-chain headerSize. New(chainName, headers, bodies, headerSize) becomes
New(chains map[string]*store.HeaderStore, bodies *store.BlockStore, sizes map[string]int).
View.Range's chain check goes from "is this my one chain" to "is this one of my chains". View.Status reports every chain it holds.
internal/filler takes a chain name and that chain's header store, and writes bodies with PutBlock(hash, raw). Its hashAt reads the header store
it was given, so one pool per chain and one shared body store.
internal/service's UTXO wiring already takes a chain name per source; itbecomes a loop.
Gate 2. TestOneInstanceServesBothChains: one btcd-lited -chains btc,xbt
against both rig nodes; GET /v1/status names both chains; a block chunk for
heights 0..5 of btc and the same range of xbt are byte-identical, which is
what "one copy" means; GET /v1/chains/xbt/blocks/0-5 does not 404.
A block's bytes begin with its header: 80 bytes, or 164 when the first four bytes carry the fork's v2 flag. So the serving path does not need a second copy of any header that it already holds a body for: locate the body by hash, read the prefix.
Why it is not only a saving. The header store held neutrino's
btcwire.BlockHeader as a fixed 80-byte record, which cannot represent the
fork's 164-byte form: PutHeaders refused a record that serialised wider, so
an xbt chain above the fork could not be stored at all, and an instance
started with -header-size 164 could not serve a single header. The stored body
can, because it has the bytes.
Corrected scope. Serving from bodies is not enough on its own: the header store is the height-to-hash index, so a chain whose headers it cannot hold has no heights. The store's records are now variable width, each with its own length prefix, so a v2 header is stored and read back at 164 bytes and the body stays the authority for what is served. That change is in phase 1's commit.
What changes:
internal/serve's headerRange reads the header out of bodies.GetBlock(hash) where the body is stored, and takes the length from
the header's own first four bytes rather than from v.HeaderSize. The body is
the authority for the bytes; the header store is the authority for `height ->
hash`.
now, and only the 80-byte form can be served from there. An xbt header above the fork height with no body is a gap, reported as one rather than served wrong.
-header-size stops affecting what is served. It stays only where a storeneeds to know the record size it will write, and the serving path derives it.
HeaderSource in internal/serve/sources.go keeps reading theheader store: a client syncing headers from an instance wants the chain the instance verified, which exists before the bodies do.
Gate 3. TestHeadersComeFromBodies: serve a range whose bodies are stored and
assert the bytes equal the first 80 of each body; then serve a range with no
bodies and assert the fallback still answers for an 80-byte chain; then, with a
164-byte body fixture in internal/serve, assert the served record is 164 bytes
and hashes to the fork construction. The last of those is a unit test with a
fixture, because no node on this machine produces post-fork xbt blocks; the
node-backed version arrives when one does.
Nothing builds filters today. This phase adds the thing the plan promises and puts it where the consolidation makes it free.
What is added:
internal/filterstore: Put(hash, filter), Get(hash), keyed by block hash,one segment file plus an index, the same shape as the block store and the same torn-tail rule.
and writes it once. Both chains read it.
Corrected: not the processing pass. A BIP158 filter includes the
scriptPubKey of every output a block spends, and a block does not carry
those: they belong to outputs created by earlier blocks. The process pass
sees one body at a time and could not answer for a later block's spend. The
build is in the UTXO walk (internal/utxobuild), which is the only place
that holds the scripts, and it drops each script as it is spent. Filters are
therefore built wherever the UTXO dataset is built, in the same pass.
fheaders.dat inside each chain's header store, because the fold is over that chain's own sequence of
heights. store.HeaderStore already carries the neutrino methods for them,
and the pass writes them through the chain's header store. The new package
holds filters only, keyed by block hash.
service.View.Range gains chunk.Filters: it reads filters for the heightsof the requested chain, resolving heights through that chain's header store.
Gate 3. TestFiltersAreBuiltAndServed: fill 20 blocks, run the processing
pass, assert every height of both chains has a filter, assert the filter for a
shared height is byte-identical whichever chain asked, and assert
GET /v1/chains/btc/filters/0-20 hashes to the chunk name the status reports.
Against a node, TestFilterParity already checks the bytes; this checks that the
product produces them.
The UTXO side is where the arithmetic is largest and the code is least ready.
Snapshot cadence is the chain's retarget interval, taken from
chains.Chain.Exported.Retarget (2016 on btc, 144 on regtest), not a
-spacing flag. A full canonical snapshot exists at every height that is a
multiple of it.
Between snapshots, one diff per block. Not one diff per range. A diff for height H describes what block H created and spent, and applies to the set at H-1.
What changes:
internal/utxobuild gains Interval() from the chain profile and writes a snapshot whenever height % interval == 0, and a diff for every height in
between. Config.Spacing goes; Config.Interval and Config.SnapshotEvery
are the same number, so there is one field.
utxo/diff/<chain>/<height> is the touch list of exactly one block. utxo/store.LoadDiff(dir, from, to) stays the range
reader and a per-block diff is the degenerate range h-1..h, which is how
the files are named. The shared prefix's diffs are written once, under
utxo/diff/shared; the range form is what the serve command concatenates
into one run.
internal/utxo/serve gains GET /v1/utxo/snapshot/{height}, which serves only a retarget height and answers a 404 naming the nearest one otherwise,
and GET /v1/utxo/diffs/{from}-{to}, which serves a run of per-block diffs
and refuses a run that crosses a snapshot.
internal/utxo/store.MergeRange stays as it is: a per-block diff is thedegenerate range of one block, and the merge already handles that, which the buffer and ordering fixes in this session established.
the per-chain part starts at SharedLastHeight. Since 961,632 is a multiple
of 2016, the last shared snapshot is at 959,616 and the 15 heights after it
are a shared diff run to 961,632, which is the first height whose header form
can differ.
What this buys, and what it costs. A client can name the set at any height:
snapshot at floor(H/interval)*interval, then at most interval-1 per-block
diffs, fetched in chunks of a hundred. That is the property the old
one-diff-per-10,000-block design could not offer without a rebuild on the client
side. The cost is that there are five times as many snapshots as a 10,000-block
cadence would have. docs/PLAN.md carries the derived arithmetic and says
plainly that it replaces the old 3.62 TB figure only after a measurement.
The index question is unchanged. Answering "is this outpoint unspent at
height H on chain X" from one canonical set plus a spent index needs the index
ordered by (outpoint, height) for a boundary lookup. Per-block diffs make that
query expressible at every height; they do not by themselves make it fast. If
the ordered index turns out to cost more than it is worth, the fallback is a
scan bounded by the epoch, at most 2016 diffs, which is affordable for a
single outpoint and not for a set.
Gate 4. Three tests:
TestSnapshotOnRetargetHeights: build over a regtest chain whose interval is144; assert a snapshot exists at 0, 144, 288 and nowhere between; assert the diff of a single block applies and reproduces the next height's snapshot name when that block is a retarget height.
TestClientReachesAnyHeight: start at a snapshot, fetch per-block diffs inchunks, and assert the set name at every height of the epoch matches the chain's own.
TestSharedPrefixIsWalkedOnce: instrument the walk, assert the block count is SharedLastHeight + 1 + postForkBodies, not twice the prefix. This one needs
a synthetic SharedLastHeight for regtest, as the last section notes.
The last phase, and it is independent of 1 to 4: it can land before them without conflict, and it is the one that changes the fill's throughput.
Phase 1 of the fill (download). internal/filler writes to
blocks/staging/<chain>/, one directory per chain because a claim's height is a
height on one chain:
staging/<seg>.dat: [u32 len][bytes], nothing else. No hash, no index.staging/claims.dat: [u32 seg][u32 height][u32 len][32 hash] per body, inappend order, so the process pass knows which height and hash each body was meant to be without re-deriving it. The segment field is not in the first draft of this list: without it a claim does not say which segment file its body is in, and the offset within the segment would have to be re-derived from the roll rule.
getdata shape and its per-peer lanes. What it stops doing is calling headerHash and PutBlock inside the loop.
Phase 2 of the fill (process). A new internal/process: walk claims.dat
and staging/<seg>.dat in step, hash each body, compare to the claimed hash and
to the header chain's hash at that height, and only then call
blocks.PutBlock(hash, raw), filterstore.Put, and hand the block to the UTXO
builder. A body that fails is dropped and its height is recorded in
blocks/missing for the next sync to request again.
Where it runs. btcd-lited -process-after-fill (default on) runs it at the
end of the fill. -process-only runs it against an existing staging directory
and no peers, which is the configuration that lets a thin-pipe host pull and a
big machine process.
The trust boundary, made explicit in code. blocks/staging is never read by
internal/serve, internal/service, internal/fetch or the UTXO builder. Only
internal/process reads it. That is the property the whole split rests on: the
unverified bytes are not reachable from any serving path.
Gate 6. Two tests:
TestStagingIsNotServed: with a staging directory full of bodies and no processing pass, /v1/status reports zero blocks and a block request 404s.
TestProcessIsSeparate: pull 20 blocks with -process-after-fill=false, assert the block store is empty and staging holds 20 bodies; then run
-process-only, assert the block store holds 20 and staging is drained. Then
corrupt one body's claimed hash and assert that height lands in missing and
is not stored.
| phase | depends on | unblocks | risk |
|---|---|---|---|
| 1 block store | nothing | 2, 3, 4, 5 | a format change; old directories must re-fill |
| 2 headers and view | 1 | 3, 4, 5 | touches every command's flags |
| 3 headers from bodies | 1, 2 | serving xbt headers at all | small, and it closes a live bug |
| 4 filters | 1, 2 | serving filters, the plan's promise | new store, new code path |
| 5 UTXO | 1, 2 | arbitrary-height queries, one spine walk | the largest, with a named fallback |
| 6 sync/process | nothing | fill throughput, movable processing | changes the fill's failure modes |
Phase 1 first because everything else assumes a chain-neutral store. Phase 6 can
go in parallel with 2 to 5 if two people are working; it touches
internal/filler and a new package only.
Phase 3 is worth doing early and cheaply even though it depends on 1 and 2: it is the smallest change in the list and it is the difference between an xbt instance that serves its own headers and one that cannot.
Truncate;the staging log and the processing pass assume the header chain they walked is the one that stays. A reorg during processing is a re-run of the pass, which is correct because a pass is idempotent per block, and is not optimised.
blocks are its own, and they go in the same hash-keyed store. There is nothing to collapse there.
utxo.base stays a full canonical set per checkpoint, and utxo.known stays unused. The consolidation is storage-side.
carrying two formats.
SharedLastHeight at regtest scale, so phase 5's shared-prefix walk can be tested without the
real 961,631 blocks. Today's regtest chains share genesis and are both
shorter than the fork height, so "shared prefix" in a test means "the whole
chain", which is enough for phases 1 to 4 and not for 5. Phase 5's gate may
need a synthetic SharedLastHeight for the test, and that constant is a
package variable used by the test only, not a build flag. Phase 3's 164-byte
header test has the same problem and takes a fixture instead.
internal/gate can start two nodes in one test. Every gate starts onetoday; the two-chain gates need two, on two ports, with two datadirs.
ExportedChain.Retarget already carries 2016 for btc and 144 for regtest, so
phase 5 reads it there; a regtest chain of 300 blocks gets snapshots at 0, 144
and 288, which is enough to test the cadence.
Each phase is a commit on main, in the order the plan gave, and the deviations
below are the ones a reader of the plan would otherwise be misled by.
As planned: 4-byte record header, NewBlockStore(dir), PutBlock(hash, raw),
GetBlockByHeight and PutHeight deleted, a format file whose version is
refused when it is not this build's. Two things went beyond the plan:
.blk, not the layout sketch's 00000000.blk versus the old .fdb: the extension changed with the format, so a directory
cannot be half old and half new by accident;
time, because phase 3's premise (serve headers out of bodies) did not fix the reason xbt could not hold its own chain. See phase 3 below.
The generic core was then extracted into store.BlobStore, which the block
store and the filter store both use. That is not in the plan and is what keeps
the two stores from being two copies of the same torn-tail logic.
As planned, with three changes of shape:
serve.New takes map[string]*store.HeaderStore and one body store, not a map of names, stores and sizes: -header-size stopped affecting what is
served once headers came from bodies, so a size per chain had nothing left to
say;
-peer and -relay take chain=host:port entries, because a two-chaininstance fills from two nodes and an address alone does not say which chain it serves. A bare address is accepted only when the instance holds one chain;
(relay.Multi), because one mux cannot take the same pattern twice and a
second mux would put the chains on different addresses.
UTXO endpoints became chain-scoped: /v1/utxo/<chain>/{manifest,chunk,set,diff}
and /v1/chains/<chain>/utxo/{query,checkpoints}. The plan did not name their
shape, and a two-chain instance cannot serve one chain's sets at an unqualified
path.
As planned, and the header store's records became variable width (see phase 1).
The consequence is that the fallback path can now serve a 164-byte record too,
so "only the 80-byte form can be served from there" no longer holds. The
internal/serve fixture that serves a 164-byte chain from the store is a test,
not a node-backed gate: no node on this machine produces post-fork xbt blocks.
As planned for the store and the serving path, and corrected for the build: the filters are built in the UTXO walk, not in the processing pass, because the scripts they need are there. Concretely:
internal/filterstore is a store.BlobStore with filters keyed by block hash; dense mode (PutFilterHeaderRecord), which is needed because neutrino's fold
starts from a filter anchor a self-built chain does not have;
chain's header store, because the filters are the same and the folds are per-chain records;
chunk.Filters is served by service.View, cut at 1,000 filters per chunk;every fold record commits to its filter's hash.
As planned for the cadence and the artifacts, with these deviations:
block H is the step from H-1 to H, so the files are diff-<H-1>-<H>.dat. The
plan said "a diff for height H ... applies to the set at H-1", which this
naming follows;
utxo/canonical and its diffs to utxo/diff/shared; a chain's own go to utxo/chain-<name> and
utxo/diff/<name>. The plan's layout had utxo/canonical as "one canonical
set per checkpoint height, shared prefix" and utxo/diff/<chain>/<height>
without a shared directory; the shared directory is what stops the prefix's
diffs being written twice;
set-<h>.dat and does not merge a range to reach one: the walk holds the set, and the old merge was the walk's
own arithmetic run twice. utxo/store.MergeRange stays, and is the primitive
a client that cannot hold the set uses;
Build returns the set it ended with, so a chain's walk continues from theshared walk's state instead of reloading a snapshot and replaying an epoch;
/v1/utxo/<chain>/snapshot/<h> and /v1/utxo/<chain>/diffs/<from>-<to>, the latter as length-prefixed records
that refuse to cross a snapshot. This does change the chunk contract for the
UTXO side, which the plan listed as a non-goal: a snapshot is named in the
manifest and served with that name in its X-Set-Name and ETag, so a
utxo.base chunk name would add nothing a client does not already check, and
a run of per-block diffs has no single name to be chunked under. The kinds
utxo.diff, utxo.base and utxo.known remain defined and are now emitted
by nothing;
SharedLastHeight of 100 overa 301-height chain, as the plan allowed, and counts block reads rather than instrumenting the walk: 101 prefix reads plus 200 per chain.
The index question is unchanged and still open: answering "is this outpoint
unspent at height H" quickly needs an index ordered by (outpoint, height),
which does not exist. Per-block diffs make the question expressible at every
height; the bounded scan is still the fallback.
Some gates landed under more than one test name, because one assertion needed a node and another did not:
| gate in this plan | test |
|---|---|
| Gate 1 | TestOneStoreTwoChains |
| Gate 2 | TestOneInstanceServesBothChains, plus TestOneBodyStoreTwoChains in internal/serve for the same claim without a process |
| Gate 3 | TestHeadersServed, TestHeaderFallsBackToTheStore, TestForkHeaderServedAt164 |
| Gate 4 (filters) | TestSnapshotFiltersAndFold, TestFiltersSharedByChains, TestServedUTXOChainFetches |
| Gate 4 (snapshots) | TestSnapshotFiltersAndFold |
TestClientReachesAnyHeight | same name |
TestSharedPrefixIsWalkedOnce | same name |
| Gate 6 | TestStagingIsNotServed, TestProcessIsSeparate |
As planned, with per-chain staging directories and the segment field in a claim.
-process-after-fill (default on) and -process-only are on btcd-lited;
cmd/btcd-lite runs both phases in one go. A dropped body is recorded in
blocks/missing/<chain>.log rather than a single blocks/missing file, because
the height is a height on one chain.
The build as it stands holds the canonical set in memory, plus a map of every unspent script, because a filter needs the scriptPubKey of each output a block spends. That is 4 GB for the entries alone and 10 to 14 GB for the scripts, which is why the 3 TB VPS cannot build the dataset although it can fill the bodies.
The fix is not a bigger box. It is that the script belongs in the set and the set belongs on disk, so the build streams an epoch at a time:
a parallel [outpoint][len][script] table sorted by outpoint beside each
snapshot. The parallel table leaves utxo.Entry, the diff format, fetch and
utxo/serve untouched, and is the smaller change.
utxobuild stops walking with a set in memory. Per epoch it merges theprevious snapshot against that epoch's per-block diffs, writes the next snapshot, and emits each block's filter where the block ends.
epoch's spends by outpoint with the height that spent them. A spent entry's script goes to the block that spent it as the streams pass.
independent of the chain's length.
Gate: build a 300-block regtest chain two ways, with the in-memory walk and with
the epoch merge, and require every filter byte and every snapshot name to match;
then build with a memory ceiling (debug.SetMemoryLimit or a ulimit) low enough
that the old path fails and the new one passes. That second half is the claim:
the bound moved, not the arithmetic.
The measured consequence is in docs/PLAN.md, "Filters from a disk-resident
set": snapshots grow by about 40 percent to roughly 1.4 TB.
Also built for the set. utxobuild.BuildStream walks one epoch at a time:
it reads the epoch's blocks to learn what they spend and create, streams the
snapshot the epoch starts at to resolve those spends, then applies the blocks in
order against that overlay, writing each block's diff and merging the epoch's end
state into the next snapshot with MergeRangeFrom. The set is never in memory, so
the 4 GB figure stops being a requirement. The gate builds 301 blocks both ways
and requires every snapshot file and every diff to be identical; the two-chain
gate requires a fork chain to read no prefix beyond the snapshot boundary below
the fork.
Filters, in the parallel-table shape. internal/filterbuild writes a sorted
[outpoint][len][script] table per epoch, joins the epoch's spends against it in
one streamed pass, emits each block's filter and fold, then rewrites the table
without the spent entries and with the epoch's creations. The set builder no
longer touches filters or scripts at all. The byte-equality half of the gate is
done and passes against a node; the memory-ceiling half is not.