headerevents.go raw

   1  // Package headerevents carries block headers as Nostr events.
   2  //
   3  // One event is one header. A header is 80 bytes, or 164 for the forked chain's version 2
   4  // form, so it fits in an event with room to spare and there is no reason for a client to ask
   5  // a gateway for one: the sidecar that follows the node publishes the header as it sees the
   6  // block, and any number of clients read it from the relay.
   7  //
   8  // The relay is an accelerator, not an authority, on the same terms as the filter batches. A
   9  // header is self-verifying: it hashes to its own id by proof of work and names its parent, so
  10  // a client that anchors at a checkpoint it trusts checks every header it accepts and the
  11  // relay gains no authority by holding them. What a relay can do is withhold, and that costs
  12  // a fetch from the tunnel.
  13  //
  14  // The created_at is the header's own time. That is what makes a re-publication the same event
  15  // rather than a second copy, and it is why two headers at one height are two different events
  16  // with different ids: a reorg is a competing fact, not a correction of the old one.
  17  package headerevents
  18  
  19  import (
  20  	"encoding/base64"
  21  	"encoding/hex"
  22  	"errors"
  23  	"fmt"
  24  	"strconv"
  25  
  26  	"git.smesh.lol/nostrino/pkg/btcwire"
  27  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  28  	"git.smesh.lol/nostrino/pkg/nostr"
  29  )
  30  
  31  // Kind is the event kind that carries one block header.
  32  //
  33  // It is a regular kind, for the reason the filter batches are: an addressable kind is stored
  34  // under (kind, pubkey, d-tag), so every header one producer published would replace the last
  35  // one. 3051 is the neighbour of the filter batches and clear of the gateway listing (30333),
  36  // the graph result (39000) and the swap's coordination kinds (30340..30350).
  37  const Kind = 3051
  38  
  39  // Tag names. A NIP-01 filter matches single-letter tags, so the chain and the height are
  40  // single letters and the block hash is the third: the hash is what lets a client tell two
  41  // headers at one height apart, and it is the value it checks its own hash against.
  42  const (
  43  	ChainTag  = "c"
  44  	HeightTag = "h"
  45  	BlockTag  = "b"
  46  )
  47  
  48  // MaxContent bounds the body: 164 bytes of header become 224 base64 characters.
  49  const MaxContent = 512
  50  
  51  // Header is one block header as the event carries it.
  52  type Header struct {
  53  	// Chain is the profile name the header belongs to.
  54  	Chain string
  55  	// Height is the block's height.
  56  	Height uint32
  57  	// Hash is the header's proof-of-work hash.
  58  	Hash chainhash.Hash
  59  	// Raw is the decoded header.
  60  	Raw btcwire.BlockHeader
  61  }
  62  
  63  // Encode returns the event for one header. It does not sign: the producer owns the key.
  64  func Encode(chain string, height uint32, header *btcwire.BlockHeader) (nostr.Event, error) {
  65  	if chain == "" {
  66  		return nostr.Event{}, errors.New("headerevents: no chain name")
  67  	}
  68  
  69  	if header == nil {
  70  		return nostr.Event{}, errors.New("headerevents: no header")
  71  	}
  72  
  73  	raw := header.SerializeAll()
  74  
  75  	if len(raw) != btcwire.BlockHeaderSize && len(raw) != btcwire.BlockHeaderV2Size {
  76  		return nostr.Event{}, fmt.Errorf("headerevents: header of %d bytes", len(raw))
  77  	}
  78  
  79  	// The header time is the event time, so republishing the same header is the same event.
  80  	at := int64(header.TimeOnWire())
  81  
  82  	if at <= 0 {
  83  		at = 1
  84  	}
  85  
  86  	hash := header.BlockHash()
  87  
  88  	return nostr.Event{
  89  		CreatedAt: at,
  90  		Kind:      Kind,
  91  		Tags: nostr.Tags{
  92  			{ChainTag, chain},
  93  			{HeightTag, strconv.FormatUint(uint64(height), 10)},
  94  			{BlockTag, hash.String()},
  95  		},
  96  		Content: base64.StdEncoding.EncodeToString(raw),
  97  	}, nil
  98  }
  99  
 100  // Decode parses an event back into a header, refusing one whose bytes do not hash to the
 101  // block hash it names.
 102  //
 103  // The hash check belongs here rather than in the caller because it is the only thing that
 104  // makes the decoded bytes and the tag the same fact: a client that trusted the tag without it
 105  // would verify a header against a name the event itself chose.
 106  func Decode(e *nostr.Event) (Header, error) {
 107  	if e == nil {
 108  		return Header{}, errors.New("headerevents: no event")
 109  	}
 110  
 111  	if e.Kind != Kind {
 112  		return Header{}, fmt.Errorf("headerevents: kind %d, want %d", e.Kind, Kind)
 113  	}
 114  
 115  	chain, ok := e.Tags.First(ChainTag)
 116  
 117  	if !ok || chain == "" {
 118  		return Header{}, errors.New("headerevents: no chain tag")
 119  	}
 120  
 121  	text, ok := e.Tags.First(HeightTag)
 122  
 123  	if !ok {
 124  		return Header{}, errors.New("headerevents: no height tag")
 125  	}
 126  
 127  	height, err := strconv.ParseUint(text, 10, 32)
 128  
 129  	if err != nil {
 130  		return Header{}, fmt.Errorf("headerevents: height %q: %w", text, err)
 131  	}
 132  
 133  	named, ok := e.Tags.First(BlockTag)
 134  
 135  	if !ok {
 136  		return Header{}, errors.New("headerevents: no block hash tag")
 137  	}
 138  
 139  	raw, err := base64.StdEncoding.DecodeString(e.Content)
 140  
 141  	if err != nil {
 142  		return Header{}, fmt.Errorf("headerevents: body: %w", err)
 143  	}
 144  
 145  	header := btcwire.BlockHeader{}
 146  
 147  	switch len(raw) {
 148  	case btcwire.BlockHeaderSize:
 149  		if err := header.Deserialize(raw); err != nil {
 150  			return Header{}, fmt.Errorf("headerevents: header: %w", err)
 151  		}
 152  
 153  	case btcwire.BlockHeaderV2Size:
 154  		if err := header.DeserializeV2(raw); err != nil {
 155  			return Header{}, fmt.Errorf("headerevents: version 2 header: %w", err)
 156  		}
 157  
 158  	default:
 159  		return Header{}, fmt.Errorf("headerevents: header of %d bytes", len(raw))
 160  	}
 161  
 162  	hash := header.BlockHash()
 163  
 164  	if hash.String() != named {
 165  		return Header{}, fmt.Errorf("headerevents: header hashes to %s, the event names %s",
 166  			hash.String(), named)
 167  	}
 168  
 169  	return Header{
 170  		Chain:  chain,
 171  		Height: uint32(height),
 172  		Hash:   hash,
 173  		Raw:    header,
 174  	}, nil
 175  }
 176  
 177  // Query is the relay filter that asks for the headers in [from,to].
 178  //
 179  // One event is one height, so the limit is the number of heights: a relay cannot answer with
 180  // more events than were asked for, and a filter that named a count instead would be a filter
 181  // trusting the relay's arithmetic.
 182  func Query(chain string, from, to uint32) nostr.Filter {
 183  	if to < from {
 184  		from, to = to, from
 185  	}
 186  
 187  	heights := make([]string, 0, to-from+1)
 188  
 189  	for height := from; height <= to; height++ {
 190  		heights = append(heights, strconv.FormatUint(uint64(height), 10))
 191  	}
 192  
 193  	return nostr.Filter{
 194  		Kinds: []int{Kind},
 195  		Tags: map[string][]string{
 196  			ChainTag:  {chain},
 197  			HeightTag: heights,
 198  		},
 199  		Limit: len(heights),
 200  	}
 201  }
 202  
 203  // HashFromText parses a block hash in the display form.
 204  func HashFromText(text string) (chainhash.Hash, error) {
 205  	var hash chainhash.Hash
 206  
 207  	raw, err := hex.DecodeString(text)
 208  
 209  	if err != nil {
 210  		return hash, err
 211  	}
 212  
 213  	if len(raw) != chainhash.HashSize {
 214  		return hash, fmt.Errorf("headerevents: hash of %d bytes", len(raw))
 215  	}
 216  
 217  	copy(hash[:], raw)
 218  
 219  	return hash, nil
 220  }
 221