# Architecture This is the single source of truth for what btcd-lite is made of: the processes, the packages they compose, the data that crosses each boundary, and what is implemented against what is not. Where this file and another disagree, this file wins and the other is a bug. Last reviewed against the code: 2026-12-03. The line counts are non-test Go source at that date; the import graph and the routes were read from the code, not recalled. It states what exists, not what is planned. The design rationale and the budget arithmetic are `docs/PLAN.md`; the test evidence per package is `docs/STATUS.md`; what was copied from where is `docs/SOURCE_AUDIT.md`. Nothing in those three repeats the component map below. ## What the service is One data directory holding both chains, pulled from peers rather than from a node's RPC, serving four things over HTTP: blocks and headers, BIP158 filters, a UTXO set collapsed to a snapshot per retarget with one diff per block, and a relay for client-signed transactions. A second instance can fill from it instead of from the p2p network. The blocks the two chains share are stored once. A body is keyed by its hash and nothing else, because the same block has one height on each chain that carries it: heights live in each chain's header store and bodies live in one store. It never talks to a node's RPC. The only node-facing code is in the gates, where a node is an independent oracle for the tests (`internal/rpc`). ## The two chains | | btc | xbt (the fork) | |---|---|---| | shared prefix | heights 0..961631, one copy of every block body | same | | headers | 80-byte, Bitcoin's rules | 80-byte through 961,639; 164-byte version 2 from 961,640 | | v2 header flag | n/a | `HeaderV2Flag 0x80000000`, height 961640 onward | | target shift | n/a | 22 bits | | coinbase maturity | 100 | 6,480 for a coinbase created at or after 973,440 while the spend height is in 973,440..979,919; 100 again from 979,920 | | genesis, network magic, port | shared with the fork | shared with the parent | `internal/chains` holds both profiles, the fork constants and the maturity rule. The shared prefix is stored once because the store has one key: the block's own hash. There is no refs table and no chain column: a body cannot be duplicated because there is nowhere to write a second one. ## Processes Three binaries plus a narrower puller. All of them read and write the same kind of data directory, so a directory is the unit of state. ### `btcd-lited` - the instance ```mermaid flowchart LR subgraph nets [p2p] N1[btc node] N2[xbt node] end subgraph inst [btcd-lited] D[litedial] H[header sync per chain] F[filler pool per chain] G[staging log per chain] P[process] R[relay] S[service + serve] U[utxo and filter routes] end D --> H H --> F F --> G G --> P P --> ST[(one body store by hash)] H --> HS[(one header store per chain)] R --> N2 S --> ST S --> HS S --> U ``` 1. **Dial.** `litedial.Connect` dials one peer per configured chain and negotiates BIP324 through `internal/v2peer`. The dials happen before any store is opened. 2. **Sync headers.** Each chain's `SyncHeaders` walks that chain's header chain into its own `internal/store` header store, at `headers/`. 3. **Filters.** `internal/filtersync` asks the same peer for the filter headers and then the filters, checks every filter against the hash the fold commits to, and writes the fold into the chain's header store. It runs before the fill because the fill takes the connection; a peer that does not advertise `NODE_COMPACT_FILTERS` is skipped, since asking one is a disconnect. 4. **Fill bodies.** `internal/filler` runs one worker per peer for each chain, one block request in flight per worker, and appends every body it receives to `blocks/staging/`. It hashes nothing and stores nothing: the claim it writes records the height and hash it asked for. A chain can be given several peers (`-peer btc=a,btc=b,...`), and the fill rate scales with the number of them because the walk is round-trip bound. 5. **Process.** `internal/process` walks the staging log, hashes each body against its claim and against the chain's header at that height, and only then files it in the shared body store. `-process-after-fill` (default on) runs it at the end of a fill; `-process-only` runs it against an existing staging directory and dials no peers. 6. **Relay** (only with `-relay`). `internal/relay` dials its own peers, one set per chain, and accepts client transactions over HTTP. 7. **Serve.** `internal/service` answers the chunk contract, `internal/serve` exposes the stores as a header and block source for a neutrino client, and `internal/utxo/serve` serves whatever UTXO dataset is in `/utxo`. The fill is one pass at startup. It does not follow the tip: a node that mines after the instance starts is not seen until the next start. That is a gap, not a design. ### `btcd-lite-serve` - the mirror The same HTTP service without the fill and without the relay, for a host that only holds the data. It builds the dataset: `utxobuild.BuildChains` walks the shared prefix once, then each chain past it, writing a snapshot at every retarget height, one diff per block, and one filter per block. The cadence comes from the chain's `Exported.Retarget` (2016, or 144 under `-regtest`); there is no flag for it. `-utxo=false` skips the build and serves only blocks and headers, and `-rebuild-utxo` rebuilds a dataset that `utxo/built.json` says is current. ### `ftool` - the client `keygen` makes a manifest-signing key, `sync` fills a second data directory's bodies from a service, `utxo` fills one chain's snapshot and diff chain. The client holds the set in memory between snapshots and checks every snapshot it computes against the name the manifest published. `cmd/btcd-lite` is a header-and-block puller with a narrower flag surface than `btcd-lited`: both phases, staging then processing, without the service. ## Packages The import graph, internal only. Arrows point at what is imported. ``` cmd/btcd-lited -> chains filler filterstore litedial logging process relay serve service staging store utxo/serve v2peer cmd/btcd-lite-serve -> chains filterstore logging serve service store utxo/serve utxobuild cmd/ftool -> chains fetch store cmd/btcd-lite -> chains filler process staging store serve -> chunk filterstore manifest service store service -> chunk utxo utxo/store wire fetch -> chunk manifest serve store utxo utxo/store filler -> chains staging store v2peer filtersync -> filterstore store v2peer filterbuild -> filter filterstore store utxo wire process -> serve staging store utxobuild -> filter filterstore store utxo utxo/store wire filterstore -> store relay -> filter store v2peer wire litedial -> v2peer v2peer -> chains store v2peer/authored wirefmt v2peer/authored -> wirefmt utxo/serve -> utxo/store utxo/store -> utxo wire utxo, filter -> wire manifest -> chunk logging -> nothing internal chunk, chains, store, wire, wirefmt, rpc, staging -> nothing internal ``` | package | owns | lines | |---|---|---| | `internal/store` | the append-only blob store (`tail.dat`, key-verified, torn-write repair, format version), the block store over it, and the header store (a full neutrino `Store` with variable-width header records, the per-chain filter-header fold and a dense fold mode for self-built filters) | 1354 | | `internal/relay` | the transaction window, admission, inv/getdata over p2p, the HTTP face for several chains, `Follow`, `Rebroadcast` | 964 | | `internal/utxo/store` | snapshot set files and the index of their names, diff files, the streaming merge, `CutRange`, `LoadDiff`, `WriteSetFile`, `LoadSet`, `Names` | 805 | | `internal/wire` | block and transaction parsing with merkle verification, the 164-byte fork header | 565 | | `internal/service` | the chunk contract: status, chunk ranges, chunk bytes, UTXO query | 561 | | `internal/v2peer` | the connection: BIP324 through btcd's transport, btcd's outbound negotiation, message read and write, header sync, block fetch | 508 | | `internal/filler` | the pool that fills a chain's staging log from peers, one lane per peer | 493 | | `internal/utxo` | the entry type, `ApplyRange`, `BlockTouches`, the diff encode and decode, `CompareOutPoints` | 486 | | `internal/serve` | the multi-chain view behind `service`: blocks by height through each chain's headers, headers out of the bodies, filters by hash, the manifest, the neutrino sources | 429 | | `internal/utxobuild` | the walk that writes snapshots, per-block diffs and filters; `BuildChains` for the shared prefix; the script state a resumed walk continues from | 443 | | `internal/staging` | the append log a fill writes and nothing serves | 370 | | `internal/chains` | the btc and xbt profiles, the fork constants, the maturity rule, the regtest parameters and its network magic | 355 | | `internal/fetch` | the HTTP client: chunk verification, body fill, snapshot and diff fill | 312 | | `internal/utxo/serve` | one chain's UTXO dataset over HTTP: manifest, snapshot, diff runs | 272 | | `internal/manifest` | the signed dataset manifest | 230 | | `internal/chunk` | the seven chunk kinds and the content-addressed name | 221 | | `internal/v2peer/authored` | btcd's outbound handshake, message for message | 179 | | `internal/rpc` | the `bitcoin-cli` vocabulary the gates use; a test oracle, not the product | 149 | | `internal/filter` | BIP158 basic filters, filter hash, filter-header fold | 149 | | `internal/process` | the pass that turns staged bodies into stored blocks | 143 | | `internal/filtersync` | BIP157 filter headers and bodies over the instance's own connection, verified against the fold | 240 | | `internal/filterbuild` | filters computed from bodies, with the scripts of unspent outputs in a sorted file streamed an epoch at a time | 470 | | `internal/logging` | the levelled logger, the request log, the heartbeat and the SIGHUP reopen | 369 | | `internal/filterstore` | filters keyed by block hash, over the blob store | 49 | | `internal/litedial` | the one dialler: context-bounded dial, then the handshake, no leftover deadline | 44 | | `internal/wirefmt` | the plaintext v1 frame, as btcd's `wire` writes it | 39 | ## No script replay Nothing in this tree executes a Bitcoin script. A block is accepted into the store because its header was verified and its bytes hash to the header's commitment, not because its transactions were validated. `internal/wire` parses scripts to find their lengths; `internal/filter` reads every scriptPubKey to build a filter's element set and hashes them; neither runs anything. The one place this shows to a client is coinbase maturity, and it is a rule rather than a number: the set records a coinbase output as unspent from its own block, and the client applies the chain's own schedule. `internal/chains`'s `MaturityRule` carries it, including the fork's long window: 6,480 blocks for a coinbase created at or after 973,440 while the spend height is at or above 973,440 and below 979,920. The reasoning, the numbers and the 68 hours of one core the decision declines are in `docs/PLAN.md`, "No script replay". ## The boundaries Six data shapes cross package lines. Each has exactly one owner. **Chunks.** A `chunk.Kind` over a height range, named by the double SHA-256 of its bytes (`chunk.Name`). Owned by `internal/chunk`. A name is verified by the receiver, never trusted: `internal/serve` cuts a chunk from the stores on request and files it under its own name, and `internal/fetch` re-hashes before it accepts. The kinds in use are `blk`, `hdrs` and `flt`; `fh`, `utxo.diff`, `utxo.base` and `utxo.known` are defined and emitted by nothing, because the filter headers and the UTXO artifacts are served by `internal/utxo/serve` with the names their manifests publish. **Staged bodies.** `[u32 len][bytes]` in `blocks/staging//.dat` and a 44-byte claim per body in `claims.dat`. Owned by `internal/staging`. Written by the filler, read by `internal/process` alone: nothing that serves data may open it, which is the boundary the sync/process split exists to draw. **Bodies.** Bytes keyed by the double SHA-256 of their own header, which is the fork's construction when the header carries the v2 flag. Owned by `internal/store`. A body is chain-neutral; a height is not. **Snapshot sets and diffs.** A canonical set is a sorted file of fixed-width 57-byte entries, named by the double SHA-256 of its entries (`utxo/store.NameOf`). A snapshot at height H is the set after block H. A diff is the net created and spent outpoints of one block, from H-1 to H (`utxo.Diff`). The writer records each snapshot's name in the directory's `index` as it writes it, because naming them by reading them back means a manifest request that reads the whole dataset; the snapshot endpoint still re-hashes what it serves, so a file edited behind the index is caught rather than believed. The merge that turns base plus diffs into the next set streams both once, in one outpoint order (`utxo.CompareOutPoints`) - every sort and every merge in the process uses that one comparison, which is not a style choice: two orders that disagree on one pair is how a checkpoint comes out with the right entries in the wrong sequence. **Filters.** BIP158 basic filters, N=19, M=784931, built from non-OP_RETURN scriptPubKeys plus the prevout scripts of every spend. The filter hash is the double SHA-256; the filter header folds it into the previous one. Owned by `internal/filter`; stored by `internal/filterstore` under the block's hash; the fold's records are the chain's own, in its header store. **The relay window.** Transactions by txid with their state (`internal/relay`). Bounded by bytes, evicting oldest first. A relayed txid answers `announced`, never a claim of acceptance. **The manifest.** An Ed25519-signed list of kinds, ranges and coverage. Owned by `internal/manifest`. ## The transport One code path for p2p, used by the fill, the relay and the gates: `internal/v2peer`. It negotiates BIP324 through btcd's `v2transport` and speaks btcd's `wire` messages above it, with `internal/wirefmt` as the plaintext fallback. `internal/litedial` is the only place a connection is dialled for the instance, so the daemon counts and the tests cannot disagree about the connection. Two things about that dependency are worth knowing before touching it: - btcd's transport, as pinned, drops a peer's first packet if the packet is already buffered when its handshake finishes. Measured, with byte counts, in `docs/upstream/v2transport-garbage-terminator.md`. It does not fire against a node; it fires every time between two btcd peers on loopback. - The instance's regtest network magic is `0xdab5bffa`, which is what the nodes on this machine accept. It is not Bitcoin Core's regtest constant. Pinned by `TestRegtestMagic`. ## The HTTP contract Registered by the code, in three places. ``` GET /v1/status internal/service GET /v1/manifest internal/service GET /v1/chains/{chain}/{kind}/{range} internal/service kind is a chunk.Kind GET /v1/chunks/{name} internal/service POST /v1/chains/{chain}/utxo/query internal/service {"outpoints":[...],"height":H|null} GET /v1/chains/{chain}/utxo/checkpoints internal/service POST /v1/chains/{chain}/tx internal/relay {"tx":"","depends_on":[...]} GET /v1/chains/{chain}/tx/{txid} internal/relay GET /v1/utxo/{chain}/manifest internal/utxo/serve GET /v1/utxo/{chain}/snapshot/{height} internal/utxo/serve a retarget height only GET /v1/utxo/{chain}/diffs/{from}-{to} internal/utxo/serve length-prefixed per-block diffs ``` `{kind}` is `blk`, `hdrs` or `flt`. A chain an instance does not hold is refused with the names of the ones it does. A diff run that crosses a snapshot height is refused; one that ends on it is served. The old `/v1/utxo/manifest`, `/v1/utxo/chunk/{name}`, `/v1/utxo/set/{height}` and `/v1/utxo/diff/{range}` paths are gone: a two-chain instance cannot serve one chain's sets at an unqualified path. Named in earlier drafts of the plan and not routes in the code: `GET /v1/peers`, `GET /v1/manifest/{kind}`, `GET /v1/manifest/{kind}/chunk/{sha256}`, `GET /v1/utxo/canonical/{height}`, `GET /v1/utxo/canonical/{height}/known`. The manifest is one document at `/v1/manifest`. ## Logging Both server commands write through `internal/logging`: `-log-level` (debug, info, warn, error or off, default info), `-log-file` (empty means stderr, and SIGHUP reopens it for a rotation) and `-heartbeat` (default five minutes, 0 disables). `-fill-progress` sets the fill's progress period (default a minute). The level is a runtime decision, not a build one: SIGUSR1 turns debug on and SIGUSR2 puts it back to the level the process started with, each acknowledged by a line that is written whatever the level is. `-log-level off` writes nothing at all, and SIGUSR1 is how a process started that way is turned back on. The p2p path has its own lines, because that is what fails first on a host brought up against a network: ``` info: dial: tcp to 1.2.3.4:8333 in 24ms info: v2peer: up: remote=1.2.3.4:8333 protocol=70016 v2=true agent="/Satoshi:27.0.0/" services=0xc49 height=884213 handshake_ms=31 info: v2peer: headers to 884213, the peer's tip, 884213 headers in 61s info: filler: 412000/984346 (41.9%) 6900 blocks/s, eta 2m18s, 0 failed, 4 workers warn: filler: 1.2.3.4:8333 failed on 412001: v2peer: timeout reading a block info: v2peer: down: remote=1.2.3.4:8333 after=12m3s err=EOF ``` A connection says what it negotiated and what the peer claims before anything is asked of it, the header sync reports every hundred thousand headers with a rate, the fill reports on a timer with a count, a percentage and an estimate (a stall shows as the same count and `eta never`), and the end of a connection says whether the instance closed it or the peer did. The per-block line and the per-request decode line are at debug. A request is logged once, at the level its outcome deserves: a 5xx is an error, a 4xx a warning, a success a debug line, and a success slower than five seconds an info line with `slow` on the end. The line is fixed-field so it can be summed with awk: ``` warn: access: remote=203.0.113.9 method=GET path="/v1/chains/btc/blk/500-510" status=400 bytes=35 dur_ms=0 note="serve: block 500: no header at 500" ``` `note` is the start of a refused or failed response's body, which is why a failure on a host nobody is watching still explains itself. Counters for requests, bytes, refusals and failures feed the heartbeat: ``` info: heartbeat: blocks=106 filters=106 requests=7 bytes_out=1827 refused=3 failed=0 heap_mb=2 goroutines=6 btc_tip=105 btc_snapshot=0 ``` The fill logs a progress line a minute rather than one line per block, which a full prefix would otherwise turn into a million-line log; the per-block line and the header-sync window lines are at debug. ## Instance classes Unchanged from the plan; repeated here because it is what the disk figures are for. A is the canonical holder (bodies, headers, every snapshot and per-block diff, filters); B is a mirror (bodies, headers, optional UTXO); C is a light client (headers and filters it needs, no bodies). Derived sizes are in `docs/PLAN.md`. ## How it is verified Thirty packages, all green under `go test ./...` with the two-chain rig up for the tests that dial it. The node-backed gates in `internal/gate` start their own `bitcoind` - from PATH, or from the rig's install - and skip only when there is none: | gate | proves | |---|---| | `TestDaemonFillsFromANode` | the instance dials, syncs headers, stages and processes bodies from a node | | `TestDaemonFillsFromTheForkNode` | the same for the fork, against the fork's own node build | | `TestOneStoreTwoChains` | two chains over one body store: 22 bodies for 21 shared heights plus one, and height 10 the same through both header stores | | `TestOneInstanceServesBothChains` | one process fills both chains, names both, and serves a shared range as one chunk | | `TestStagingIsNotServed` | a fill with no processing pass stages every body and serves none | | `TestProcessIsSeparate` | `-process-only` stores the bodies with no peer, drains the log, drops a corrupted body and records its height | | `TestUTXOSetMatchesTheNode` | a dataset built from node bodies, coinbase outpoints cross-checked with `gettxout` | | `TestSnapshotFiltersAndFold` | snapshots at 0, 144 and 288 and nowhere else; 301 filters byte-identical to `getblockfilter`; the fold reaches the tip | | `TestClientReachesAnyHeight` | a client fetches the snapshots and reproduces the builder's name at height 200 | | `TestSharedPrefixIsWalkedOnce` | 101 prefix reads plus 200 per chain for two chains of 301 heights | | `TestServedUTXOChainFetches` | instance to serve command to HTTP client, every boundary matching, filters the node's | | `TestRelayAnnouncesToTheNode` | a transaction the node never saw, submitted to the instance, ends up in the node's mempool | | `TestFilterParity` | every regtest block's filters match `getblockfilter` | | `TestSeedFromService`, `TestFToolSync` | a second instance fills from the first by chunk name | The measured cost numbers (merge rates, rebuild time) are in `docs/PLAN.md`; `STATUS.md` records which of them the tests still exercise and which are still estimates. ## What is not built `docs/STATUS.md` is the only list of gaps. This section names just the two that are structural - a boundary the code does not have at all, as opposed to a route or a test that is missing - because those are the ones a reader of the architecture needs to know before they trust a diagram: - **No follow-the-tip loop.** The fill closes when it reaches the tip of a peer, the processing pass runs once, and the process has no polling phase afterwards. A node that mines later is not seen until the next start. - **No branch mode for the UTXO set.** The set is canonical and linear: a diff applies to exactly one base at one height. An earlier plan draft's `utxo.branch` and `utxo.cp` kinds were never built and are not in `internal/chunk`. Everything else - the egress budget, filter sync from a node, incremental dataset builds, rate limiting, the header half of `ftool sync`, the memory-mapped canonical file, the routes from earlier drafts, the alliance network - is listed in `STATUS.md` with what each would need.