blockcache.go raw

   1  // Package blockcache is a disk cache of raw blocks for a sidecar that serves them.
   2  //
   3  // Blocks are the one piece of chain data a relay cannot hold: a block is a megabyte or more
   4  // and the relay's event budget is a hundred kilobytes. So the sidecar keeps them on disk and
   5  // serves them over HTTP, from the cache when it has the block and from its node when it does
   6  // not, and a client asks the cache before it asks the tunnel.
   7  //
   8  // The cache is bounded and evicts the oldest entry first. Oldest is the order things were
   9  // stored, which is close enough to height: a sidecar that starts at the tip stores the tip
  10  // first and works in the same direction the chain grew. When the bound is reached the oldest
  11  // block goes, so what a 10 GiB cache holds is the newest 10 GiB of blocks, which is where the
  12  // requests are.
  13  //
  14  // Nothing here is a consensus decision and nothing here is trusted by a client: the block is
  15  // committed by its own header, and a client that fetches one hashes it and compares the result
  16  // with the header it already accepted.
  17  package blockcache
  18  
  19  import (
  20  	"encoding/hex"
  21  	"encoding/json"
  22  	"errors"
  23  	"fmt"
  24  	"os"
  25  	"path/filepath"
  26  	"strings"
  27  	"sync"
  28  
  29  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  30  )
  31  
  32  // DefaultMaxBytes is the cache bound when none is configured: ten gibibytes, which is about
  33  // ten thousand mainnet blocks and several times that on a chain of smaller blocks.
  34  const DefaultMaxBytes = 10 << 30
  35  
  36  // indexName is the file the entry list lives in.
  37  const indexName = "index.json"
  38  
  39  // Config is what the cache is opened with.
  40  type Config struct {
  41  	// Dir is where the blocks and the index live. It is created if it does not exist.
  42  	Dir string
  43  	// MaxBytes bounds the cache. Zero means DefaultMaxBytes.
  44  	MaxBytes int64
  45  	// Logf receives one line per eviction; nil discards them.
  46  	Logf func(string, ...any)
  47  }
  48  
  49  // entry is one cached block in insertion order.
  50  type entry struct {
  51  	Chain string `json:"chain"`
  52  	Hash  string `json:"hash"`
  53  	Bytes int64  `json:"bytes"`
  54  }
  55  
  56  // Cache is a bounded on-disk block store.
  57  type Cache struct {
  58  	cfg Config
  59  
  60  	mu      sync.Mutex
  61  	entries []entry
  62  	bytes   int64
  63  	open    bool
  64  }
  65  
  66  // Open creates or loads the cache and evicts down to the bound.
  67  func Open(cfg Config) (*Cache, error) {
  68  	if strings.TrimSpace(cfg.Dir) == "" {
  69  		return nil, errors.New("blockcache: no directory")
  70  	}
  71  
  72  	if cfg.MaxBytes <= 0 {
  73  		cfg.MaxBytes = DefaultMaxBytes
  74  	}
  75  
  76  	if cfg.Logf == nil {
  77  		cfg.Logf = func(string, ...any) {}
  78  	}
  79  
  80  	if err := os.MkdirAll(cfg.Dir, 0o755); err != nil {
  81  		return nil, fmt.Errorf("blockcache: %w", err)
  82  	}
  83  
  84  	cache := &Cache{cfg: cfg, open: true}
  85  
  86  	if err := cache.load(); err != nil {
  87  		return nil, err
  88  	}
  89  
  90  	if err := cache.evict(); err != nil {
  91  		return nil, err
  92  	}
  93  
  94  	return cache, nil
  95  }
  96  
  97  // load reads the index and drops entries whose file is gone.
  98  func (c *Cache) load() error {
  99  	raw, err := os.ReadFile(filepath.Join(c.cfg.Dir, indexName))
 100  
 101  	if errors.Is(err, os.ErrNotExist) {
 102  		return nil
 103  	}
 104  
 105  	if err != nil {
 106  		return fmt.Errorf("blockcache: %w", err)
 107  	}
 108  
 109  	var entries []entry
 110  
 111  	if err := json.Unmarshal(raw, &entries); err != nil {
 112  		// A corrupted index is not worth refusing to start over: the blocks are committed by
 113  		// their headers and a client that has one will ask again if it needs it.
 114  		c.cfg.Logf("blockcache: the index is unreadable, starting empty: %v", err)
 115  
 116  		return nil
 117  	}
 118  
 119  	for _, candidate := range entries {
 120  		path, err := c.path(candidate.Chain, candidate.Hash)
 121  
 122  		if err != nil {
 123  			continue
 124  		}
 125  
 126  		info, err := os.Stat(path)
 127  
 128  		if err != nil {
 129  			continue
 130  		}
 131  
 132  		candidate.Bytes = info.Size()
 133  		c.entries = append(c.entries, candidate)
 134  		c.bytes += candidate.Bytes
 135  	}
 136  
 137  	return nil
 138  }
 139  
 140  // Get returns one cached block.
 141  func (c *Cache) Get(chain string, hash chainhash.Hash) ([]byte, bool, error) {
 142  	c.mu.Lock()
 143  	defer c.mu.Unlock()
 144  
 145  	if !c.open {
 146  		return nil, false, errors.New("blockcache: closed")
 147  	}
 148  
 149  	path, err := c.path(chain, hash.String())
 150  
 151  	if err != nil {
 152  		return nil, false, err
 153  	}
 154  
 155  	raw, err := os.ReadFile(path)
 156  
 157  	if errors.Is(err, os.ErrNotExist) {
 158  		return nil, false, nil
 159  	}
 160  
 161  	if err != nil {
 162  		return nil, false, fmt.Errorf("blockcache: %w", err)
 163  	}
 164  
 165  	return raw, true, nil
 166  }
 167  
 168  // Put stores one block, evicting the oldest entries until it fits.
 169  func (c *Cache) Put(chain string, hash chainhash.Hash, raw []byte) error {
 170  	if len(raw) == 0 {
 171  		return errors.New("blockcache: empty block")
 172  	}
 173  
 174  	if int64(len(raw)) > c.cfg.MaxBytes {
 175  		return fmt.Errorf("blockcache: a block of %d bytes is larger than the whole cache", len(raw))
 176  	}
 177  
 178  	c.mu.Lock()
 179  	defer c.mu.Unlock()
 180  
 181  	if !c.open {
 182  		return errors.New("blockcache: closed")
 183  	}
 184  
 185  	path, err := c.path(chain, hash.String())
 186  
 187  	if err != nil {
 188  		return err
 189  	}
 190  
 191  	if existing, ok := c.find(chain, hash.String()); ok {
 192  		// Already stored. No write: the bytes are committed by the header and a second copy
 193  		// would be a second chance to disagree with it.
 194  		if existing.Bytes == int64(len(raw)) {
 195  			return nil
 196  		}
 197  	}
 198  
 199  	if err := os.WriteFile(path, raw, 0o644); err != nil {
 200  		return fmt.Errorf("blockcache: %w", err)
 201  	}
 202  
 203  	c.entries = append(c.entries, entry{Chain: chain, Hash: hash.String(), Bytes: int64(len(raw))})
 204  	c.bytes += int64(len(raw))
 205  
 206  	return c.evictLocked()
 207  }
 208  
 209  // Len reports the entries and the bytes held.
 210  func (c *Cache) Len() (int, int64) {
 211  	c.mu.Lock()
 212  	defer c.mu.Unlock()
 213  
 214  	return len(c.entries), c.bytes
 215  }
 216  
 217  // Close writes the index and refuses further use.
 218  func (c *Cache) Close() error {
 219  	c.mu.Lock()
 220  	defer c.mu.Unlock()
 221  
 222  	if !c.open {
 223  		return nil
 224  	}
 225  
 226  	c.open = false
 227  
 228  	return c.saveLocked()
 229  }
 230  
 231  // evict trims the cache to its bound when it is opened.
 232  func (c *Cache) evict() error {
 233  	c.mu.Lock()
 234  	defer c.mu.Unlock()
 235  
 236  	return c.evictLocked()
 237  }
 238  
 239  // evictLocked removes the oldest entries until the cache fits, and saves the index.
 240  func (c *Cache) evictLocked() error {
 241  	removed := 0
 242  
 243  	for c.bytes > c.cfg.MaxBytes && len(c.entries) > 0 {
 244  		oldest := c.entries[0]
 245  		c.entries = c.entries[1:]
 246  		c.bytes -= oldest.Bytes
 247  
 248  		path, err := c.path(oldest.Chain, oldest.Hash)
 249  
 250  		if err == nil {
 251  			_ = os.Remove(path)
 252  		}
 253  
 254  		removed++
 255  	}
 256  
 257  	if removed > 0 {
 258  		c.cfg.Logf("blockcache: evicted %d block(s), %d left", removed, len(c.entries))
 259  	}
 260  
 261  	return c.saveLocked()
 262  }
 263  
 264  // saveLocked writes the index.
 265  func (c *Cache) saveLocked() error {
 266  	encoded, err := json.Marshal(c.entries)
 267  
 268  	if err != nil {
 269  		return fmt.Errorf("blockcache: %w", err)
 270  	}
 271  
 272  	path := filepath.Join(c.cfg.Dir, indexName)
 273  	temporary := path + ".tmp"
 274  
 275  	if err := os.WriteFile(temporary, encoded, 0o644); err != nil {
 276  		return fmt.Errorf("blockcache: %w", err)
 277  	}
 278  
 279  	if err := os.Rename(temporary, path); err != nil {
 280  		return fmt.Errorf("blockcache: %w", err)
 281  	}
 282  
 283  	return nil
 284  }
 285  
 286  // find returns the entry for one block.
 287  func (c *Cache) find(chain, hash string) (entry, bool) {
 288  	for _, candidate := range c.entries {
 289  		if candidate.Chain == chain && candidate.Hash == hash {
 290  			return candidate, true
 291  		}
 292  	}
 293  
 294  	return entry{}, false
 295  }
 296  
 297  // path is where one block lives, refusing anything that is not a chain name and a hash.
 298  //
 299  // The names come from a request, so they are checked rather than trusted: a chain name is
 300  // lowercase letters and digits, and a hash is 64 hex characters.
 301  func (c *Cache) path(chain, hash string) (string, error) {
 302  	if !validChain(chain) {
 303  		return "", fmt.Errorf("blockcache: %q is not a chain name", chain)
 304  	}
 305  
 306  	if len(hash) != 64 {
 307  		return "", fmt.Errorf("blockcache: %q is not a block hash", hash)
 308  	}
 309  
 310  	if _, err := hex.DecodeString(hash); err != nil {
 311  		return "", fmt.Errorf("blockcache: %q is not a block hash", hash)
 312  	}
 313  
 314  	return filepath.Join(c.cfg.Dir, chain+"-"+strings.ToLower(hash)+".block"), nil
 315  }
 316  
 317  // validChain reports whether a name is a chain name and not a path.
 318  func validChain(chain string) bool {
 319  	if chain == "" || len(chain) > 32 {
 320  		return false
 321  	}
 322  
 323  	for _, r := range chain {
 324  		switch {
 325  		case r >= 'a' && r <= 'z':
 326  		case r >= '0' && r <= '9':
 327  		default:
 328  			return false
 329  		}
 330  	}
 331  
 332  	return true
 333  }
 334