serve.go raw

   1  // Package serve answers what the body store and the header stores hold, through
   2  // the chunk contract the service speaks.
   3  //
   4  // It is the read side of a filled instance and the first half of the seeding
   5  // path: an instance that holds blocks can hand them to another one in chunks
   6  // the other verifies by name. It is a view over the stores on every call, so a
   7  // chunk is cut from the bytes that are there now, not from a snapshot that can
   8  // drift from the store.
   9  //
  10  // One view holds any number of chains over one body store. A body is keyed by
  11  // its hash and nothing else: the same block has one height on each chain that
  12  // carries it, so a height is resolved through the chain's own header store and
  13  // never through the bodies.
  14  package serve
  15  
  16  import (
  17  	"crypto/ed25519"
  18  	"encoding/binary"
  19  	"encoding/hex"
  20  	"fmt"
  21  	"sort"
  22  	"strings"
  23  	"sync"
  24  
  25  	"git.smesh.lol/nostrino/pkg/btcwire"
  26  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  27  
  28  	"git.smesh.lol/btcd-lite/internal/chunk"
  29  	"git.smesh.lol/btcd-lite/internal/filterstore"
  30  	"git.smesh.lol/btcd-lite/internal/manifest"
  31  	"git.smesh.lol/btcd-lite/internal/service"
  32  	"git.smesh.lol/btcd-lite/internal/store"
  33  )
  34  
  35  // BlocksPerChunk is the plan's `blk` budget in blocks: a hundred blocks, which
  36  // at a megabyte each is a hundred-megabyte answer.
  37  const BlocksPerChunk = 100
  38  
  39  // HeadersPerChunk is the plan's `hdrs` budget in headers. At 164 bytes a
  40  // header it is a 1.6 MB answer.
  41  const HeadersPerChunk = 10000
  42  
  43  // View serves the chains' blocks and headers from the stores.
  44  type View struct {
  45  	// Headers is one header store per chain, keyed by the chain's name.
  46  	Headers map[string]*store.HeaderStore
  47  	// Bodies holds every chain's blocks by hash.
  48  	Bodies *store.BlockStore
  49  	// Filters holds the chains' filters by block hash. Nil means the view
  50  	// serves no filters, which is what an instance that has not built them
  51  	// does.
  52  	Filters *filterstore.Store
  53  	// Key signs the published manifest. Nil means the view publishes none.
  54  	Key ed25519.PrivateKey
  55  
  56  	mu     sync.Mutex
  57  	chunks map[string]chunk.Chunk
  58  }
  59  
  60  // New returns a view over the given header stores and body store.
  61  func New(headers map[string]*store.HeaderStore, bodies *store.BlockStore) *View {
  62  	return &View{Headers: headers, Bodies: bodies, chunks: map[string]chunk.Chunk{}}
  63  }
  64  
  65  // ChainNames returns the chains the view holds, sorted.
  66  func (v *View) ChainNames() []string {
  67  	names := make([]string, 0, len(v.Headers))
  68  	for name := range v.Headers {
  69  		names = append(names, name)
  70  	}
  71  	sort.Strings(names)
  72  	return names
  73  }
  74  
  75  // Status implements service.Chunks: the coverage the stores hold.
  76  func (v *View) Status() service.Status {
  77  	s := service.Status{Chains: map[string]service.Chain{}}
  78  	for name, headers := range v.Headers {
  79  		if tip, _, ok := headers.HeaderTip(); ok {
  80  			s.Chains[name] = service.Chain{Start: 0, Tip: tip}
  81  		}
  82  	}
  83  	if v.Bodies != nil {
  84  		s.Blocks = uint64(v.Bodies.Len())
  85  	}
  86  	if v.Filters != nil {
  87  		s.Filters = uint64(v.Filters.Len())
  88  	}
  89  	return s
  90  }
  91  
  92  // Range implements service.Chunks.
  93  //
  94  // The chunks are cut from the blocks the store holds at request time. A block
  95  // the store does not have stops the range: a chunk with a hole in it is a
  96  // chunk the client cannot verify against its headers, so the instance says how
  97  // far it got rather than pretending.
  98  func (v *View) Range(kind chunk.Kind, chainName string, from, to uint32) ([]chunk.Chunk, error) {
  99  	headers, ok := v.Headers[chainName]
 100  	if !ok {
 101  		return nil, fmt.Errorf("serve: this instance holds %s, not %q", strings.Join(v.ChainNames(), ","), chainName)
 102  	}
 103  	switch kind {
 104  	case chunk.Blocks:
 105  		return v.blockRange(chainName, headers, from, to)
 106  	case chunk.Headers:
 107  		return v.headerRange(chainName, headers, from, to)
 108  	case chunk.Filters:
 109  		return v.filterRange(chainName, headers, from, to)
 110  	}
 111  	return nil, fmt.Errorf("serve: %s is not served from these stores", kind)
 112  }
 113  
 114  func (v *View) blockRange(chainName string, headers *store.HeaderStore, from, to uint32) ([]chunk.Chunk, error) {
 115  	var raw []byte
 116  	var heights []uint32
 117  	for h := from; h < to; h++ {
 118  		b, err := v.blockAt(headers, h)
 119  		if err != nil {
 120  			return nil, fmt.Errorf("serve: block %d: %w", h, err)
 121  		}
 122  		raw = binary.LittleEndian.AppendUint32(raw, uint32(len(b)))
 123  		raw = append(raw, b...)
 124  		heights = append(heights, h)
 125  	}
 126  	var out []chunk.Chunk
 127  	at := 0
 128  	for i := 0; i < len(heights); i += BlocksPerChunk {
 129  		end := min(i+BlocksPerChunk, len(heights))
 130  		startBytes := at
 131  		for j := i; j < end; j++ {
 132  			n := int(binary.LittleEndian.Uint32(raw[at:]))
 133  			at += 4 + n
 134  		}
 135  		out = append(out, chunk.Chunk{Kind: chunk.Blocks, Chain: chainName,
 136  			From: heights[i], To: heights[end-1] + 1, Raw: raw[startBytes:at]})
 137  	}
 138  	v.remember(out)
 139  	return out, nil
 140  }
 141  
 142  // blockAt reads the body at a height on a chain: the header store is the
 143  // height-to-hash index and the body store holds the bytes.
 144  func (v *View) blockAt(headers *store.HeaderStore, h uint32) ([]byte, error) {
 145  	hdr, ok := headers.Header(h)
 146  	if !ok {
 147  		return nil, fmt.Errorf("no header at %d", h)
 148  	}
 149  	return v.Bodies.GetBlock(hdr.BlockHash())
 150  }
 151  
 152  // headerRange cuts a run of raw headers for one chain.
 153  //
 154  // A header is the first 80 bytes of its block, or the first 164 when the
 155  // block's first four bytes carry the fork's v2 flag, so the serving path reads
 156  // it out of the body whenever the body is stored. The body is the authority
 157  // for the bytes; the header store is the authority for height to hash. It also
 158  // cannot hold the fork's form: it stores neutrino's 80-byte header struct and
 159  // refuses a record that serialises wider than that, so a v2 header has no
 160  // second copy to disagree with.
 161  //
 162  // Where the body is absent the header comes from the header store, which is
 163  // the chain the instance verified before the bodies arrived. That path answers
 164  // the 80-byte form only, which is the only form a header store can hold.
 165  func (v *View) headerRange(chainName string, headers *store.HeaderStore, from, to uint32) ([]chunk.Chunk, error) {
 166  	var out []chunk.Chunk
 167  	var raw []byte
 168  	have := from
 169  	width := 0
 170  	flush := func(upto uint32) {
 171  		out = append(out, chunk.Chunk{Kind: chunk.Headers, Chain: chainName,
 172  			From: have, To: upto, Raw: raw})
 173  		raw = nil
 174  		width = 0
 175  		have = upto
 176  	}
 177  	for h := from; h < to; h++ {
 178  		rec, ok := v.headerAt(headers, h)
 179  		if !ok {
 180  			break
 181  		}
 182  		if width != 0 && (len(rec) != width || len(raw)+len(rec) > HeadersPerChunk*width) {
 183  			flush(h)
 184  		}
 185  		width = len(rec)
 186  		raw = append(raw, rec...)
 187  	}
 188  	if len(raw) > 0 {
 189  		flush(have + uint32(len(raw)/width))
 190  	}
 191  	if len(out) == 0 {
 192  		return nil, fmt.Errorf("serve: headers %d-%d are not held", from, to)
 193  	}
 194  	v.remember(out)
 195  	return out, nil
 196  }
 197  
 198  // headerAt returns one header's wire bytes for a chain, from the body when the
 199  // body is stored and from the header store otherwise.
 200  func (v *View) headerAt(headers *store.HeaderStore, h uint32) ([]byte, bool) {
 201  	hdr, ok := headers.Header(h)
 202  	if !ok {
 203  		return nil, false
 204  	}
 205  	if v.Bodies != nil {
 206  		if raw, err := v.Bodies.GetBlock(hdr.BlockHash()); err == nil {
 207  			if n := headerWidth(raw); n > 0 && n <= len(raw) {
 208  				return raw[:n], true
 209  			}
 210  		}
 211  	}
 212  	// No body: the header store's own record, at whatever width the header
 213  	// is. A version 2 header is 164 bytes there too, because the store keeps
 214  	// each record's length.
 215  	enc := hdr.SerializeAll()
 216  	return enc, len(enc) > 0
 217  }
 218  
 219  // headerWidth is the width a block's header has, read from its own first four
 220  // bytes: the fork's v2 flag widens it, and nothing else does.
 221  func headerWidth(raw []byte) int {
 222  	if len(raw) >= btcwire.BlockHeaderV2Size && binary.LittleEndian.Uint32(raw[:4])&btcwire.HeaderV2Flag != 0 {
 223  		return btcwire.BlockHeaderV2Size
 224  	}
 225  	if len(raw) >= btcwire.BlockHeaderSize {
 226  		return btcwire.BlockHeaderSize
 227  	}
 228  	return 0
 229  }
 230  
 231  // FiltersPerChunk is the plan's `flt` budget in filters.
 232  const FiltersPerChunk = 1000
 233  
 234  // filterRange cuts a run of filters for one chain.
 235  //
 236  // A filter is keyed by its block's hash, so the bytes a chain serves for a
 237  // shared height are the bytes the other chain serves, and both chains resolve
 238  // the height through their own header store.
 239  func (v *View) filterRange(chainName string, headers *store.HeaderStore, from, to uint32) ([]chunk.Chunk, error) {
 240  	if v.Filters == nil {
 241  		return nil, fmt.Errorf("serve: this instance holds no filters")
 242  	}
 243  	var raw []byte
 244  	var heights []uint32
 245  	for h := from; h < to; h++ {
 246  		hdr, ok := headers.Header(h)
 247  		if !ok {
 248  			break
 249  		}
 250  		f, err := v.Filters.Get(hdr.BlockHash())
 251  		if err != nil {
 252  			return nil, fmt.Errorf("serve: filter %d: %w", h, err)
 253  		}
 254  		raw = binary.LittleEndian.AppendUint32(raw, uint32(len(f)))
 255  		raw = append(raw, f...)
 256  		heights = append(heights, h)
 257  	}
 258  	if len(heights) == 0 {
 259  		return nil, fmt.Errorf("serve: filters %d-%d are not held", from, to)
 260  	}
 261  	var out []chunk.Chunk
 262  	at := 0
 263  	for i := 0; i < len(heights); i += FiltersPerChunk {
 264  		end := min(i+FiltersPerChunk, len(heights))
 265  		startBytes := at
 266  		for j := i; j < end; j++ {
 267  			n := int(binary.LittleEndian.Uint32(raw[at:]))
 268  			at += 4 + n
 269  		}
 270  		out = append(out, chunk.Chunk{Kind: chunk.Filters, Chain: chainName,
 271  			From: heights[i], To: heights[end-1] + 1, Raw: raw[startBytes:at]})
 272  	}
 273  	v.remember(out)
 274  	return out, nil
 275  }
 276  
 277  // remember files chunks in the view so Get can answer for the chunks it cut.
 278  func (v *View) remember(chunks []chunk.Chunk) {
 279  	v.mu.Lock()
 280  	defer v.mu.Unlock()
 281  	for _, c := range chunks {
 282  		v.chunks[c.Name().String()] = c
 283  	}
 284  }
 285  
 286  // Get implements service.Chunks.
 287  func (v *View) Get(name string) (chunk.Chunk, bool) {
 288  	v.mu.Lock()
 289  	defer v.mu.Unlock()
 290  	c, ok := v.chunks[name]
 291  	return c, ok
 292  }
 293  
 294  // Manifest implements service.Chunks. The view cuts chunks on request from the
 295  // stores, so its inventory is the coverage Status reports and not a list of
 296  // chunk names.
 297  //
 298  // With a signing key it publishes a manifest of that coverage: one block run
 299  // per chain, cut by the same rules the range endpoint uses, so a client that
 300  // reads the manifest and a client that asks for a range see the same chunks.
 301  // Without a key the view publishes nothing and a client that pins a key cannot
 302  // be served from it.
 303  func (v *View) Manifest() ([]byte, bool) {
 304  	if v.Key == nil {
 305  		return nil, false
 306  	}
 307  	names := v.ChainNames()
 308  	if len(names) == 0 {
 309  		return nil, false
 310  	}
 311  	m, err := manifest.New(strings.Join(names, ","), v.Key)
 312  	if err != nil {
 313  		return nil, false
 314  	}
 315  	added := false
 316  	for _, name := range names {
 317  		st := v.Status()
 318  		cov, ok := st.Chains[name]
 319  		if !ok {
 320  			// No header tip: there is no height-to-hash index, so no block
 321  			// range can be cut or named. The bodies alone are not an
 322  			// inventory, because a body has a height only on a chain.
 323  			continue
 324  		}
 325  		if cov.Tip < cov.Start {
 326  			continue
 327  		}
 328  		// The status names heights the chain holds; a run is half-open, so the
 329  		// end is one past the last height it holds.
 330  		end := cov.Tip + 1
 331  		bl, err := v.blockRange(name, v.Headers[name], cov.Start, end)
 332  		if err != nil {
 333  			continue
 334  		}
 335  		got := make([]string, len(bl))
 336  		for i, c := range bl {
 337  			got[i] = c.Name().String()
 338  		}
 339  		if err := m.Add(chunk.Blocks, name, cov.Start, end, got); err != nil {
 340  			return nil, false
 341  		}
 342  		added = true
 343  	}
 344  	if !added {
 345  		return nil, false
 346  	}
 347  	canon, err := m.Canonical()
 348  	if err != nil {
 349  		return nil, false
 350  	}
 351  	sig := ed25519.Sign(v.Key, canon)
 352  	m.Signature = hex.EncodeToString(sig)
 353  	raw, err := m.Encode()
 354  	if err != nil {
 355  		return nil, false
 356  	}
 357  	return raw, true
 358  }
 359  
 360  // HeaderHash is the hash a block's own header commits to, honouring the fork's
 361  // 164-byte form. It is what a client of this service checks a block chunk
 362  // against, and it is here so a caller does not reimplement it.
 363  func HeaderHash(raw []byte) chainhash.Hash {
 364  	if len(raw) >= 4 && binary.LittleEndian.Uint32(raw[:4])&btcwire.HeaderV2Flag != 0 && len(raw) >= btcwire.BlockHeaderV2Size {
 365  		var h btcwire.BlockHeader
 366  		if err := h.DeserializeV2(raw[:btcwire.BlockHeaderV2Size]); err == nil {
 367  			return h.BlockHash()
 368  		}
 369  	}
 370  	return chainhash.DoubleHashH(raw[:80])
 371  }
 372