package main import ( "context" "encoding/json" "errors" "fmt" "net/http" "strings" "sync" "time" "git.smesh.lol/nostrino/pkg/blockcache" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // blockReader is the node side of the block service: one block by hash. type blockReader interface { blockByHash(context.Context, chainhash.Hash) ([]byte, error) } // blockService serves raw blocks over HTTP, from the cache or from the node. // // A block is the one thing a relay cannot carry, so the sidecar is what a wallet asks. The // cache is bounded and evicts the oldest entry first, which is where the requests are not: a // client scanning the chain wants the newest blocks and a client catching up wants whatever // it is behind by, and the second case pays a node read once and then a cache hit for whoever // asks next. type blockService struct { chain string node blockReader cache *blockcache.Cache logf func(string, ...any) // mu guards fetching, which coalesces concurrent requests for one hash into one node read: // ten clients asking for the tip block are still one fetch. mu sync.Mutex fetching map[string]chan struct{} last time.Time } // newBlockService prepares the service. func newBlockService(chain string, node blockReader, cache *blockcache.Cache, logf func(string, ...any)) *blockService { return &blockService{ chain: chain, node: node, cache: cache, logf: logf, fetching: make(map[string]chan struct{}), } } // handler routes the service. func (s *blockService) handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("/block/", s.serveBlock) mux.HandleFunc("/health", s.serveHealth) return mux } // serveBlock answers one block by hash. // // The path is /block//. The chain is checked against the one this process follows // rather than used as a cache key alone: a sidecar for one chain answering for another is a // deployment mistake, and a client that trusted it would hash the block and throw it away. func (s *blockService) serveBlock(w http.ResponseWriter, r *http.Request) { // // The client is a page, not a program: a browser will not read a cross-origin response // without this, and the service is on its own port beside the relay the page came from. // The response is public, immutable block data addressed by its own hash, so a wildcard // costs nothing that a read of the chain does not already give away. // w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "*") if r.Method == http.MethodOptions { w.WriteHeader(http.StatusNoContent) return } if r.Method != http.MethodGet && r.Method != http.MethodHead { w.Header().Set("Allow", "GET, HEAD") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/block/"), "/") if len(parts) != 2 { http.Error(w, "want /block//", http.StatusBadRequest) return } if profile, err := chain.ByName(parts[0]); err != nil || profile.Name != s.chain { http.Error(w, "this service serves "+s.chain, http.StatusNotFound) return } hash, err := chainhash.NewHashFromStr(parts[1]) if err != nil { http.Error(w, "not a block hash", http.StatusBadRequest) return } raw, hit, err := s.cache.Get(s.chain, *hash) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if !hit { raw, err = s.fetch(r.Context(), *hash) if err != nil { status := http.StatusBadGateway if errors.Is(err, errNoSuchBlock) { status = http.StatusNotFound } http.Error(w, err.Error(), status) return } } w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Length", fmt.Sprint(len(raw))) w.Header().Set("X-Block-Source", map[bool]string{true: "cache", false: "node"}[hit]) if r.Method == http.MethodHead { return } if _, err := w.Write(raw); err != nil { s.logf("block %s: write: %v", hash.String(), err) } } // errNoSuchBlock reports a hash the node does not have. var errNoSuchBlock = errors.New("no such block") // fetch reads one block from the node and stores it, coalescing concurrent requests. func (s *blockService) fetch(ctx context.Context, hash chainhash.Hash) ([]byte, error) { key := hash.String() s.mu.Lock() if waiting, present := s.fetching[key]; present { s.mu.Unlock() select { case <-waiting: case <-ctx.Done(): return nil, ctx.Err() } raw, hit, err := s.cache.Get(s.chain, hash) if err != nil { return nil, err } if !hit { return nil, fmt.Errorf("block %s: the fetch that was already running did not store it", key) } return raw, nil } done := make(chan struct{}) s.fetching[key] = done s.mu.Unlock() defer func() { s.mu.Lock() delete(s.fetching, key) s.mu.Unlock() close(done) }() started := time.Now() raw, err := s.node.blockByHash(ctx, hash) if err != nil { if strings.Contains(err.Error(), "not found") || strings.Contains(err.Error(), "-5") { return nil, fmt.Errorf("%w: %s", errNoSuchBlock, hash.String()) } return nil, err } // Storing is best effort: a full cache that cannot evict must not fail the request that // paid for the read. if err := s.cache.Put(s.chain, hash, raw); err != nil { s.logf("block %s: fetched %d bytes in %s, not cached: %v", key, len(raw), time.Since(started).Round(time.Millisecond), err) } else { s.logf("block %s: fetched %d bytes in %s and cached", key, len(raw), time.Since(started).Round(time.Millisecond)) } return raw, nil } // prefetch stores one height's block ahead of a request. // // It is for the tip: the first client to need the new block would otherwise pay the node read, // and the point of the cache is that nobody has to pay it twice. func (s *blockService) prefetch(ctx context.Context, height uint32, hash chainhash.Hash) { if _, hit, err := s.cache.Get(s.chain, hash); err != nil || hit { return } if _, err := s.fetch(ctx, hash); err != nil { s.logf("prefetch %d (%s): %v", height, hash.String(), err) } } // serveHealth reports the cache and the chain. func (s *blockService) serveHealth(w http.ResponseWriter, _ *http.Request) { blocks, bytes := s.cache.Len() w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ "chain": s.chain, "cache_blocks": blocks, "cache_bytes": bytes, }) }