// Package nip59 implements NIP-59 gift wrap: an unsigned rumor sealed with // NIP-44 into a kind 13 seal, which is itself sealed into a kind 1059 gift wrap // addressed to one recipient. // // Musiquay uses NIP-59 as the transport for purchase orders (3222), entitlement // deeds (3223), and delivery receipts (32218). Receipts and orders travel as // rumors. A deed travels as a *signed* 3223 event inside the seal, because a // host that is not the recipient must be able to verify it; a rumor is // unsigned and would prove nothing. // // Kind 21059 is deliberately not used. NIP-59 defines it as an ephemeral wrap, // but the registry assigns 21059 to a Concord kind, and every musiquay artifact // is asynchronous, so 1059 covers all of them. package nip59 import ( "crypto/rand" "crypto/sha256" "encoding/json" "fmt" "math/big" "time" "golang.org/x/crypto/hkdf" "git.smesh.lol/orly/pkg/nostr/crypto/encryption" "git.smesh.lol/orly/pkg/nostr/encoders/event" "git.smesh.lol/orly/pkg/nostr/encoders/hex" "git.smesh.lol/orly/pkg/nostr/encoders/kind" "git.smesh.lol/orly/pkg/nostr/encoders/tag" "git.smesh.lol/orly/pkg/nostr/encoders/timestamp" "git.smesh.lol/orly/pkg/nostr/interfaces/signer" "git.smesh.lol/orly/pkg/nostr/interfaces/signer/p8k" ) const ( // SealKind is the NIP-59 seal kind. SealKind = 13 // WrapKind is the NIP-59 gift wrap kind. WrapKind = 1059 // DefaultJitter is how far into the past the randomised seal and wrap // timestamps may be placed. NIP-59 recommends two days. DefaultJitter = 48 * time.Hour ) // Config controls wrapping. The zero value is usable. type Config struct { // Jitter randomises created_at into the recent past. Zero means // DefaultJitter. A negative value disables randomisation. Jitter time.Duration // Now supplies the current time; nil means time.Now. Now func() time.Time // Ephemeral supplies the wrap key. Nil means generate a fresh one per wrap. // It exists for deterministic tests only; production always generates. Ephemeral signer.I } func (c *Config) jitter() time.Duration { if c == nil { return DefaultJitter } if c.Jitter == 0 { return DefaultJitter } return c.Jitter } func (c *Config) now() time.Time { if c == nil || c.Now == nil { return time.Now() } return c.Now() } // PastTimestamp returns a timestamp in the recent past with a random offset of // up to the configured jitter. A negative jitter disables randomisation. func (c *Config) PastTimestamp() time.Time { now := c.now() j := c.jitter() if j < 0 { return now } n, err := rand.Int(rand.Reader, big.NewInt(int64(j)+1)) if err != nil { // A failed entropy read must not weaken the wrap; fall back to the // full jitter window. return now.Add(-j) } return now.Add(-time.Duration(n.Int64())) } // NewRumor builds an unsigned rumor from a signer, a kind, tags, and content. // The rumor carries the signer's public key and a valid event id; it has no // signature, and NIP-59 forbids adding one. func NewRumor(sign signer.I, k *kind.K, tags *tag.S, content []byte) *event.E { pub := sign.Pub() ev := event.New() ev.Kind = k.ToU16() ev.Pubkey = make([]byte, len(pub)) copy(ev.Pubkey, pub) ev.CreatedAt = timestamp.Now().I64() if tags != nil { ev.Tags = tags } ev.Content = content ev.ID = ev.GetIDBytes() return ev } // RumorFromEvent turns an already-built event into a rumor by clearing the // signature and recomputing the id. Use it when the content was assembled by a // caller that did not have a signer at hand. func RumorFromEvent(ev *event.E, pub []byte) *event.E { out := ev.Clone() out.Pubkey = make([]byte, len(pub)) copy(out.Pubkey, pub) out.Sig = nil out.ID = out.GetIDBytes() return out } // Wrap seals payload into a kind 1059 gift wrap addressed to recipient. // // payload may be a rumor or a signed event. The payload's own signature, if // any, is preserved: the seal authenticates the sender, the payload's signature // authenticates the statement. func Wrap(sign signer.I, recipient []byte, payload *event.E, cfg *Config) (wrap *event.E, seal *event.E, err error) { payloadJSON, err := json.Marshal(payload) if err != nil { return nil, nil, fmt.Errorf("nip59: marshal payload: %w", err) } return WrapBytes(sign, recipient, payloadJSON, cfg) } // WrapBytes seals an already-serialized payload into a kind 1059 gift wrap. // It is the form used for deeds, where the payload must be the exact signed // event bytes and may have been received over the wire. func WrapBytes(sign signer.I, recipient, payloadJSON []byte, cfg *Config) (wrap *event.E, seal *event.E, err error) { if len(recipient) != 32 { return nil, nil, fmt.Errorf("nip59: recipient must be a 32-byte pubkey") } // Seal: kind 13, content is the NIP-44 ciphertext of the payload, no tags, // signed by the sender. sealKey, err := conversationKey(sign, recipient) if err != nil { return nil, nil, err } sealCT, err := encryption.Encrypt(sealKey, payloadJSON, nil) if err != nil { return nil, nil, fmt.Errorf("nip59: encrypt seal: %w", err) } seal = event.New() seal.Kind = SealKind seal.CreatedAt = cfg.PastTimestamp().Unix() seal.Tags = tag.NewS() seal.Content = []byte(sealCT) if err = seal.Sign(sign); err != nil { return nil, nil, fmt.Errorf("nip59: sign seal: %w", err) } // Wrap: kind 1059, content is the NIP-44 ciphertext of the seal, one p tag // for the recipient, signed by a throwaway ephemeral key. eph := cfg.ephemeral() if eph == nil { if eph, err = p8k.New(); err != nil { return nil, nil, fmt.Errorf("nip59: ephemeral signer: %w", err) } if err = eph.Generate(); err != nil { return nil, nil, fmt.Errorf("nip59: generate ephemeral key: %w", err) } } sealJSON, err := json.Marshal(seal) if err != nil { return nil, nil, fmt.Errorf("nip59: marshal seal: %w", err) } wrapKey, err := conversationKey(eph, recipient) if err != nil { return nil, nil, err } wrapCT, err := encryption.Encrypt(wrapKey, sealJSON, nil) if err != nil { return nil, nil, fmt.Errorf("nip59: encrypt wrap: %w", err) } wrap = event.New() wrap.Kind = WrapKind wrap.CreatedAt = cfg.PastTimestamp().Unix() wrap.Tags = tag.NewS() wrap.Tags.Append(tag.NewFromBytesSlice([]byte("p"), []byte(hex.Enc(recipient)))) wrap.Content = []byte(wrapCT) if err = wrap.Sign(eph); err != nil { return nil, nil, fmt.Errorf("nip59: sign wrap: %w", err) } return wrap, seal, nil } // Unwrapped is the result of opening a gift wrap. type Unwrapped struct { // Wrap is the kind 1059 event. Wrap *event.E // Seal is the verified kind 13 event. Seal *event.E // PayloadJSON is the exact payload bytes recovered from the seal. PayloadJSON []byte // Payload is the decoded payload. It is a rumor (no signature) or a signed // event, depending on how it was produced. Payload *event.E } // Unwrap opens a gift wrap addressed to the holder of recipient, verifies the // wrap and seal signatures, and decodes the payload. // // Unwrap enforces the NIP-59 author binding: a rumor payload must name the seal // author, otherwise a recipient could be shown a statement that the seal's // signer did not make. A signed payload is not bound to the seal author, // because a deed is deliberately forwarded by a party other than its signer. func Unwrap(recipient signer.I, wrap *event.E, cfg *Config) (*Unwrapped, error) { if wrap == nil { return nil, fmt.Errorf("nip59: nil wrap") } if wrap.Kind != WrapKind { return nil, fmt.Errorf("nip59: kind %d is not a gift wrap", wrap.Kind) } if valid, err := wrap.Verify(); err != nil { return nil, fmt.Errorf("nip59: verify wrap: %w", err) } else if !valid { return nil, fmt.Errorf("nip59: wrap signature invalid") } // Recipient binding: the wrap must carry a p tag for this key. The // decryption would fail anyway, but a clear error is better than a // cryptographic one. me := recipient.Pub() pTags := wrap.Tags.GetAll([]byte("p")) found := false for _, t := range pTags { v, err := hex.Dec(string(t.ValueHex())) if err == nil && len(v) == 32 && equalBytes(v, me) { found = true break } } if !found { return nil, fmt.Errorf("nip59: wrap is not addressed to this key") } wrapKey, err := conversationKey(recipient, wrap.Pubkey) if err != nil { return nil, err } sealJSON, err := encryption.Decrypt(wrapKey, string(wrap.Content)) if err != nil { return nil, fmt.Errorf("nip59: decrypt wrap: %w", err) } seal := event.New() if err = json.Unmarshal([]byte(sealJSON), seal); err != nil { return nil, fmt.Errorf("nip59: decode seal: %w", err) } if seal.Kind != SealKind { return nil, fmt.Errorf("nip59: sealed kind %d is not a seal", seal.Kind) } if valid, err := seal.Verify(); err != nil { return nil, fmt.Errorf("nip59: verify seal: %w", err) } else if !valid { return nil, fmt.Errorf("nip59: seal signature invalid") } sealKey, err := conversationKey(recipient, seal.Pubkey) if err != nil { return nil, err } payloadJSON, err := encryption.Decrypt(sealKey, string(seal.Content)) if err != nil { return nil, fmt.Errorf("nip59: decrypt seal: %w", err) } payload := event.New() if err = json.Unmarshal([]byte(payloadJSON), payload); err != nil { return nil, fmt.Errorf("nip59: decode payload: %w", err) } if len(payload.Sig) == 0 { // Rumor: bind the claimed author to the seal's signer. if !equalBytes(payload.Pubkey, seal.Pubkey) { return nil, fmt.Errorf("nip59: rumor author does not match seal author") } if id := payload.GetIDBytes(); !equalBytes(id, payload.ID) { return nil, fmt.Errorf("nip59: rumor id is invalid") } } else if valid, err := payload.Verify(); err != nil { return nil, fmt.Errorf("nip59: verify payload: %w", err) } else if !valid { return nil, fmt.Errorf("nip59: payload signature invalid") } return &Unwrapped{ Wrap: wrap, Seal: seal, PayloadJSON: []byte(payloadJSON), Payload: payload, }, nil } // ephemeral returns the configured ephemeral signer, if any. func (c *Config) ephemeral() signer.I { if c == nil { return nil } return c.Ephemeral } // conversationKey derives the NIP-44 v2 conversation key from a signer and a // peer public key. func conversationKey(sign signer.I, peer []byte) ([]byte, error) { shared, err := sign.ECDHRaw(peer) if err != nil { return nil, fmt.Errorf("nip59: ECDH: %w", err) } return hkdf.Extract(sha256.New, shared, []byte("nip44-v2")), nil } func equalBytes(a, b []byte) bool { if len(a) != len(b) { return false } var v byte for i := range a { v |= a[i] ^ b[i] } return v == 0 }