// Package serve answers what the body store and the header stores hold, through // the chunk contract the service speaks. // // It is the read side of a filled instance and the first half of the seeding // path: an instance that holds blocks can hand them to another one in chunks // the other verifies by name. It is a view over the stores on every call, so a // chunk is cut from the bytes that are there now, not from a snapshot that can // drift from the store. // // One view holds any number of chains over one body store. A body is keyed by // its hash and nothing else: the same block has one height on each chain that // carries it, so a height is resolved through the chain's own header store and // never through the bodies. package serve import ( "crypto/ed25519" "encoding/binary" "encoding/hex" "fmt" "sort" "strings" "sync" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/chunk" "git.smesh.lol/btcd-lite/internal/filterstore" "git.smesh.lol/btcd-lite/internal/manifest" "git.smesh.lol/btcd-lite/internal/service" "git.smesh.lol/btcd-lite/internal/store" ) // BlocksPerChunk is the plan's `blk` budget in blocks: a hundred blocks, which // at a megabyte each is a hundred-megabyte answer. const BlocksPerChunk = 100 // HeadersPerChunk is the plan's `hdrs` budget in headers. At 164 bytes a // header it is a 1.6 MB answer. const HeadersPerChunk = 10000 // View serves the chains' blocks and headers from the stores. type View struct { // Headers is one header store per chain, keyed by the chain's name. Headers map[string]*store.HeaderStore // Bodies holds every chain's blocks by hash. Bodies *store.BlockStore // Filters holds the chains' filters by block hash. Nil means the view // serves no filters, which is what an instance that has not built them // does. Filters *filterstore.Store // Key signs the published manifest. Nil means the view publishes none. Key ed25519.PrivateKey mu sync.Mutex chunks map[string]chunk.Chunk } // New returns a view over the given header stores and body store. func New(headers map[string]*store.HeaderStore, bodies *store.BlockStore) *View { return &View{Headers: headers, Bodies: bodies, chunks: map[string]chunk.Chunk{}} } // ChainNames returns the chains the view holds, sorted. func (v *View) ChainNames() []string { names := make([]string, 0, len(v.Headers)) for name := range v.Headers { names = append(names, name) } sort.Strings(names) return names } // Status implements service.Chunks: the coverage the stores hold. func (v *View) Status() service.Status { s := service.Status{Chains: map[string]service.Chain{}} for name, headers := range v.Headers { if tip, _, ok := headers.HeaderTip(); ok { s.Chains[name] = service.Chain{Start: 0, Tip: tip} } } if v.Bodies != nil { s.Blocks = uint64(v.Bodies.Len()) } if v.Filters != nil { s.Filters = uint64(v.Filters.Len()) } return s } // Range implements service.Chunks. // // The chunks are cut from the blocks the store holds at request time. A block // the store does not have stops the range: a chunk with a hole in it is a // chunk the client cannot verify against its headers, so the instance says how // far it got rather than pretending. func (v *View) Range(kind chunk.Kind, chainName string, from, to uint32) ([]chunk.Chunk, error) { headers, ok := v.Headers[chainName] if !ok { return nil, fmt.Errorf("serve: this instance holds %s, not %q", strings.Join(v.ChainNames(), ","), chainName) } switch kind { case chunk.Blocks: return v.blockRange(chainName, headers, from, to) case chunk.Headers: return v.headerRange(chainName, headers, from, to) case chunk.Filters: return v.filterRange(chainName, headers, from, to) } return nil, fmt.Errorf("serve: %s is not served from these stores", kind) } func (v *View) blockRange(chainName string, headers *store.HeaderStore, from, to uint32) ([]chunk.Chunk, error) { var raw []byte var heights []uint32 for h := from; h < to; h++ { b, err := v.blockAt(headers, h) if err != nil { return nil, fmt.Errorf("serve: block %d: %w", h, err) } raw = binary.LittleEndian.AppendUint32(raw, uint32(len(b))) raw = append(raw, b...) heights = append(heights, h) } var out []chunk.Chunk at := 0 for i := 0; i < len(heights); i += BlocksPerChunk { end := min(i+BlocksPerChunk, len(heights)) startBytes := at for j := i; j < end; j++ { n := int(binary.LittleEndian.Uint32(raw[at:])) at += 4 + n } out = append(out, chunk.Chunk{Kind: chunk.Blocks, Chain: chainName, From: heights[i], To: heights[end-1] + 1, Raw: raw[startBytes:at]}) } v.remember(out) return out, nil } // blockAt reads the body at a height on a chain: the header store is the // height-to-hash index and the body store holds the bytes. func (v *View) blockAt(headers *store.HeaderStore, h uint32) ([]byte, error) { hdr, ok := headers.Header(h) if !ok { return nil, fmt.Errorf("no header at %d", h) } return v.Bodies.GetBlock(hdr.BlockHash()) } // headerRange cuts a run of raw headers for one chain. // // A header is the first 80 bytes of its block, or the first 164 when the // block's first four bytes carry the fork's v2 flag, so the serving path reads // it out of the body whenever the body is stored. The body is the authority // for the bytes; the header store is the authority for height to hash. It also // cannot hold the fork's form: it stores neutrino's 80-byte header struct and // refuses a record that serialises wider than that, so a v2 header has no // second copy to disagree with. // // Where the body is absent the header comes from the header store, which is // the chain the instance verified before the bodies arrived. That path answers // the 80-byte form only, which is the only form a header store can hold. func (v *View) headerRange(chainName string, headers *store.HeaderStore, from, to uint32) ([]chunk.Chunk, error) { var out []chunk.Chunk var raw []byte have := from width := 0 flush := func(upto uint32) { out = append(out, chunk.Chunk{Kind: chunk.Headers, Chain: chainName, From: have, To: upto, Raw: raw}) raw = nil width = 0 have = upto } for h := from; h < to; h++ { rec, ok := v.headerAt(headers, h) if !ok { break } if width != 0 && (len(rec) != width || len(raw)+len(rec) > HeadersPerChunk*width) { flush(h) } width = len(rec) raw = append(raw, rec...) } if len(raw) > 0 { flush(have + uint32(len(raw)/width)) } if len(out) == 0 { return nil, fmt.Errorf("serve: headers %d-%d are not held", from, to) } v.remember(out) return out, nil } // headerAt returns one header's wire bytes for a chain, from the body when the // body is stored and from the header store otherwise. func (v *View) headerAt(headers *store.HeaderStore, h uint32) ([]byte, bool) { hdr, ok := headers.Header(h) if !ok { return nil, false } if v.Bodies != nil { if raw, err := v.Bodies.GetBlock(hdr.BlockHash()); err == nil { if n := headerWidth(raw); n > 0 && n <= len(raw) { return raw[:n], true } } } // No body: the header store's own record, at whatever width the header // is. A version 2 header is 164 bytes there too, because the store keeps // each record's length. enc := hdr.SerializeAll() return enc, len(enc) > 0 } // headerWidth is the width a block's header has, read from its own first four // bytes: the fork's v2 flag widens it, and nothing else does. func headerWidth(raw []byte) int { if len(raw) >= btcwire.BlockHeaderV2Size && binary.LittleEndian.Uint32(raw[:4])&btcwire.HeaderV2Flag != 0 { return btcwire.BlockHeaderV2Size } if len(raw) >= btcwire.BlockHeaderSize { return btcwire.BlockHeaderSize } return 0 } // FiltersPerChunk is the plan's `flt` budget in filters. const FiltersPerChunk = 1000 // filterRange cuts a run of filters for one chain. // // A filter is keyed by its block's hash, so the bytes a chain serves for a // shared height are the bytes the other chain serves, and both chains resolve // the height through their own header store. func (v *View) filterRange(chainName string, headers *store.HeaderStore, from, to uint32) ([]chunk.Chunk, error) { if v.Filters == nil { return nil, fmt.Errorf("serve: this instance holds no filters") } var raw []byte var heights []uint32 for h := from; h < to; h++ { hdr, ok := headers.Header(h) if !ok { break } f, err := v.Filters.Get(hdr.BlockHash()) if err != nil { return nil, fmt.Errorf("serve: filter %d: %w", h, err) } raw = binary.LittleEndian.AppendUint32(raw, uint32(len(f))) raw = append(raw, f...) heights = append(heights, h) } if len(heights) == 0 { return nil, fmt.Errorf("serve: filters %d-%d are not held", from, to) } var out []chunk.Chunk at := 0 for i := 0; i < len(heights); i += FiltersPerChunk { end := min(i+FiltersPerChunk, len(heights)) startBytes := at for j := i; j < end; j++ { n := int(binary.LittleEndian.Uint32(raw[at:])) at += 4 + n } out = append(out, chunk.Chunk{Kind: chunk.Filters, Chain: chainName, From: heights[i], To: heights[end-1] + 1, Raw: raw[startBytes:at]}) } v.remember(out) return out, nil } // remember files chunks in the view so Get can answer for the chunks it cut. func (v *View) remember(chunks []chunk.Chunk) { v.mu.Lock() defer v.mu.Unlock() for _, c := range chunks { v.chunks[c.Name().String()] = c } } // Get implements service.Chunks. func (v *View) Get(name string) (chunk.Chunk, bool) { v.mu.Lock() defer v.mu.Unlock() c, ok := v.chunks[name] return c, ok } // Manifest implements service.Chunks. The view cuts chunks on request from the // stores, so its inventory is the coverage Status reports and not a list of // chunk names. // // With a signing key it publishes a manifest of that coverage: one block run // per chain, cut by the same rules the range endpoint uses, so a client that // reads the manifest and a client that asks for a range see the same chunks. // Without a key the view publishes nothing and a client that pins a key cannot // be served from it. func (v *View) Manifest() ([]byte, bool) { if v.Key == nil { return nil, false } names := v.ChainNames() if len(names) == 0 { return nil, false } m, err := manifest.New(strings.Join(names, ","), v.Key) if err != nil { return nil, false } added := false for _, name := range names { st := v.Status() cov, ok := st.Chains[name] if !ok { // No header tip: there is no height-to-hash index, so no block // range can be cut or named. The bodies alone are not an // inventory, because a body has a height only on a chain. continue } if cov.Tip < cov.Start { continue } // The status names heights the chain holds; a run is half-open, so the // end is one past the last height it holds. end := cov.Tip + 1 bl, err := v.blockRange(name, v.Headers[name], cov.Start, end) if err != nil { continue } got := make([]string, len(bl)) for i, c := range bl { got[i] = c.Name().String() } if err := m.Add(chunk.Blocks, name, cov.Start, end, got); err != nil { return nil, false } added = true } if !added { return nil, false } canon, err := m.Canonical() if err != nil { return nil, false } sig := ed25519.Sign(v.Key, canon) m.Signature = hex.EncodeToString(sig) raw, err := m.Encode() if err != nil { return nil, false } return raw, true } // HeaderHash is the hash a block's own header commits to, honouring the fork's // 164-byte form. It is what a client of this service checks a block chunk // against, and it is here so a caller does not reimplement it. func HeaderHash(raw []byte) chainhash.Hash { if len(raw) >= 4 && binary.LittleEndian.Uint32(raw[:4])&btcwire.HeaderV2Flag != 0 && len(raw) >= btcwire.BlockHeaderV2Size { var h btcwire.BlockHeader if err := h.DeserializeV2(raw[:btcwire.BlockHeaderV2Size]); err == nil { return h.BlockHash() } } return chainhash.DoubleHashH(raw[:80]) }