// Package blockcache is a disk cache of raw blocks for a sidecar that serves them. // // Blocks are the one piece of chain data a relay cannot hold: a block is a megabyte or more // and the relay's event budget is a hundred kilobytes. So the sidecar keeps them on disk and // serves them over HTTP, from the cache when it has the block and from its node when it does // not, and a client asks the cache before it asks the tunnel. // // The cache is bounded and evicts the oldest entry first. Oldest is the order things were // stored, which is close enough to height: a sidecar that starts at the tip stores the tip // first and works in the same direction the chain grew. When the bound is reached the oldest // block goes, so what a 10 GiB cache holds is the newest 10 GiB of blocks, which is where the // requests are. // // Nothing here is a consensus decision and nothing here is trusted by a client: the block is // committed by its own header, and a client that fetches one hashes it and compares the result // with the header it already accepted. package blockcache import ( "encoding/hex" "encoding/json" "errors" "fmt" "os" "path/filepath" "strings" "sync" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // DefaultMaxBytes is the cache bound when none is configured: ten gibibytes, which is about // ten thousand mainnet blocks and several times that on a chain of smaller blocks. const DefaultMaxBytes = 10 << 30 // indexName is the file the entry list lives in. const indexName = "index.json" // Config is what the cache is opened with. type Config struct { // Dir is where the blocks and the index live. It is created if it does not exist. Dir string // MaxBytes bounds the cache. Zero means DefaultMaxBytes. MaxBytes int64 // Logf receives one line per eviction; nil discards them. Logf func(string, ...any) } // entry is one cached block in insertion order. type entry struct { Chain string `json:"chain"` Hash string `json:"hash"` Bytes int64 `json:"bytes"` } // Cache is a bounded on-disk block store. type Cache struct { cfg Config mu sync.Mutex entries []entry bytes int64 open bool } // Open creates or loads the cache and evicts down to the bound. func Open(cfg Config) (*Cache, error) { if strings.TrimSpace(cfg.Dir) == "" { return nil, errors.New("blockcache: no directory") } if cfg.MaxBytes <= 0 { cfg.MaxBytes = DefaultMaxBytes } if cfg.Logf == nil { cfg.Logf = func(string, ...any) {} } if err := os.MkdirAll(cfg.Dir, 0o755); err != nil { return nil, fmt.Errorf("blockcache: %w", err) } cache := &Cache{cfg: cfg, open: true} if err := cache.load(); err != nil { return nil, err } if err := cache.evict(); err != nil { return nil, err } return cache, nil } // load reads the index and drops entries whose file is gone. func (c *Cache) load() error { raw, err := os.ReadFile(filepath.Join(c.cfg.Dir, indexName)) if errors.Is(err, os.ErrNotExist) { return nil } if err != nil { return fmt.Errorf("blockcache: %w", err) } var entries []entry if err := json.Unmarshal(raw, &entries); err != nil { // A corrupted index is not worth refusing to start over: the blocks are committed by // their headers and a client that has one will ask again if it needs it. c.cfg.Logf("blockcache: the index is unreadable, starting empty: %v", err) return nil } for _, candidate := range entries { path, err := c.path(candidate.Chain, candidate.Hash) if err != nil { continue } info, err := os.Stat(path) if err != nil { continue } candidate.Bytes = info.Size() c.entries = append(c.entries, candidate) c.bytes += candidate.Bytes } return nil } // Get returns one cached block. func (c *Cache) Get(chain string, hash chainhash.Hash) ([]byte, bool, error) { c.mu.Lock() defer c.mu.Unlock() if !c.open { return nil, false, errors.New("blockcache: closed") } path, err := c.path(chain, hash.String()) if err != nil { return nil, false, err } raw, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return nil, false, nil } if err != nil { return nil, false, fmt.Errorf("blockcache: %w", err) } return raw, true, nil } // Put stores one block, evicting the oldest entries until it fits. func (c *Cache) Put(chain string, hash chainhash.Hash, raw []byte) error { if len(raw) == 0 { return errors.New("blockcache: empty block") } if int64(len(raw)) > c.cfg.MaxBytes { return fmt.Errorf("blockcache: a block of %d bytes is larger than the whole cache", len(raw)) } c.mu.Lock() defer c.mu.Unlock() if !c.open { return errors.New("blockcache: closed") } path, err := c.path(chain, hash.String()) if err != nil { return err } if existing, ok := c.find(chain, hash.String()); ok { // Already stored. No write: the bytes are committed by the header and a second copy // would be a second chance to disagree with it. if existing.Bytes == int64(len(raw)) { return nil } } if err := os.WriteFile(path, raw, 0o644); err != nil { return fmt.Errorf("blockcache: %w", err) } c.entries = append(c.entries, entry{Chain: chain, Hash: hash.String(), Bytes: int64(len(raw))}) c.bytes += int64(len(raw)) return c.evictLocked() } // Len reports the entries and the bytes held. func (c *Cache) Len() (int, int64) { c.mu.Lock() defer c.mu.Unlock() return len(c.entries), c.bytes } // Close writes the index and refuses further use. func (c *Cache) Close() error { c.mu.Lock() defer c.mu.Unlock() if !c.open { return nil } c.open = false return c.saveLocked() } // evict trims the cache to its bound when it is opened. func (c *Cache) evict() error { c.mu.Lock() defer c.mu.Unlock() return c.evictLocked() } // evictLocked removes the oldest entries until the cache fits, and saves the index. func (c *Cache) evictLocked() error { removed := 0 for c.bytes > c.cfg.MaxBytes && len(c.entries) > 0 { oldest := c.entries[0] c.entries = c.entries[1:] c.bytes -= oldest.Bytes path, err := c.path(oldest.Chain, oldest.Hash) if err == nil { _ = os.Remove(path) } removed++ } if removed > 0 { c.cfg.Logf("blockcache: evicted %d block(s), %d left", removed, len(c.entries)) } return c.saveLocked() } // saveLocked writes the index. func (c *Cache) saveLocked() error { encoded, err := json.Marshal(c.entries) if err != nil { return fmt.Errorf("blockcache: %w", err) } path := filepath.Join(c.cfg.Dir, indexName) temporary := path + ".tmp" if err := os.WriteFile(temporary, encoded, 0o644); err != nil { return fmt.Errorf("blockcache: %w", err) } if err := os.Rename(temporary, path); err != nil { return fmt.Errorf("blockcache: %w", err) } return nil } // find returns the entry for one block. func (c *Cache) find(chain, hash string) (entry, bool) { for _, candidate := range c.entries { if candidate.Chain == chain && candidate.Hash == hash { return candidate, true } } return entry{}, false } // path is where one block lives, refusing anything that is not a chain name and a hash. // // The names come from a request, so they are checked rather than trusted: a chain name is // lowercase letters and digits, and a hash is 64 hex characters. func (c *Cache) path(chain, hash string) (string, error) { if !validChain(chain) { return "", fmt.Errorf("blockcache: %q is not a chain name", chain) } if len(hash) != 64 { return "", fmt.Errorf("blockcache: %q is not a block hash", hash) } if _, err := hex.DecodeString(hash); err != nil { return "", fmt.Errorf("blockcache: %q is not a block hash", hash) } return filepath.Join(c.cfg.Dir, chain+"-"+strings.ToLower(hash)+".block"), nil } // validChain reports whether a name is a chain name and not a path. func validChain(chain string) bool { if chain == "" || len(chain) > 32 { return false } for _, r := range chain { switch { case r >= 'a' && r <= 'z': case r >= '0' && r <= '9': default: return false } } return true }