1 // Package cfevents carries BIP157 compact filters as Nostr events.
2 //
3 // The relay is an accelerator, not an authority. A client decides whether a
4 // batch is usable by its own data and nothing else: the filter hash is
5 // committed by the filter header chain, which the client anchors at a
6 // checkpoint it already trusts, and a filter hash is the double SHA-256 of the
7 // filter bytes. So a batch carries the filter hash next to every filter, and
8 // the client compares those hashes with the ones its own store holds before it
9 // stores anything. A relay can withhold a batch, and that costs a fetch from a
10 // peer; it cannot change one.
11 //
12 // One implementation of the format is used by both the producer and the
13 // consumer, because two encoders of the same wire format is how the two ends
14 // drift apart.
15 package cfevents
16 17 import (
18 "encoding/base64"
19 "encoding/binary"
20 "errors"
21 "fmt"
22 "strconv"
23 24 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
25 "git.smesh.lol/nostrino/pkg/nostr"
26 )
27 28 // Kind is the event kind that carries one batch of compact filters.
29 //
30 // It is a regular kind, and that is not an arbitrary choice. A kind in the
31 // addressable range (30000..39999) is stored under (kind, pubkey, d-tag), so
32 // every batch one producer published would replace the last one: the first real
33 // run of the sidecar published three batches and the relay kept only the third,
34 // answering "replaced: a newer event was already stored" for the others. A
35 // regular kind keeps every batch and deduplicates by event id, which with a
36 // deterministic created_at is exactly the behaviour wanted. 3050 is clear of the
37 // kinds the swap market and the gateway use.
38 const Kind = 3050
39 40 // MaxContent bounds the base64 body.
41 //
42 // The relay's ceiling is TORLY_MAX_EVENT_BYTES (131072) for the whole event.
43 // The body is allowed three quarters of that, which leaves 32768 for the tags,
44 // id, pubkey and signature: those are about 400 bytes, so the slack is wide,
45 // and it is there because the relay counts the serialized event, not the body.
46 const MaxContent = 96 << 10
47 48 // BodySize is the binary budget that MaxContent encodes: base64 expands by 4/3.
49 const BodySize = MaxContent * 3 / 4
50 51 // HeaderSize is the bytes of filter hash carried with each filter.
52 const HeaderSize = 32
53 54 // MaxBlocks bounds how many heights one batch may cover.
55 //
56 // Every height is tagged, which is what lets a consumer ask a relay for exactly
57 // the heights it needs: a Nostr filter matches tag values, not ranges, so a
58 // batch that names only its first and last height can only be found by fetching
59 // everything and throwing most of it away. The tags cost about 30 bytes per
60 // height, so the count is capped to leave the event's tag budget intact even
61 // when the filters themselves are tiny.
62 const MaxBlocks = 200
63 64 // Tag and filter names. A Nostr filter addresses events by single-letter tag:
65 // ChainTag carries the chain, HeightTag every height in the batch.
66 const (
67 ChainTag = "c"
68 HeightTag = "h"
69 )
70 71 // EntryOverhead is the fixed cost of one filter: its length prefix and its
72 // filter hash.
73 const EntryOverhead = 4 + HeaderSize
74 75 var (
76 // ErrFull is returned by Add when the next filter would push the body past
77 // its budget. The batch is unchanged.
78 ErrFull = errors.New("cfevents: the batch has no room for another filter")
79 // ErrEmpty is returned by Add for a filter of no bytes. A BIP158 basic
80 // filter always includes the coinbase output script, so an empty one is a
81 // node that answered with nothing useful.
82 ErrEmpty = errors.New("cfevents: empty filter")
83 )
84 85 // Batch is one run of contiguous filters, as published to a relay.
86 type Batch struct {
87 // Chain is the chain profile name: "btc" or "blake".
88 Chain string
89 90 // From is the height of the first filter.
91 From uint32
92 93 // At is the created_at of the event: the timestamp of the last block in
94 // the batch. Deriving it from the chain rather than the clock is what makes
95 // a batch's event id stable, so a restarted producer publishes the same id
96 // and a relay that already holds it answers "duplicate" for no cost.
97 At int64
98 99 // Hashes are the filter hashes: the value the filter header chain commits
100 // to at each height. Parallel to Filters.
101 Hashes []chainhash.Hash
102 103 // Filters are the compact filters, in height order.
104 Filters [][]byte
105 }
106 107 // To returns the height of the last filter.
108 func (b *Batch) To() uint32 {
109 if len(b.Filters) == 0 {
110 return b.From
111 }
112 return b.From + uint32(len(b.Filters)) - 1
113 }
114 115 // Len returns the number of filters.
116 func (b *Batch) Len() int { return len(b.Filters) }
117 118 // Add appends one filter, or returns ErrFull or ErrEmpty without changing the
119 // batch. Filling a batch is a loop that stops on ErrFull, publishes, and starts
120 // a new batch with the filter that did not fit.
121 func (b *Batch) Add(filterHash chainhash.Hash, filter []byte) error {
122 if len(filter) == 0 {
123 return ErrEmpty
124 }
125 if len(b.Filters) >= MaxBlocks {
126 return ErrFull
127 }
128 if b.size()+EntryOverhead+len(filter) > BodySize {
129 return ErrFull
130 }
131 b.Hashes = append(b.Hashes, filterHash)
132 b.Filters = append(b.Filters, filter)
133 return nil
134 }
135 136 // size is the encoded body length for the filters added so far, including the
137 // leading count. It is recomputed rather than accumulated so that a Batch built
138 // by any path encodes to a consistent length; a batch holds a few dozen filters
139 // at most, so the walk costs nothing.
140 func (b *Batch) size() int {
141 n := 4
142 for _, f := range b.Filters {
143 n += EntryOverhead + len(f)
144 }
145 return n
146 }
147 148 // body returns the binary body: a filter count followed by each filter's length,
149 // filter hash and bytes.
150 func (b *Batch) body() []byte {
151 out := make([]byte, 4, b.size())
152 binary.BigEndian.PutUint32(out, uint32(len(b.Filters)))
153 for i, filter := range b.Filters {
154 var n [4]byte
155 binary.BigEndian.PutUint32(n[:], uint32(len(filter)))
156 out = append(out, n[:]...)
157 out = append(out, b.Hashes[i][:]...)
158 out = append(out, filter...)
159 }
160 return out
161 }
162 163 // Encode returns the event. It does not sign: the producer owns the key, and
164 // signing is the only part of building an event that needs a secret.
165 func (b *Batch) Encode() (nostr.Event, error) {
166 if b.Chain == "" {
167 return nostr.Event{}, errors.New("cfevents: no chain name")
168 }
169 if len(b.Filters) == 0 {
170 return nostr.Event{}, errors.New("cfevents: empty batch")
171 }
172 if len(b.Hashes) != len(b.Filters) {
173 return nostr.Event{}, fmt.Errorf("cfevents: %d filters and %d hashes",
174 len(b.Filters), len(b.Hashes))
175 }
176 if b.At <= 0 {
177 return nostr.Event{}, errors.New("cfevents: no created_at")
178 }
179 body := b.body()
180 if base64.StdEncoding.EncodedLen(len(body)) > MaxContent {
181 return nostr.Event{}, fmt.Errorf("cfevents: body of %d bytes encodes past the cap", len(body))
182 }
183 to := b.To()
184 tags := make(nostr.Tags, 0, len(b.Filters)+3)
185 // "c" and "h" are single letters because that is all a NIP-01 filter can
186 // match on: a relay indexes "#c" and "#h", and ignores a multi-letter name.
187 // The from and to tags are for a human reading the event, not for a query.
188 tags = append(tags,
189 nostr.Tag{ChainTag, b.Chain},
190 nostr.Tag{"from", strconv.FormatUint(uint64(b.From), 10)},
191 nostr.Tag{"to", strconv.FormatUint(uint64(to), 10)},
192 )
193 for height := b.From; height <= to; height++ {
194 tags = append(tags, nostr.Tag{"h", strconv.FormatUint(uint64(height), 10)})
195 }
196 return nostr.Event{
197 CreatedAt: b.At,
198 Kind: Kind,
199 Tags: tags,
200 Content: base64.StdEncoding.EncodeToString(body),
201 }, nil
202 }
203 204 // Decode parses an event. It checks the shape of what it is given and nothing
205 // about whether the filters are right: that is Take's job, and it needs the
206 // consumer's own committed hashes to do it.
207 func Decode(e *nostr.Event) (Batch, error) {
208 if e.Kind != Kind {
209 return Batch{}, fmt.Errorf("cfevents: kind %d, want %d", e.Kind, Kind)
210 }
211 chain, ok := e.Tags.First(ChainTag)
212 if !ok || chain == "" {
213 return Batch{}, errors.New("cfevents: no chain tag")
214 }
215 from, err := heightTag(e, "from")
216 if err != nil {
217 return Batch{}, err
218 }
219 to, err := heightTag(e, "to")
220 if err != nil {
221 return Batch{}, err
222 }
223 if to < from {
224 return Batch{}, fmt.Errorf("cfevents: range %d..%d is reversed", from, to)
225 }
226 body, err := base64.StdEncoding.DecodeString(e.Content)
227 if err != nil {
228 return Batch{}, fmt.Errorf("cfevents: body is not base64: %w", err)
229 }
230 if len(body) < 4 {
231 return Batch{}, errors.New("cfevents: body is shorter than its own count")
232 }
233 n := binary.BigEndian.Uint32(body)
234 if want := uint64(to) - uint64(from) + 1; uint64(n) != want {
235 return Batch{}, fmt.Errorf("cfevents: body holds %d filters, tags claim %d", n, want)
236 }
237 b := Batch{
238 Chain: chain,
239 From: from,
240 At: e.CreatedAt,
241 Filters: make([][]byte, 0, n),
242 Hashes: make([]chainhash.Hash, 0, n),
243 }
244 rest := body[4:]
245 for i := uint32(0); i < n; i++ {
246 if len(rest) < 4+HeaderSize {
247 return Batch{}, fmt.Errorf("cfevents: filter %d has no length or hash", from+i)
248 }
249 length := binary.BigEndian.Uint32(rest)
250 rest = rest[4:]
251 var hash chainhash.Hash
252 copy(hash[:], rest[:HeaderSize])
253 rest = rest[HeaderSize:]
254 if uint64(length) > uint64(len(rest)) {
255 return Batch{}, fmt.Errorf("cfevents: filter %d claims %d bytes, %d remain",
256 from+i, length, len(rest))
257 }
258 filter := make([]byte, length)
259 copy(filter, rest[:length])
260 rest = rest[length:]
261 b.Hashes = append(b.Hashes, hash)
262 b.Filters = append(b.Filters, filter)
263 }
264 if len(rest) != 0 {
265 return Batch{}, fmt.Errorf("cfevents: %d trailing bytes after the last filter", len(rest))
266 }
267 return b, nil
268 }
269 270 // Take verifies the batch against the filter hashes the consumer holds and
271 // returns the filters that may be stored, keyed by height.
272 //
273 // It fails whole on a chain disagreement. A batch whose first filter hash is not
274 // the one committed at that height is not a batch with one bad filter, it is a
275 // batch for a fork or another chain, and storing any of it would be storing
276 // bytes from a history this client is not following. Individual filters that
277 // fail their own hash check inside a matching batch are dropped one at a time,
278 // because that is a producer bug rather than a wrong chain.
279 //
280 // The returned count of drops distinguishes the two cases for the caller's log:
281 // the length of the map says how many were usable.
282 func (b *Batch) Take(committed func(height uint32) (chainhash.Hash, bool)) (map[uint32][]byte, error) {
283 if len(b.Filters) == 0 {
284 return nil, errors.New("cfevents: empty batch")
285 }
286 want, ok := committed(b.From)
287 if !ok {
288 // The consumer has no commitment at this height, so it cannot judge the
289 // batch at all. Not an error: the range is simply not one it can use
290 // the cache for.
291 return nil, nil
292 }
293 if want != b.Hashes[0] {
294 return nil, fmt.Errorf("cfevents: chain differs at %d: batch %s, committed %s",
295 b.From, b.Hashes[0], want)
296 }
297 out := make(map[uint32][]byte, len(b.Filters))
298 for i, filter := range b.Filters {
299 if chainhash.DoubleHashH(filter) != b.Hashes[i] {
300 continue
301 }
302 out[b.From+uint32(i)] = filter
303 }
304 return out, nil
305 }
306 307 // heightTag reads a tag whose value is a block height.
308 func heightTag(e *nostr.Event, name string) (uint32, error) {
309 v, ok := e.Tags.First(name)
310 if !ok {
311 return 0, fmt.Errorf("cfevents: no %s tag", name)
312 }
313 n, err := strconv.ParseUint(v, 10, 32)
314 if err != nil {
315 return 0, fmt.Errorf("cfevents: %s tag %q is not a height", name, v)
316 }
317 return uint32(n), nil
318 }
319 320 // Query is the relay filter that asks for the batches covering [from,to].
321 //
322 // A Nostr filter matches tag values and not ranges, so the heights are named
323 // one by one out of the per-height tags. The alternative, asking by time, would
324 // pull every batch since the first block of the range: the relay has no other
325 // way to bound the answer, and at mainnet filter sizes one wasted batch is a
326 // megabyte.
327 func Query(chain string, from, to uint32) nostr.Filter {
328 if to < from {
329 from, to = to, from
330 }
331 heights := make([]string, 0, to-from+1)
332 for height := from; height <= to; height++ {
333 heights = append(heights, strconv.FormatUint(uint64(height), 10))
334 }
335 return nostr.Filter{
336 Kinds: []int{Kind},
337 Tags: map[string][]string{
338 ChainTag: {chain},
339 HeightTag: heights,
340 },
341 // Each matching event covers at least one of the heights asked for, so
342 // the number of events cannot exceed the number of heights.
343 Limit: len(heights),
344 }
345 }
346