// Package headerevents carries block headers as Nostr events. // // One event is one header. A header is 80 bytes, or 164 for the forked chain's version 2 // form, so it fits in an event with room to spare and there is no reason for a client to ask // a gateway for one: the sidecar that follows the node publishes the header as it sees the // block, and any number of clients read it from the relay. // // The relay is an accelerator, not an authority, on the same terms as the filter batches. A // header is self-verifying: it hashes to its own id by proof of work and names its parent, so // a client that anchors at a checkpoint it trusts checks every header it accepts and the // relay gains no authority by holding them. What a relay can do is withhold, and that costs // a fetch from the tunnel. // // The created_at is the header's own time. That is what makes a re-publication the same event // rather than a second copy, and it is why two headers at one height are two different events // with different ids: a reorg is a competing fact, not a correction of the old one. package headerevents import ( "encoding/base64" "encoding/hex" "errors" "fmt" "strconv" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/nostr" ) // Kind is the event kind that carries one block header. // // It is a regular kind, for the reason the filter batches are: an addressable kind is stored // under (kind, pubkey, d-tag), so every header one producer published would replace the last // one. 3051 is the neighbour of the filter batches and clear of the gateway listing (30333), // the graph result (39000) and the swap's coordination kinds (30340..30350). const Kind = 3051 // Tag names. A NIP-01 filter matches single-letter tags, so the chain and the height are // single letters and the block hash is the third: the hash is what lets a client tell two // headers at one height apart, and it is the value it checks its own hash against. const ( ChainTag = "c" HeightTag = "h" BlockTag = "b" ) // MaxContent bounds the body: 164 bytes of header become 224 base64 characters. const MaxContent = 512 // Header is one block header as the event carries it. type Header struct { // Chain is the profile name the header belongs to. Chain string // Height is the block's height. Height uint32 // Hash is the header's proof-of-work hash. Hash chainhash.Hash // Raw is the decoded header. Raw btcwire.BlockHeader } // Encode returns the event for one header. It does not sign: the producer owns the key. func Encode(chain string, height uint32, header *btcwire.BlockHeader) (nostr.Event, error) { if chain == "" { return nostr.Event{}, errors.New("headerevents: no chain name") } if header == nil { return nostr.Event{}, errors.New("headerevents: no header") } raw := header.SerializeAll() if len(raw) != btcwire.BlockHeaderSize && len(raw) != btcwire.BlockHeaderV2Size { return nostr.Event{}, fmt.Errorf("headerevents: header of %d bytes", len(raw)) } // The header time is the event time, so republishing the same header is the same event. at := int64(header.TimeOnWire()) if at <= 0 { at = 1 } hash := header.BlockHash() return nostr.Event{ CreatedAt: at, Kind: Kind, Tags: nostr.Tags{ {ChainTag, chain}, {HeightTag, strconv.FormatUint(uint64(height), 10)}, {BlockTag, hash.String()}, }, Content: base64.StdEncoding.EncodeToString(raw), }, nil } // Decode parses an event back into a header, refusing one whose bytes do not hash to the // block hash it names. // // The hash check belongs here rather than in the caller because it is the only thing that // makes the decoded bytes and the tag the same fact: a client that trusted the tag without it // would verify a header against a name the event itself chose. func Decode(e *nostr.Event) (Header, error) { if e == nil { return Header{}, errors.New("headerevents: no event") } if e.Kind != Kind { return Header{}, fmt.Errorf("headerevents: kind %d, want %d", e.Kind, Kind) } chain, ok := e.Tags.First(ChainTag) if !ok || chain == "" { return Header{}, errors.New("headerevents: no chain tag") } text, ok := e.Tags.First(HeightTag) if !ok { return Header{}, errors.New("headerevents: no height tag") } height, err := strconv.ParseUint(text, 10, 32) if err != nil { return Header{}, fmt.Errorf("headerevents: height %q: %w", text, err) } named, ok := e.Tags.First(BlockTag) if !ok { return Header{}, errors.New("headerevents: no block hash tag") } raw, err := base64.StdEncoding.DecodeString(e.Content) if err != nil { return Header{}, fmt.Errorf("headerevents: body: %w", err) } header := btcwire.BlockHeader{} switch len(raw) { case btcwire.BlockHeaderSize: if err := header.Deserialize(raw); err != nil { return Header{}, fmt.Errorf("headerevents: header: %w", err) } case btcwire.BlockHeaderV2Size: if err := header.DeserializeV2(raw); err != nil { return Header{}, fmt.Errorf("headerevents: version 2 header: %w", err) } default: return Header{}, fmt.Errorf("headerevents: header of %d bytes", len(raw)) } hash := header.BlockHash() if hash.String() != named { return Header{}, fmt.Errorf("headerevents: header hashes to %s, the event names %s", hash.String(), named) } return Header{ Chain: chain, Height: uint32(height), Hash: hash, Raw: header, }, nil } // Query is the relay filter that asks for the headers in [from,to]. // // One event is one height, so the limit is the number of heights: a relay cannot answer with // more events than were asked for, and a filter that named a count instead would be a filter // trusting the relay's arithmetic. 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, }, Limit: len(heights), } } // HashFromText parses a block hash in the display form. func HashFromText(text string) (chainhash.Hash, error) { var hash chainhash.Hash raw, err := hex.DecodeString(text) if err != nil { return hash, err } if len(raw) != chainhash.HashSize { return hash, fmt.Errorf("headerevents: hash of %d bytes", len(raw)) } copy(hash[:], raw) return hash, nil }