nip59.go raw

   1  // Package nip59 implements NIP-59 gift wrap: an unsigned rumor sealed with
   2  // NIP-44 into a kind 13 seal, which is itself sealed into a kind 1059 gift wrap
   3  // addressed to one recipient.
   4  //
   5  // Musiquay uses NIP-59 as the transport for purchase orders (3222), entitlement
   6  // deeds (3223), and delivery receipts (32218). Receipts and orders travel as
   7  // rumors. A deed travels as a *signed* 3223 event inside the seal, because a
   8  // host that is not the recipient must be able to verify it; a rumor is
   9  // unsigned and would prove nothing.
  10  //
  11  // Kind 21059 is deliberately not used. NIP-59 defines it as an ephemeral wrap,
  12  // but the registry assigns 21059 to a Concord kind, and every musiquay artifact
  13  // is asynchronous, so 1059 covers all of them.
  14  package nip59
  15  
  16  import (
  17  	"crypto/rand"
  18  	"crypto/sha256"
  19  	"encoding/json"
  20  	"fmt"
  21  	"math/big"
  22  	"time"
  23  
  24  	"golang.org/x/crypto/hkdf"
  25  
  26  	"git.smesh.lol/orly/pkg/nostr/crypto/encryption"
  27  	"git.smesh.lol/orly/pkg/nostr/encoders/event"
  28  	"git.smesh.lol/orly/pkg/nostr/encoders/hex"
  29  	"git.smesh.lol/orly/pkg/nostr/encoders/kind"
  30  	"git.smesh.lol/orly/pkg/nostr/encoders/tag"
  31  	"git.smesh.lol/orly/pkg/nostr/encoders/timestamp"
  32  	"git.smesh.lol/orly/pkg/nostr/interfaces/signer"
  33  	"git.smesh.lol/orly/pkg/nostr/interfaces/signer/p8k"
  34  )
  35  
  36  const (
  37  	// SealKind is the NIP-59 seal kind.
  38  	SealKind = 13
  39  	// WrapKind is the NIP-59 gift wrap kind.
  40  	WrapKind = 1059
  41  	// DefaultJitter is how far into the past the randomised seal and wrap
  42  	// timestamps may be placed. NIP-59 recommends two days.
  43  	DefaultJitter = 48 * time.Hour
  44  )
  45  
  46  // Config controls wrapping. The zero value is usable.
  47  type Config struct {
  48  	// Jitter randomises created_at into the recent past. Zero means
  49  	// DefaultJitter. A negative value disables randomisation.
  50  	Jitter time.Duration
  51  	// Now supplies the current time; nil means time.Now.
  52  	Now func() time.Time
  53  	// Ephemeral supplies the wrap key. Nil means generate a fresh one per wrap.
  54  	// It exists for deterministic tests only; production always generates.
  55  	Ephemeral signer.I
  56  }
  57  
  58  func (c *Config) jitter() time.Duration {
  59  	if c == nil {
  60  		return DefaultJitter
  61  	}
  62  	if c.Jitter == 0 {
  63  		return DefaultJitter
  64  	}
  65  	return c.Jitter
  66  }
  67  
  68  func (c *Config) now() time.Time {
  69  	if c == nil || c.Now == nil {
  70  		return time.Now()
  71  	}
  72  	return c.Now()
  73  }
  74  
  75  // PastTimestamp returns a timestamp in the recent past with a random offset of
  76  // up to the configured jitter. A negative jitter disables randomisation.
  77  func (c *Config) PastTimestamp() time.Time {
  78  	now := c.now()
  79  	j := c.jitter()
  80  	if j < 0 {
  81  		return now
  82  	}
  83  	n, err := rand.Int(rand.Reader, big.NewInt(int64(j)+1))
  84  	if err != nil {
  85  		// A failed entropy read must not weaken the wrap; fall back to the
  86  		// full jitter window.
  87  		return now.Add(-j)
  88  	}
  89  	return now.Add(-time.Duration(n.Int64()))
  90  }
  91  
  92  // NewRumor builds an unsigned rumor from a signer, a kind, tags, and content.
  93  // The rumor carries the signer's public key and a valid event id; it has no
  94  // signature, and NIP-59 forbids adding one.
  95  func NewRumor(sign signer.I, k *kind.K, tags *tag.S, content []byte) *event.E {
  96  	pub := sign.Pub()
  97  	ev := event.New()
  98  	ev.Kind = k.ToU16()
  99  	ev.Pubkey = make([]byte, len(pub))
 100  	copy(ev.Pubkey, pub)
 101  	ev.CreatedAt = timestamp.Now().I64()
 102  	if tags != nil {
 103  		ev.Tags = tags
 104  	}
 105  	ev.Content = content
 106  	ev.ID = ev.GetIDBytes()
 107  	return ev
 108  }
 109  
 110  // RumorFromEvent turns an already-built event into a rumor by clearing the
 111  // signature and recomputing the id. Use it when the content was assembled by a
 112  // caller that did not have a signer at hand.
 113  func RumorFromEvent(ev *event.E, pub []byte) *event.E {
 114  	out := ev.Clone()
 115  	out.Pubkey = make([]byte, len(pub))
 116  	copy(out.Pubkey, pub)
 117  	out.Sig = nil
 118  	out.ID = out.GetIDBytes()
 119  	return out
 120  }
 121  
 122  // Wrap seals payload into a kind 1059 gift wrap addressed to recipient.
 123  //
 124  // payload may be a rumor or a signed event. The payload's own signature, if
 125  // any, is preserved: the seal authenticates the sender, the payload's signature
 126  // authenticates the statement.
 127  func Wrap(sign signer.I, recipient []byte, payload *event.E, cfg *Config) (wrap *event.E, seal *event.E, err error) {
 128  	payloadJSON, err := json.Marshal(payload)
 129  	if err != nil {
 130  		return nil, nil, fmt.Errorf("nip59: marshal payload: %w", err)
 131  	}
 132  	return WrapBytes(sign, recipient, payloadJSON, cfg)
 133  }
 134  
 135  // WrapBytes seals an already-serialized payload into a kind 1059 gift wrap.
 136  // It is the form used for deeds, where the payload must be the exact signed
 137  // event bytes and may have been received over the wire.
 138  func WrapBytes(sign signer.I, recipient, payloadJSON []byte, cfg *Config) (wrap *event.E, seal *event.E, err error) {
 139  	if len(recipient) != 32 {
 140  		return nil, nil, fmt.Errorf("nip59: recipient must be a 32-byte pubkey")
 141  	}
 142  
 143  	// Seal: kind 13, content is the NIP-44 ciphertext of the payload, no tags,
 144  	// signed by the sender.
 145  	sealKey, err := conversationKey(sign, recipient)
 146  	if err != nil {
 147  		return nil, nil, err
 148  	}
 149  	sealCT, err := encryption.Encrypt(sealKey, payloadJSON, nil)
 150  	if err != nil {
 151  		return nil, nil, fmt.Errorf("nip59: encrypt seal: %w", err)
 152  	}
 153  	seal = event.New()
 154  	seal.Kind = SealKind
 155  	seal.CreatedAt = cfg.PastTimestamp().Unix()
 156  	seal.Tags = tag.NewS()
 157  	seal.Content = []byte(sealCT)
 158  	if err = seal.Sign(sign); err != nil {
 159  		return nil, nil, fmt.Errorf("nip59: sign seal: %w", err)
 160  	}
 161  
 162  	// Wrap: kind 1059, content is the NIP-44 ciphertext of the seal, one p tag
 163  	// for the recipient, signed by a throwaway ephemeral key.
 164  	eph := cfg.ephemeral()
 165  	if eph == nil {
 166  		if eph, err = p8k.New(); err != nil {
 167  			return nil, nil, fmt.Errorf("nip59: ephemeral signer: %w", err)
 168  		}
 169  		if err = eph.Generate(); err != nil {
 170  			return nil, nil, fmt.Errorf("nip59: generate ephemeral key: %w", err)
 171  		}
 172  	}
 173  	sealJSON, err := json.Marshal(seal)
 174  	if err != nil {
 175  		return nil, nil, fmt.Errorf("nip59: marshal seal: %w", err)
 176  	}
 177  	wrapKey, err := conversationKey(eph, recipient)
 178  	if err != nil {
 179  		return nil, nil, err
 180  	}
 181  	wrapCT, err := encryption.Encrypt(wrapKey, sealJSON, nil)
 182  	if err != nil {
 183  		return nil, nil, fmt.Errorf("nip59: encrypt wrap: %w", err)
 184  	}
 185  	wrap = event.New()
 186  	wrap.Kind = WrapKind
 187  	wrap.CreatedAt = cfg.PastTimestamp().Unix()
 188  	wrap.Tags = tag.NewS()
 189  	wrap.Tags.Append(tag.NewFromBytesSlice([]byte("p"), []byte(hex.Enc(recipient))))
 190  	wrap.Content = []byte(wrapCT)
 191  	if err = wrap.Sign(eph); err != nil {
 192  		return nil, nil, fmt.Errorf("nip59: sign wrap: %w", err)
 193  	}
 194  	return wrap, seal, nil
 195  }
 196  
 197  // Unwrapped is the result of opening a gift wrap.
 198  type Unwrapped struct {
 199  	// Wrap is the kind 1059 event.
 200  	Wrap *event.E
 201  	// Seal is the verified kind 13 event.
 202  	Seal *event.E
 203  	// PayloadJSON is the exact payload bytes recovered from the seal.
 204  	PayloadJSON []byte
 205  	// Payload is the decoded payload. It is a rumor (no signature) or a signed
 206  	// event, depending on how it was produced.
 207  	Payload *event.E
 208  }
 209  
 210  // Unwrap opens a gift wrap addressed to the holder of recipient, verifies the
 211  // wrap and seal signatures, and decodes the payload.
 212  //
 213  // Unwrap enforces the NIP-59 author binding: a rumor payload must name the seal
 214  // author, otherwise a recipient could be shown a statement that the seal's
 215  // signer did not make. A signed payload is not bound to the seal author,
 216  // because a deed is deliberately forwarded by a party other than its signer.
 217  func Unwrap(recipient signer.I, wrap *event.E, cfg *Config) (*Unwrapped, error) {
 218  	if wrap == nil {
 219  		return nil, fmt.Errorf("nip59: nil wrap")
 220  	}
 221  	if wrap.Kind != WrapKind {
 222  		return nil, fmt.Errorf("nip59: kind %d is not a gift wrap", wrap.Kind)
 223  	}
 224  	if valid, err := wrap.Verify(); err != nil {
 225  		return nil, fmt.Errorf("nip59: verify wrap: %w", err)
 226  	} else if !valid {
 227  		return nil, fmt.Errorf("nip59: wrap signature invalid")
 228  	}
 229  
 230  	// Recipient binding: the wrap must carry a p tag for this key. The
 231  	// decryption would fail anyway, but a clear error is better than a
 232  	// cryptographic one.
 233  	me := recipient.Pub()
 234  	pTags := wrap.Tags.GetAll([]byte("p"))
 235  	found := false
 236  	for _, t := range pTags {
 237  		v, err := hex.Dec(string(t.ValueHex()))
 238  		if err == nil && len(v) == 32 && equalBytes(v, me) {
 239  			found = true
 240  			break
 241  		}
 242  	}
 243  	if !found {
 244  		return nil, fmt.Errorf("nip59: wrap is not addressed to this key")
 245  	}
 246  
 247  	wrapKey, err := conversationKey(recipient, wrap.Pubkey)
 248  	if err != nil {
 249  		return nil, err
 250  	}
 251  	sealJSON, err := encryption.Decrypt(wrapKey, string(wrap.Content))
 252  	if err != nil {
 253  		return nil, fmt.Errorf("nip59: decrypt wrap: %w", err)
 254  	}
 255  	seal := event.New()
 256  	if err = json.Unmarshal([]byte(sealJSON), seal); err != nil {
 257  		return nil, fmt.Errorf("nip59: decode seal: %w", err)
 258  	}
 259  	if seal.Kind != SealKind {
 260  		return nil, fmt.Errorf("nip59: sealed kind %d is not a seal", seal.Kind)
 261  	}
 262  	if valid, err := seal.Verify(); err != nil {
 263  		return nil, fmt.Errorf("nip59: verify seal: %w", err)
 264  	} else if !valid {
 265  		return nil, fmt.Errorf("nip59: seal signature invalid")
 266  	}
 267  
 268  	sealKey, err := conversationKey(recipient, seal.Pubkey)
 269  	if err != nil {
 270  		return nil, err
 271  	}
 272  	payloadJSON, err := encryption.Decrypt(sealKey, string(seal.Content))
 273  	if err != nil {
 274  		return nil, fmt.Errorf("nip59: decrypt seal: %w", err)
 275  	}
 276  	payload := event.New()
 277  	if err = json.Unmarshal([]byte(payloadJSON), payload); err != nil {
 278  		return nil, fmt.Errorf("nip59: decode payload: %w", err)
 279  	}
 280  	if len(payload.Sig) == 0 {
 281  		// Rumor: bind the claimed author to the seal's signer.
 282  		if !equalBytes(payload.Pubkey, seal.Pubkey) {
 283  			return nil, fmt.Errorf("nip59: rumor author does not match seal author")
 284  		}
 285  		if id := payload.GetIDBytes(); !equalBytes(id, payload.ID) {
 286  			return nil, fmt.Errorf("nip59: rumor id is invalid")
 287  		}
 288  	} else if valid, err := payload.Verify(); err != nil {
 289  		return nil, fmt.Errorf("nip59: verify payload: %w", err)
 290  	} else if !valid {
 291  		return nil, fmt.Errorf("nip59: payload signature invalid")
 292  	}
 293  
 294  	return &Unwrapped{
 295  		Wrap:        wrap,
 296  		Seal:        seal,
 297  		PayloadJSON: []byte(payloadJSON),
 298  		Payload:     payload,
 299  	}, nil
 300  }
 301  
 302  // ephemeral returns the configured ephemeral signer, if any.
 303  func (c *Config) ephemeral() signer.I {
 304  	if c == nil {
 305  		return nil
 306  	}
 307  	return c.Ephemeral
 308  }
 309  
 310  // conversationKey derives the NIP-44 v2 conversation key from a signer and a
 311  // peer public key.
 312  func conversationKey(sign signer.I, peer []byte) ([]byte, error) {
 313  	shared, err := sign.ECDHRaw(peer)
 314  	if err != nil {
 315  		return nil, fmt.Errorf("nip59: ECDH: %w", err)
 316  	}
 317  	return hkdf.Extract(sha256.New, shared, []byte("nip44-v2")), nil
 318  }
 319  
 320  func equalBytes(a, b []byte) bool {
 321  	if len(a) != len(b) {
 322  		return false
 323  	}
 324  	var v byte
 325  	for i := range a {
 326  		v |= a[i] ^ b[i]
 327  	}
 328  	return v == 0
 329  }
 330