// Package cfevents carries BIP157 compact filters as Nostr events. // // The relay is an accelerator, not an authority. A client decides whether a // batch is usable by its own data and nothing else: the filter hash is // committed by the filter header chain, which the client anchors at a // checkpoint it already trusts, and a filter hash is the double SHA-256 of the // filter bytes. So a batch carries the filter hash next to every filter, and // the client compares those hashes with the ones its own store holds before it // stores anything. A relay can withhold a batch, and that costs a fetch from a // peer; it cannot change one. // // One implementation of the format is used by both the producer and the // consumer, because two encoders of the same wire format is how the two ends // drift apart. package cfevents import ( "encoding/base64" "encoding/binary" "errors" "fmt" "strconv" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/nostr" ) // Kind is the event kind that carries one batch of compact filters. // // It is a regular kind, and that is not an arbitrary choice. A kind in the // addressable range (30000..39999) is stored under (kind, pubkey, d-tag), so // every batch one producer published would replace the last one: the first real // run of the sidecar published three batches and the relay kept only the third, // answering "replaced: a newer event was already stored" for the others. A // regular kind keeps every batch and deduplicates by event id, which with a // deterministic created_at is exactly the behaviour wanted. 3050 is clear of the // kinds the swap market and the gateway use. const Kind = 3050 // MaxContent bounds the base64 body. // // The relay's ceiling is TORLY_MAX_EVENT_BYTES (131072) for the whole event. // The body is allowed three quarters of that, which leaves 32768 for the tags, // id, pubkey and signature: those are about 400 bytes, so the slack is wide, // and it is there because the relay counts the serialized event, not the body. const MaxContent = 96 << 10 // BodySize is the binary budget that MaxContent encodes: base64 expands by 4/3. const BodySize = MaxContent * 3 / 4 // HeaderSize is the bytes of filter hash carried with each filter. const HeaderSize = 32 // MaxBlocks bounds how many heights one batch may cover. // // Every height is tagged, which is what lets a consumer ask a relay for exactly // the heights it needs: a Nostr filter matches tag values, not ranges, so a // batch that names only its first and last height can only be found by fetching // everything and throwing most of it away. The tags cost about 30 bytes per // height, so the count is capped to leave the event's tag budget intact even // when the filters themselves are tiny. const MaxBlocks = 200 // Tag and filter names. A Nostr filter addresses events by single-letter tag: // ChainTag carries the chain, HeightTag every height in the batch. const ( ChainTag = "c" HeightTag = "h" ) // EntryOverhead is the fixed cost of one filter: its length prefix and its // filter hash. const EntryOverhead = 4 + HeaderSize var ( // ErrFull is returned by Add when the next filter would push the body past // its budget. The batch is unchanged. ErrFull = errors.New("cfevents: the batch has no room for another filter") // ErrEmpty is returned by Add for a filter of no bytes. A BIP158 basic // filter always includes the coinbase output script, so an empty one is a // node that answered with nothing useful. ErrEmpty = errors.New("cfevents: empty filter") ) // Batch is one run of contiguous filters, as published to a relay. type Batch struct { // Chain is the chain profile name: "btc" or "blake". Chain string // From is the height of the first filter. From uint32 // At is the created_at of the event: the timestamp of the last block in // the batch. Deriving it from the chain rather than the clock is what makes // a batch's event id stable, so a restarted producer publishes the same id // and a relay that already holds it answers "duplicate" for no cost. At int64 // Hashes are the filter hashes: the value the filter header chain commits // to at each height. Parallel to Filters. Hashes []chainhash.Hash // Filters are the compact filters, in height order. Filters [][]byte } // To returns the height of the last filter. func (b *Batch) To() uint32 { if len(b.Filters) == 0 { return b.From } return b.From + uint32(len(b.Filters)) - 1 } // Len returns the number of filters. func (b *Batch) Len() int { return len(b.Filters) } // Add appends one filter, or returns ErrFull or ErrEmpty without changing the // batch. Filling a batch is a loop that stops on ErrFull, publishes, and starts // a new batch with the filter that did not fit. func (b *Batch) Add(filterHash chainhash.Hash, filter []byte) error { if len(filter) == 0 { return ErrEmpty } if len(b.Filters) >= MaxBlocks { return ErrFull } if b.size()+EntryOverhead+len(filter) > BodySize { return ErrFull } b.Hashes = append(b.Hashes, filterHash) b.Filters = append(b.Filters, filter) return nil } // size is the encoded body length for the filters added so far, including the // leading count. It is recomputed rather than accumulated so that a Batch built // by any path encodes to a consistent length; a batch holds a few dozen filters // at most, so the walk costs nothing. func (b *Batch) size() int { n := 4 for _, f := range b.Filters { n += EntryOverhead + len(f) } return n } // body returns the binary body: a filter count followed by each filter's length, // filter hash and bytes. func (b *Batch) body() []byte { out := make([]byte, 4, b.size()) binary.BigEndian.PutUint32(out, uint32(len(b.Filters))) for i, filter := range b.Filters { var n [4]byte binary.BigEndian.PutUint32(n[:], uint32(len(filter))) out = append(out, n[:]...) out = append(out, b.Hashes[i][:]...) out = append(out, filter...) } return out } // Encode returns the event. It does not sign: the producer owns the key, and // signing is the only part of building an event that needs a secret. func (b *Batch) Encode() (nostr.Event, error) { if b.Chain == "" { return nostr.Event{}, errors.New("cfevents: no chain name") } if len(b.Filters) == 0 { return nostr.Event{}, errors.New("cfevents: empty batch") } if len(b.Hashes) != len(b.Filters) { return nostr.Event{}, fmt.Errorf("cfevents: %d filters and %d hashes", len(b.Filters), len(b.Hashes)) } if b.At <= 0 { return nostr.Event{}, errors.New("cfevents: no created_at") } body := b.body() if base64.StdEncoding.EncodedLen(len(body)) > MaxContent { return nostr.Event{}, fmt.Errorf("cfevents: body of %d bytes encodes past the cap", len(body)) } to := b.To() tags := make(nostr.Tags, 0, len(b.Filters)+3) // "c" and "h" are single letters because that is all a NIP-01 filter can // match on: a relay indexes "#c" and "#h", and ignores a multi-letter name. // The from and to tags are for a human reading the event, not for a query. tags = append(tags, nostr.Tag{ChainTag, b.Chain}, nostr.Tag{"from", strconv.FormatUint(uint64(b.From), 10)}, nostr.Tag{"to", strconv.FormatUint(uint64(to), 10)}, ) for height := b.From; height <= to; height++ { tags = append(tags, nostr.Tag{"h", strconv.FormatUint(uint64(height), 10)}) } return nostr.Event{ CreatedAt: b.At, Kind: Kind, Tags: tags, Content: base64.StdEncoding.EncodeToString(body), }, nil } // Decode parses an event. It checks the shape of what it is given and nothing // about whether the filters are right: that is Take's job, and it needs the // consumer's own committed hashes to do it. func Decode(e *nostr.Event) (Batch, error) { if e.Kind != Kind { return Batch{}, fmt.Errorf("cfevents: kind %d, want %d", e.Kind, Kind) } chain, ok := e.Tags.First(ChainTag) if !ok || chain == "" { return Batch{}, errors.New("cfevents: no chain tag") } from, err := heightTag(e, "from") if err != nil { return Batch{}, err } to, err := heightTag(e, "to") if err != nil { return Batch{}, err } if to < from { return Batch{}, fmt.Errorf("cfevents: range %d..%d is reversed", from, to) } body, err := base64.StdEncoding.DecodeString(e.Content) if err != nil { return Batch{}, fmt.Errorf("cfevents: body is not base64: %w", err) } if len(body) < 4 { return Batch{}, errors.New("cfevents: body is shorter than its own count") } n := binary.BigEndian.Uint32(body) if want := uint64(to) - uint64(from) + 1; uint64(n) != want { return Batch{}, fmt.Errorf("cfevents: body holds %d filters, tags claim %d", n, want) } b := Batch{ Chain: chain, From: from, At: e.CreatedAt, Filters: make([][]byte, 0, n), Hashes: make([]chainhash.Hash, 0, n), } rest := body[4:] for i := uint32(0); i < n; i++ { if len(rest) < 4+HeaderSize { return Batch{}, fmt.Errorf("cfevents: filter %d has no length or hash", from+i) } length := binary.BigEndian.Uint32(rest) rest = rest[4:] var hash chainhash.Hash copy(hash[:], rest[:HeaderSize]) rest = rest[HeaderSize:] if uint64(length) > uint64(len(rest)) { return Batch{}, fmt.Errorf("cfevents: filter %d claims %d bytes, %d remain", from+i, length, len(rest)) } filter := make([]byte, length) copy(filter, rest[:length]) rest = rest[length:] b.Hashes = append(b.Hashes, hash) b.Filters = append(b.Filters, filter) } if len(rest) != 0 { return Batch{}, fmt.Errorf("cfevents: %d trailing bytes after the last filter", len(rest)) } return b, nil } // Take verifies the batch against the filter hashes the consumer holds and // returns the filters that may be stored, keyed by height. // // It fails whole on a chain disagreement. A batch whose first filter hash is not // the one committed at that height is not a batch with one bad filter, it is a // batch for a fork or another chain, and storing any of it would be storing // bytes from a history this client is not following. Individual filters that // fail their own hash check inside a matching batch are dropped one at a time, // because that is a producer bug rather than a wrong chain. // // The returned count of drops distinguishes the two cases for the caller's log: // the length of the map says how many were usable. func (b *Batch) Take(committed func(height uint32) (chainhash.Hash, bool)) (map[uint32][]byte, error) { if len(b.Filters) == 0 { return nil, errors.New("cfevents: empty batch") } want, ok := committed(b.From) if !ok { // The consumer has no commitment at this height, so it cannot judge the // batch at all. Not an error: the range is simply not one it can use // the cache for. return nil, nil } if want != b.Hashes[0] { return nil, fmt.Errorf("cfevents: chain differs at %d: batch %s, committed %s", b.From, b.Hashes[0], want) } out := make(map[uint32][]byte, len(b.Filters)) for i, filter := range b.Filters { if chainhash.DoubleHashH(filter) != b.Hashes[i] { continue } out[b.From+uint32(i)] = filter } return out, nil } // heightTag reads a tag whose value is a block height. func heightTag(e *nostr.Event, name string) (uint32, error) { v, ok := e.Tags.First(name) if !ok { return 0, fmt.Errorf("cfevents: no %s tag", name) } n, err := strconv.ParseUint(v, 10, 32) if err != nil { return 0, fmt.Errorf("cfevents: %s tag %q is not a height", name, v) } return uint32(n), nil } // Query is the relay filter that asks for the batches covering [from,to]. // // A Nostr filter matches tag values and not ranges, so the heights are named // one by one out of the per-height tags. The alternative, asking by time, would // pull every batch since the first block of the range: the relay has no other // way to bound the answer, and at mainnet filter sizes one wasted batch is a // megabyte. func Query(chain string, from, to uint32) nostr.Filter { if to < from { from, to = to, from } heights := make([]string, 0, to-from+1) for height := from; height <= to; height++ { heights = append(heights, strconv.FormatUint(uint64(height), 10)) } return nostr.Filter{ Kinds: []int{Kind}, Tags: map[string][]string{ ChainTag: {chain}, HeightTag: heights, }, // Each matching event covers at least one of the heights asked for, so // the number of events cannot exceed the number of heights. Limit: len(heights), } }