// Command nostrino-filtercache publishes a chain's compact filters to a relay. // // A wallet that follows a chain through BIP157 needs one filter per block it // scans, and a node serves them one getcfilters round trip at a time. That is // the cost this program removes: it reads the filters from a node it trusts, // batches them into events, and publishes them once so any number of wallets // can read them from the relay instead. The wallet still verifies every filter // against the filter hash its own header chain commits to, so the relay gains // no authority by holding them. // // The filter cache is built from a node and never from another cache: one bad // batch republished by a second cache would spread to every client that trusts // relays. // // Progress is a watermark in the data directory. Batches are cut by byte budget // from the watermark, so a restart cuts them in the same places: the same run // produces the same events, and re-publishing one costs a "duplicate" answer // rather than a second copy in the relay. package main import ( "context" "crypto/rand" "encoding/json" "errors" "flag" "fmt" "net" "net/http" "net/url" "os" "os/signal" "path/filepath" "strings" "syscall" "time" "git.smesh.lol/nostrino/pkg/blockcache" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/cfevents" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/crypto/secp256k1" "git.smesh.lol/nostrino/pkg/headerevents" "git.smesh.lol/nostrino/pkg/nostr" "git.smesh.lol/nostrino/pkg/relay" ) func main() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() if err := run(ctx, os.Args[1:]); err != nil { fmt.Fprintln(os.Stderr, "nostrino-filtercache:", err) os.Exit(1) } } // config is what the flags describe. type config struct { nodeURL string cookie string // peer is a P2P address to follow instead of an RPC node, for a sidecar that has no node of // its own beside the gateway. peer string // genesisAnchor starts the header chain at genesis rather than the profile's checkpoint, for // a peer that answers nothing to a checkpoint locator. genesisAnchor bool // noFilters turns off the filter batches. A peer that does not serve BIP157 is still a peer // for headers and blocks, and a sidecar that dies on a filter it cannot get is a sidecar that // publishes nothing else. noFilters bool // noHeaders turns off the header events, for a peer that will not serve a header chain from // the anchor this sidecar has. noHeaders bool chain *chain.Profile relays []string data string from uint32 fromSet bool poll time.Duration once bool headers bool // tag is the chain name the events carry and the block service answers to. The profile // is the network's parameters; the tag is which of the application's chains the data is // for. Two regtest nodes are one profile and two chains, and a client looking for blake // would otherwise read btc's headers. tag string // The block service: where it listens, where its cache lives and how big it may grow. blockListen string blockDir string blockBytes int64 blockPrefetch int status bool pubkey bool keyFile string attempts int } // chainNode is the node side of the cache: the four reads it makes, and nothing // else. It is a seam, not scaffolding: it keeps the program's dependence on the // node enumerable, and it lets the publish loop be driven by a fixture. // chainNode is where one chain's data is read from. // // It is keyed by height because that is what the publisher walks and what an accumulator of // headers has: an interface keyed by hash would make every implementation carry a height to // hash lookup for the one caller that wants a block by name. type chainNode interface { tip(context.Context) (uint32, error) // header returns one block header at a height, which is what the header events carry. header(context.Context, uint32) (btcwire.BlockHeader, error) blockTime(context.Context, uint32) (int64, error) filter(context.Context, uint32) ([]byte, chainhash.Hash, error) block(context.Context, uint32) ([]byte, error) blockByHash(context.Context, chainhash.Hash) ([]byte, error) } // eventSink is where batches go. type eventSink interface { publish(context.Context, *nostr.Event) error } var ( _ chainNode = (*node)(nil) _ eventSink = (*publisher)(nil) ) func run(ctx context.Context, args []string) error { cfg, err := parseFlags(args) if err != nil { return err } statePath := filepath.Join(cfg.data, "state.json") prev, err := loadState(statePath) if err != nil { return err } if prev != nil && prev.Chain != cfg.tag { return fmt.Errorf("%s holds progress for chain %q, not %q: one data directory per chain", statePath, prev.Chain, cfg.tag) } if cfg.status { return printStatus(cfg, prev) } // // The identity is a fact an operator has to copy into a relay policy, so it // can be printed without starting a publish loop: one flag, one line on // stdout, and no node or relay touched. It creates the key when the file is // absent, which is the same thing the loop would do. // if cfg.pubkey { _, pub, fresh, err := loadKey(cfg.keyFile) if err != nil { return err } if fresh { fmt.Fprintf(os.Stderr, "new identity written to %s\n", cfg.keyFile) } fmt.Println(nostr.Hex(pub[:])) return nil } if err := os.MkdirAll(cfg.data, 0o755); err != nil { return err } var ( source chainNode closer func() ) switch { case strings.TrimSpace(cfg.peer) != "": profile := cfg.chain if cfg.genesisAnchor { fromGenesis := *profile fromGenesis.Checkpoint = nil profile = &fromGenesis } followed, err := openP2PNode(ctx, profile, filepath.Join(cfg.data, "peerstore"), cfg.peer, logf) if err != nil { return err } source, closer = followed, followed.close logf("following the peer %s for %s", cfg.peer, cfg.tag) case strings.TrimSpace(cfg.nodeURL) != "": rpcNode, err := newNode(cfg.nodeURL, cfg.cookie) if err != nil { return err } source = rpcNode default: return errors.New("either -node (JSON-RPC) or -peer (P2P) is required") } if closer != nil { defer closer() } // The chain tag is what a wallet subscribes to, so the node behind it has to // be the chain the profile names. Genesis is the cheapest proof of that, and // pointing a mainnet profile at a regtest node is a mistake worth catching // before it publishes nineteen thousand blocks of the wrong filters. if rpcNode, ok := source.(*node); ok { if err := checkGenesis(ctx, rpcNode, cfg.chain); err != nil { return err } } if prev == nil && !cfg.fromSet { tip, err := source.tip(ctx) if err != nil { return err } // // A store whose only header is its anchor has nothing to publish at the tip: the anchor // is a height this sidecar has no header for, so the first publishable height is the one // above it. That is the normal state of a chain whose peer is at the checkpoint, and it is // a wait, not a failure. // if _, err := source.header(ctx, tip); err != nil { tip++ } cfg.from = tip logf("a fresh cache for %s starts at %d; -from backfills", cfg.tag, tip) } key, pub, fresh, err := loadKey(cfg.keyFile) if err != nil { return err } if fresh { logf("new identity written to %s", cfg.keyFile) } logf("chain=%s (tag %s) relays=%s pubkey=%s", cfg.chain.Name, cfg.tag, strings.Join(cfg.relays, ","), nostr.Hex(pub[:])) send := newPublisher(cfg.relays, key) defer send.close() st := &state{ Chain: cfg.tag, PublishedTo: int64(cfg.from) - 1, HeadersTo: int64(cfg.from) - 1, Start: cfg.from, } if prev != nil { st = prev if st.PublishedTo+1 < int64(cfg.from) { // The flag moved forward, so the gap below it is now somebody // else's problem; say so rather than pretend coverage is complete. logf("progress says %d, so the range below %d will not be published", st.PublishedTo, cfg.from) st.PublishedTo = int64(cfg.from) - 1 st.HeadersTo = int64(cfg.from) - 1 } } blocks, err := startBlockService(ctx, cfg, source) if err != nil { return err } if blocks != nil { defer blocks.cache.Close() } return follow(ctx, cfg, source, send, st, statePath, blocks) } // startBlockService brings the HTTP block service up when one was asked for. // // It returns nil when no address was configured, which is the default: a sidecar that only // publishes events needs no listener, and an operator who has not opened one has not thought // about who can reach it. func startBlockService(ctx context.Context, cfg *config, node blockReader) (*blockService, error) { if cfg.blockListen == "" { return nil, nil } dir := cfg.blockDir if dir == "" { dir = filepath.Join(cfg.data, "blocks") } cache, err := blockcache.Open(blockcache.Config{Dir: dir, MaxBytes: cfg.blockBytes, Logf: logf}) if err != nil { return nil, err } // The route resolves the name it is given to a profile and compares that // profile's name, so the service is told the profile, not the tag. A forked // chain's tag is the application's name: blake is the xbt profile, and a // service told "blake" rejected both spellings of its own chain. blocks := newBlockService(cfg.chain.Name, node, cache, logf) listener, err := net.Listen("tcp", cfg.blockListen) if err != nil { _ = cache.Close() return nil, err } server := &http.Server{Handler: blocks.handler(), ReadHeaderTimeout: 15 * time.Second} go func() { if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { logf("block service stopped: %v", err) } }() go func() { <-ctx.Done() _ = server.Close() }() held, bytes := cache.Len() logf("block service on http://%s/block/%s/, cache %s holding %d block(s) in %s", listener.Addr(), cfg.tag, size(int(bytes)), held, dir) return blocks, nil } // follow is the publishing loop: backfill to the node tip, then follow it. func follow( ctx context.Context, cfg *config, node chainNode, pub eventSink, st *state, statePath string, blocks *blockService, ) error { // A fixture or a caller that set only the profile publishes under its name, which is what // -tag defaults to. if cfg.tag == "" { cfg.tag = cfg.chain.Name } for { tip, err := node.tip(ctx) if err != nil { return err } st.Tip = int64(tip) // // Headers first, then the filters. A client chains headers from a checkpoint it // trusts and derives the filter-header chain from the filter hashes, so a filter // batch is only usable once its headers are there: publishing them in that order // means the newest block is scannable as soon as the second event lands. // if cfg.headers { for st.HeadersTo < int64(tip) { height := uint32(st.HeadersTo + 1) header, err := node.header(ctx, height) if err != nil { st.LastError = err.Error() _ = saveState(statePath, st) return err } ev, err := headerevents.Encode(cfg.tag, height, &header) if err != nil { st.LastError = err.Error() _ = saveState(statePath, st) return fmt.Errorf("encode header %d: %w", height, err) } if err := publishWithRetry(ctx, pub, &ev, cfg.attempts); err != nil { st.LastError = err.Error() _ = saveState(statePath, st) return fmt.Errorf("publish header %d: %w", height, err) } st.HeadersTo = int64(height) st.Headers++ // The block service holds the newest blocks before anyone asks: the first // client to need a new block would otherwise pay the node read, and the point // of the cache is that nobody has to pay it twice. if blocks != nil && height+uint32(cfg.blockPrefetch) >= tip { blocks.prefetch(ctx, height, header.BlockHash()) } // A backfill saves every hundred heights and the tip saves each time: the // watermark only has to be close enough that a crash republishes a run of // duplicates, which a relay answers as success. if height%100 == 0 || height == tip { if err := saveState(statePath, st); err != nil { return err } } } logf("headers published to %d", st.HeadersTo) } for !cfg.noFilters && st.PublishedTo < int64(tip) { from := uint32(st.PublishedTo + 1) started := time.Now() batch, err := build(ctx, node, cfg.tag, from, tip) if err != nil { st.LastError = err.Error() _ = saveState(statePath, st) return err } ev, err := batch.Encode() if err != nil { st.LastError = err.Error() _ = saveState(statePath, st) return fmt.Errorf("encode %d..%d: %w", from, batch.To(), err) } if err := publishWithRetry(ctx, pub, &ev, cfg.attempts); err != nil { st.LastError = err.Error() _ = saveState(statePath, st) return fmt.Errorf("publish %d..%d: %w", from, batch.To(), err) } st.PublishedTo = int64(batch.To()) st.Batches++ st.LastError = "" if err := saveState(statePath, st); err != nil { return err } logf("published %s %d..%d (%d filters, %s) id=%s in %s", cfg.tag, batch.From, batch.To(), batch.Len(), size(len(ev.Content)), nostr.Hex(ev.ID[:]), time.Since(started).Round(time.Millisecond)) } if cfg.once { logf("at the node tip %d, stopping as asked", tip) return nil } select { case <-ctx.Done(): return nil case <-time.After(cfg.poll): } } } // build fills one batch from from, adding filters until the next would not fit. func build(ctx context.Context, node chainNode, chainName string, from, tip uint32) (*cfevents.Batch, error) { batch := &cfevents.Batch{Chain: chainName, From: from} var last uint32 var count uint32 for height := from; height <= tip; height++ { filter, filterHash, err := node.filter(ctx, height) if err != nil { return nil, err } err = batch.Add(filterHash, filter) if errors.Is(err, cfevents.ErrFull) { break } if err != nil { return nil, fmt.Errorf("height %d: %w", height, err) } last = height count++ } if count == 0 { return nil, fmt.Errorf("no filter at %d fits in one event (a filter over %d bytes?)", from, cfevents.BodySize) } // created_at is the last block's time, so the event id depends on the chain // and not on when this program ran. at, err := node.blockTime(ctx, last) if err != nil { return nil, err } batch.At = at return batch, nil } // publishTimeout bounds one publish attempt: dial, auth, and the relay's OK. const publishTimeout = 90 * time.Second // publishWithRetry sends one event, retrying while the failure could be // temporary. The event id is fixed, so a retry after a rejection that did get // stored costs a "duplicate" answer. func publishWithRetry(ctx context.Context, pub eventSink, ev *nostr.Event, attempts int) error { backoff := time.Second for attempt := 1; ; attempt++ { // One attempt is bounded. A relay that accepts the connection and then // answers nothing must not own the process: the dial, the auth // handshake and the OK all live inside this deadline. attemptCtx, cancel := context.WithTimeout(ctx, publishTimeout) err := pub.publish(attemptCtx, ev) cancel() if err == nil { return nil } // A refusal the relay will repeat is not worth eight rounds of // backoff: the operator needs the relay's own words now, with the // watermark still where it was. var rejection *relay.Rejection if errors.As(err, &rejection) { // A deterministic producer republishes the same event after a crash, and the // relay answering "duplicate" means the event is already there, which is all // this loop wanted. if rejection.Duplicate() { return nil } if !rejection.Retryable() { return fmt.Errorf("the relay refused permanently: %w", err) } } if attempt >= attempts { return fmt.Errorf("%w (after %d attempts)", err, attempt) } logf("publish failed, retrying in %s: %v", backoff, err) select { case <-ctx.Done(): return ctx.Err() case <-time.After(backoff): } if backoff < 30*time.Second { backoff *= 2 } } } // checkGenesis refuses a node that is not the chain the profile names. func checkGenesis(ctx context.Context, node *node, profile *chain.Profile) error { hash, err := node.blockHash(ctx, 0) if err != nil { return err } if hash != profile.GenesisHash { return fmt.Errorf("the node's genesis is %s, but %s has %s: wrong node for this chain", hash, profile.Name, profile.GenesisHash) } return nil } // state is the data directory's record of what has been published. type state struct { Chain string `json:"chain"` Start uint32 `json:"start"` PublishedTo int64 `json:"published_to"` // HeadersTo is the highest height whose header event is published. It is separate from // PublishedTo because the two events carry different things and a run can be interrupted // between them. HeadersTo int64 `json:"headers_to"` Tip int64 `json:"node_tip"` Batches int `json:"batches"` Headers int `json:"headers,omitempty"` Updated string `json:"updated"` LastError string `json:"last_error,omitempty"` } func loadState(path string) (*state, error) { raw, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return nil, nil } if err != nil { return nil, err } var st state if err := json.Unmarshal(raw, &st); err != nil { return nil, fmt.Errorf("%s: %w", path, err) } return &st, nil } func saveState(path string, st *state) error { st.Updated = time.Now().UTC().Format(time.RFC3339) raw, err := json.MarshalIndent(st, "", " ") if err != nil { return err } tmp := path + ".tmp" if err := os.WriteFile(tmp, append(raw, '\n'), 0o644); err != nil { return err } return os.Rename(tmp, path) } func printStatus(cfg *config, st *state) error { out := struct { Chain string `json:"chain"` Start uint32 `json:"start"` PublishedTo int64 `json:"published_to"` Covered int64 `json:"covered_blocks"` Batches int `json:"batches"` Updated string `json:"updated"` LastError string `json:"last_error,omitempty"` }{ Chain: cfg.tag, Start: cfg.from, Updated: "never", } if st != nil { out.PublishedTo = st.PublishedTo out.Start = st.Start out.Batches = st.Batches out.Updated = st.Updated out.LastError = st.LastError } if out.PublishedTo >= int64(out.Start) { out.Covered = out.PublishedTo - int64(out.Start) + 1 } raw, err := json.MarshalIndent(out, "", " ") if err != nil { return err } fmt.Println(string(raw)) return nil } // publisher owns one relay connection per URL. type publisher struct { urls []string key [32]byte relays map[string]*relay.Client } func newPublisher(urls []string, key [32]byte) *publisher { return &publisher{urls: urls, key: key, relays: make(map[string]*relay.Client)} } func (p *publisher) client(url string) (*relay.Client, error) { if c, ok := p.relays[url]; ok { select { case <-c.Done(): // The connection ended; the next attempt opens a new one. _ = c.Close() delete(p.relays, url) default: return c, nil } } transport, err := relay.DialTransport(url) if err != nil { return nil, err } c, err := relay.New(transport, p.key, relay.Options{RelayURL: url}) if err != nil { return nil, err } p.relays[url] = c return c, nil } // refused is a relay's refusal with the URL that produced it, keeping the // rejection typed so the retry policy can tell a permanent no from a busy // relay. Joining the messages into one string would lose that distinction, and // the first version did: a policy refusal was retried eight times with backoff. type refused struct { url string *relay.Rejection } func (r *refused) Error() string { return r.url + ": " + r.Rejection.Error() } func (r *refused) Unwrap() error { return r.Rejection } // publish sends one event to every relay. A relay that already holds it counts // as success: the event is there, which is the whole point, and a restart after // a partial backfill would otherwise never get past the first batch. func (p *publisher) publish(ctx context.Context, ev *nostr.Event) error { var failed []string var permanent error for _, u := range p.urls { c, err := p.client(u) if err != nil { failed = append(failed, u+": "+err.Error()) continue } err = c.Publish(ctx, ev) if err == nil { continue } var rejection *relay.Rejection if errors.As(err, &rejection) { if rejection.Duplicate() { continue } if permanent == nil && !rejection.Retryable() { permanent = &refused{url: u, Rejection: rejection} } } failed = append(failed, u+": "+err.Error()) } if permanent != nil { return permanent } if len(failed) > 0 { return errors.New(strings.Join(failed, "; ")) } return nil } func (p *publisher) close() { for _, c := range p.relays { _ = c.Close() } } // loadKey reads the identity, creating one when the file is absent. The pubkey // it prints is what the relay policy has to allow, so a first run tells the // operator what to paste. func loadKey(path string) ([32]byte, [32]byte, bool, error) { raw, err := os.ReadFile(path) if err == nil { var key [32]byte if err := nostr.Decode32(strings.TrimSpace(string(raw)), key[:]); err != nil { return [32]byte{}, [32]byte{}, false, fmt.Errorf("%s: %w", path, err) } pub, ok := secp256k1.PubKey(key) if !ok { return [32]byte{}, [32]byte{}, false, fmt.Errorf("%s: not a usable secret key", path) } return key, pub, false, nil } if !errors.Is(err, os.ErrNotExist) { return [32]byte{}, [32]byte{}, false, err } for { var key [32]byte if _, err := rand.Read(key[:]); err != nil { return [32]byte{}, [32]byte{}, false, err } pub, ok := secp256k1.PubKey(key) if !ok { continue } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return [32]byte{}, [32]byte{}, false, err } if err := os.WriteFile(path, []byte(nostr.Hex(key[:])+"\n"), 0o600); err != nil { return [32]byte{}, [32]byte{}, false, err } return key, pub, true, nil } } func parseFlags(args []string) (*config, error) { fs := flag.NewFlagSet("nostrino-filtercache", flag.ContinueOnError) var ( nodeURL = fs.String("node", "", "node JSON-RPC endpoint, http://user:pass@host:port") peerArg = fs.String("peer", "", "P2P peer to follow when there is no RPC node (host:port), as the gateway's own peer") noHeaders = fs.Bool("no-headers", false, "publish blocks only; for a peer that will not serve headers from this anchor") noFilters = fs.Bool("no-filters", false, "publish headers and blocks only; for a peer that does not serve BIP157") genesisFlag = fs.Bool("genesis", false, "anchor the header chain at genesis rather than the profile's checkpoint") cookie = fs.String("cookie", "", "path to the node's .cookie file, when the URL carries no credentials") chainArg = fs.String("chain", "btc", "chain profile name or alias: btc, xbt, blake, testnet3, regtest") tagArg = fs.String("tag", "", "chain name the events and the block service use (default: the profile name)") data = fs.String("data", "", "data directory for progress and the identity (default filtercache-)") from = fs.String("from", "", "first height to publish; the default is the node tip on a fresh cache, so only new heights are published") keyFile = fs.String("key", "", "identity file (default /identity.key)") poll = fs.Duration("poll", 10*time.Second, "how often to check the node for new blocks") headers = fs.Bool("headers", true, "publish one event per block header before its filters") blockListen = fs.String("block-listen", "", "serve raw blocks on this address (host:port); empty disables the service") blockDir = fs.String("block-cache-dir", "", "where cached blocks live (default /blocks)") blockBytes = fs.Int64("block-cache-bytes", blockcache.DefaultMaxBytes, "how many bytes of blocks to keep; the oldest are evicted first") blockPrefetch = fs.Int("block-prefetch", 2, "prefetch the blocks this many heights behind the tip") once = fs.Bool("once", false, "run to the node's current tip and exit") status = fs.Bool("status", false, "print coverage and exit") pubkey = fs.Bool("pubkey", false, "print the identity's public key and exit") attempts = fs.Int("attempts", 8, "publish attempts per batch before giving up") relayArg stringList ) fs.Var(&relayArg, "relay", "relay URL to publish to; repeat for more than one") if err := fs.Parse(args); err != nil { return nil, err } profile, err := chain.ByName(*chainArg) if err != nil { return nil, err } cfg := &config{ nodeURL: *nodeURL, cookie: *cookie, peer: *peerArg, genesisAnchor: *genesisFlag, noFilters: *noFilters, noHeaders: *noHeaders, chain: profile, tag: *tagArg, relays: relayArg, data: *data, poll: *poll, headers: *headers && !*noHeaders, blockListen: *blockListen, blockDir: *blockDir, blockBytes: *blockBytes, blockPrefetch: *blockPrefetch, once: *once, status: *status, pubkey: *pubkey, attempts: *attempts, } if cfg.tag == "" { // The tag is the name the operator asked for, not the profile's canonical one: a // client addresses a chain by the name it knows it by, and the profile is only the // parameters behind that name. "blake" and "xbt" are one profile and two spellings, // and the application uses the first, so a sidecar started with -chain blake must // publish under blake. cfg.tag = strings.ToLower(strings.TrimSpace(*chainArg)) } if cfg.data == "" { cfg.data = "filtercache-" + cfg.tag } if *keyFile == "" { cfg.keyFile = filepath.Join(cfg.data, "identity.key") } else { cfg.keyFile = *keyFile } // A checkpoint is the lowest height whose filters a light client can use, // so it is the natural floor for the cache as well: below it the client // cannot verify anything, cached or not. A chain with no checkpoint starts // at the node's tip on the first run, because publishing every filter since // genesis is a different program. // The tip is the default because a sidecar beside a gateway is there for the newest block; // a backfill is a decision an operator makes with -from. cfg.from = 0 if *from != "" { n, err := parseHeight(*from) if err != nil { return nil, err } cfg.from = n cfg.fromSet = true } if !cfg.status && !cfg.pubkey { if cfg.nodeURL == "" && cfg.peer == "" { return nil, errors.New("-node (JSON-RPC) or -peer (P2P) is required") } if len(cfg.relays) == 0 { return nil, errors.New("-relay is required at least once") } for _, u := range cfg.relays { if _, err := url.Parse(u); err != nil { return nil, fmt.Errorf("relay %q: %w", u, err) } } } if cfg.attempts < 1 { return nil, errors.New("-attempts must be at least 1") } return cfg, nil } func parseHeight(s string) (uint32, error) { var n uint64 if _, err := fmt.Sscan(s, &n); err != nil || n > 0xffffffff { return 0, fmt.Errorf("height %q is not a block height", s) } return uint32(n), nil } // stringList is a repeatable flag. type stringList []string func (s *stringList) String() string { return strings.Join(*s, ",") } func (s *stringList) Set(v string) error { if v == "" { return errors.New("empty value") } *s = append(*s, v) return nil } // size renders a body size without pretending to be precise to the byte. func size(n int) string { switch { case n >= 1<<20: return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20)) case n >= 1<<10: return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10)) default: return fmt.Sprintf("%d B", n) } } func logf(format string, args ...any) { fmt.Fprintf(os.Stderr, time.Now().UTC().Format("2006-01-02T15:04:05Z")+" "+format+"\n", args...) }