// Package nwc is a Nostr Wallet Connect (NIP-47) client: one connection string, a few requests, // and no wallet daemon to integrate. // // The gateway and the relay both need to move sats without holding keys: a gateway charges for the // service it provides, and a relay charges for the tunnel it carries. NWC is the smallest thing // that lets an operator point either of them at whatever wallet they already run — the connection // string is the whole integration, and the secret in it can be revoked from the wallet. // // Requests are NIP-44 encrypted to the wallet, published as kind 23194; the wallet answers on kind // 23195 with the request's event id in an "e" tag. Nothing here talks to a Lightning node. package nwc import ( "context" "crypto/rand" "encoding/json" "fmt" "net/url" "strings" "time" "git.smesh.lol/nostrino/pkg/crypto/secp256k1" "git.smesh.lol/nostrino/pkg/nip44" "git.smesh.lol/nostrino/pkg/nostr" "git.smesh.lol/nostrino/pkg/relay" ) // Request kinds from NIP-47. const ( KindRequest = 23194 KindResponse = 23195 ) // Methods this package implements. const ( MethodPayInvoice = "pay_invoice" MethodPayKeysend = "pay_keysend" MethodMakeInvoice = "make_invoice" MethodLookupInvoice = "lookup_invoice" MethodListTransactions = "list_transactions" MethodGetBalance = "get_balance" MethodGetInfo = "get_info" ) // Connection is a parsed `nostr+walletconnect://` string. type Connection struct { // Wallet is the wallet service's public key, the one that answers requests. Wallet [32]byte // Secret is this client's own key, which is also the wallet's handle on the connection: the // wallet authorises it when the string was issued and can revoke it. Secret [32]byte // RelayURL is where the wallet listens. RelayURL string } // ParseURI reads a wallet connect string. The secret is part of it, so the string is a credential // and belongs in a 0600 file, never in a log line or an event. func ParseURI(text string) (Connection, error) { text = strings.TrimSpace(text) const scheme = "nostr+walletconnect://" if !strings.HasPrefix(text, scheme) { return Connection{}, fmt.Errorf("nwc: not a wallet connect string (want %s…)", scheme) } rest := text[len(scheme):] walletHex := rest if i := strings.IndexAny(rest, "?"); i >= 0 { walletHex = rest[:i] } wallet, err := parseHexKey(walletHex) if err != nil { return Connection{}, fmt.Errorf("nwc: wallet key: %w", err) } query := url.Values{} if i := strings.Index(rest, "?"); i >= 0 { parsed, err := url.ParseQuery(rest[i+1:]) if err != nil { return Connection{}, fmt.Errorf("nwc: %w", err) } query = parsed } relayURL := firstNonEmpty(query.Get("relay"), query.Get("relay_url")) if relayURL == "" { return Connection{}, fmt.Errorf("nwc: no relay in the connection string") } secretHex := firstNonEmpty(query.Get("secret"), query.Get("secret_key")) if secretHex == "" { return Connection{}, fmt.Errorf("nwc: no secret in the connection string") } secret, err := parseHexKey(secretHex) if err != nil { return Connection{}, fmt.Errorf("nwc: secret: %w", err) } return Connection{Wallet: wallet, Secret: secret, RelayURL: relayURL}, nil } // Client is one open wallet connection. type Client struct { conn Connection relay *relay.Client sub *relay.Subscription conversation [32]byte } // Dial connects to the wallet's relay and subscribes to its answers. func Dial(ctx context.Context, conn Connection, transport relay.Transport) (*Client, error) { conversation, err := nip44.ConversationKey(conn.Secret, conn.Wallet) if err != nil { return nil, fmt.Errorf("nwc: %w", err) } client, err := relay.New(transport, conn.Secret, relay.Options{RelayURL: conn.RelayURL}) if err != nil { return nil, fmt.Errorf("nwc: %w", err) } // Answers are addressed to this key, so one subscription sees every reply that matters. self := pubOf(conn.Secret) sub, err := client.Subscribe(nostr.Filter{ Kinds: []int{KindResponse}, Authors: []string{nostr.Hex(conn.Wallet[:])}, Tags: map[string][]string{"p": {nostr.Hex(self[:])}}, }) if err != nil { client.Close() return nil, fmt.Errorf("nwc: subscribe: %w", err) } eoseCtx, cancel := context.WithTimeout(ctx, 10*time.Second) err = client.WaitEOSE(eoseCtx, sub) cancel() if err != nil { client.Close() return nil, fmt.Errorf("nwc: subscribe: %w", err) } return &Client{conn: conn, relay: client, sub: sub, conversation: conversation}, nil } // Close ends the connection. func (c *Client) Close() error { return c.relay.Close() } // request publishes one encrypted request and waits for the matching answer. func (c *Client) request(ctx context.Context, method string, params map[string]any) (json.RawMessage, error) { payload, err := json.Marshal(map[string]any{"method": method, "params": params}) if err != nil { return nil, fmt.Errorf("nwc: %w", err) } content, err := nip44.Encrypt(c.conversation, payload) if err != nil { return nil, fmt.Errorf("nwc: %w", err) } event := &nostr.Event{ Kind: KindRequest, CreatedAt: time.Now().Unix(), Tags: nostr.Tags{{"p", nostr.Hex(c.conn.Wallet[:])}}, Content: content, } if err := event.Sign(c.conn.Secret); err != nil { return nil, fmt.Errorf("nwc: sign: %w", err) } if err := c.relay.Publish(ctx, event); err != nil { return nil, fmt.Errorf("nwc: publish: %w", err) } want := nostr.Hex(event.ID[:]) for { select { case <-ctx.Done(): return nil, fmt.Errorf("nwc: %s: %w", method, ctx.Err()) case answer, ok := <-c.sub.Events: if !ok { return nil, fmt.Errorf("nwc: %s: the wallet connection closed", method) } if !hasTag(answer, "e", want) { continue } return DecodeResponse(c.conn.Secret, c.conn.Wallet, answer) } } } // DecodeResponse decrypts and validates one answer to a request this client sent. func DecodeResponse(secret, wallet [32]byte, event *nostr.Event) (json.RawMessage, error) { if event.Kind != KindResponse { return nil, fmt.Errorf("nwc: kind %d is not a wallet answer", event.Kind) } conversation, err := nip44.ConversationKey(secret, wallet) if err != nil { return nil, fmt.Errorf("nwc: %w", err) } plain, err := nip44.Decrypt(conversation, event.Content) if err != nil { return nil, fmt.Errorf("nwc: decrypt: %w", err) } var answer struct { ResultType string `json:"result_type"` Error *struct { Code string `json:"code"` Message string `json:"message"` } `json:"error"` Result json.RawMessage `json:"result"` } if err := json.Unmarshal(plain, &answer); err != nil { return nil, fmt.Errorf("nwc: answer is not JSON: %w", err) } if answer.Error != nil { return nil, fmt.Errorf("nwc: %s: %s", answer.Error.Code, answer.Error.Message) } if len(answer.Result) == 0 { return nil, fmt.Errorf("nwc: answer has no result") } return answer.Result, nil } // PayInvoice pays a bolt11 invoice and returns the preimage. func (c *Client) PayInvoice(ctx context.Context, invoice string) (string, error) { result, err := c.request(ctx, MethodPayInvoice, map[string]any{"invoice": invoice}) if err != nil { return "", err } var paid struct { Preimage string `json:"preimage"` FeesPaid int64 `json:"fees_paid"` } if err := json.Unmarshal(result, &paid); err != nil { return "", fmt.Errorf("nwc: pay_invoice answer: %w", err) } return paid.Preimage, nil } // PayKeysend pays without an invoice, and chooses the preimage. // // A keysend payment carries a preimage the sender picks. That is what makes it useful here: the // preimage is 32 bytes, exactly the size of a Nostr public key, so a gateway can pay with its own // key as the preimage and the receiver can tell which gateway paid without a shared account, a // reference field, or a second message. The preimage is not a secret in this use — it is an // identity — so it is passed as hex and never derived from a hash of a secret. func (c *Client) PayKeysend(ctx context.Context, pubkeyHex, preimageHex string, amountSats int64) (string, error) { if _, err := parseHexKey(pubkeyHex); err != nil { return "", fmt.Errorf("nwc: payee: %w", err) } if _, err := parseHexKey(preimageHex); err != nil { return "", fmt.Errorf("nwc: preimage: %w", err) } result, err := c.request(ctx, MethodPayKeysend, map[string]any{ "pubkey": pubkeyHex, "preimage": preimageHex, "amount": amountSats * 1000, // NIP-47 amounts are millisats }) if err != nil { return "", err } var paid struct { Preimage string `json:"preimage"` } if err := json.Unmarshal(result, &paid); err != nil { return "", fmt.Errorf("nwc: pay_keysend answer: %w", err) } return paid.Preimage, nil } // Invoice is an invoice the wallet issued and the state of it. type Invoice struct { Invoice string `json:"invoice"` PaymentHash string `json:"payment_hash"` Preimage string `json:"preimage,omitempty"` AmountSats int64 `json:"amount"` SettledAt int64 `json:"settled_at,omitempty"` } // LookupInvoice asks whether an invoice this wallet issued has been paid. It is how a gateway // knows to go ahead with a listing that waited for its fee. func (c *Client) LookupInvoice(ctx context.Context, paymentHash string) (Invoice, error) { result, err := c.request(ctx, MethodLookupInvoice, map[string]any{"payment_hash": paymentHash}) if err != nil { return Invoice{}, err } var invoice Invoice if err := json.Unmarshal(result, &invoice); err != nil { return Invoice{}, fmt.Errorf("nwc: lookup_invoice answer: %w", err) } // NIP-47 amounts are millisats; everything above this layer speaks sats. invoice.AmountSats = invoice.AmountSats / 1000 return invoice, nil } // Transaction is one payment in or out of the wallet. type Transaction struct { Type string `json:"type"` Invoice string `json:"invoice,omitempty"` Preimage string `json:"preimage,omitempty"` PaymentHash string `json:"payment_hash,omitempty"` AmountSats int64 `json:"amount"` SettledAt int64 `json:"settled_at,omitempty"` } // ListTransactions returns recent payments. A relay uses the incoming side to credit a gateway: // the preimage names the gateway and the amount buys days at whatever rate it charges. func (c *Client) ListTransactions(ctx context.Context, limit int) ([]Transaction, error) { params := map[string]any{"type": "incoming"} if limit > 0 { params["limit"] = limit } result, err := c.request(ctx, MethodListTransactions, params) if err != nil { return nil, err } var listed []Transaction if err := json.Unmarshal(result, &listed); err != nil { return nil, fmt.Errorf("nwc: list_transactions answer: %w", err) } for i := range listed { listed[i].AmountSats = listed[i].AmountSats / 1000 } return listed, nil } // MakeInvoice asks the wallet for an invoice to be paid, and returns the payment hash with it: the // hash is the reference a payment is later looked up by, and reading it out of the bolt11 string // would be a bech32 decoder nobody needs. func (c *Client) MakeInvoice(ctx context.Context, amountSats int64, description string) (Invoice, error) { result, err := c.request(ctx, MethodMakeInvoice, map[string]any{ "amount": amountSats * 1000, // NIP-47 amounts are millisats "description": description, }) if err != nil { return Invoice{}, err } var made Invoice if err := json.Unmarshal(result, &made); err != nil { return Invoice{}, fmt.Errorf("nwc: make_invoice answer: %w", err) } if made.Invoice == "" { return Invoice{}, fmt.Errorf("nwc: the wallet returned no invoice") } if made.PaymentHash == "" { return Invoice{}, fmt.Errorf("nwc: the wallet returned an invoice with no payment hash") } made.AmountSats = made.AmountSats / 1000 if made.AmountSats == 0 { made.AmountSats = amountSats } return made, nil } // Balance is the wallet's spendable balance. type Balance struct { BalanceSats int64 `json:"balance"` } // GetBalance asks the wallet what it has. func (c *Client) GetBalance(ctx context.Context) (int64, error) { result, err := c.request(ctx, MethodGetBalance, nil) if err != nil { return 0, err } var balance Balance if err := json.Unmarshal(result, &balance); err != nil { return 0, fmt.Errorf("nwc: get_balance answer: %w", err) } return balance.BalanceSats, nil } // Info is the wallet's self-description. type Info struct { Alias string `json:"alias"` Methods []string `json:"methods"` Network string `json:"network"` PubKey string `json:"pubkey"` } // GetInfo asks the wallet what it can do. It is the cheapest proof that a connection string works. func (c *Client) GetInfo(ctx context.Context) (Info, error) { result, err := c.request(ctx, MethodGetInfo, nil) if err != nil { return Info{}, err } var info Info if err := json.Unmarshal(result, &info); err != nil { return Info{}, fmt.Errorf("nwc: get_info answer: %w", err) } return info, nil } // RandomSecret returns a fresh client key for a connection that does not have one. func RandomSecret() ([32]byte, error) { var secret [32]byte if _, err := rand.Read(secret[:]); err != nil { return secret, err } return secret, nil } // SatsPerDay is a price written as an integer number of sats; this keeps callers from inventing // their own rounding rules. func SatsPerDay(sats int64) int64 { if sats < 0 { return 0 } return sats } // DurationInSats prices a period of access at a daily rate, rounding up: a part day costs a day. func DurationInSats(ratePerDay int64, period time.Duration) int64 { if ratePerDay <= 0 || period <= 0 { return 0 } days := int64((period + 24*time.Hour - 1) / (24 * time.Hour)) return ratePerDay * days } func hasTag(event *nostr.Event, name, value string) bool { for _, tag := range event.Tags { if len(tag) >= 2 && tag[0] == name && tag[1] == value { return true } } return false } func pubOf(secret [32]byte) [32]byte { pub, _ := secp256k1.PubKey(secret) return pub } func parseHexKey(text string) ([32]byte, error) { var key [32]byte raw, err := hexDecode(strings.TrimSpace(text)) if err != nil { return key, err } if len(raw) != 32 { return key, fmt.Errorf("want 64 hex characters, got %d", len(text)) } copy(key[:], raw) return key, nil } func hexDecode(text string) ([]byte, error) { out := make([]byte, len(text)/2) if len(text)%2 != 0 { return nil, fmt.Errorf("odd number of hex characters") } for i := 0; i < len(out); i++ { hi, ok := hexDigit(text[2*i]) if !ok { return nil, fmt.Errorf("not hex") } lo, ok := hexDigit(text[2*i+1]) if !ok { return nil, fmt.Errorf("not hex") } out[i] = hi<<4 | lo } return out, nil } func hexDigit(c byte) (byte, bool) { switch { case c >= '0' && c <= '9': return c - '0', true case c >= 'a' && c <= 'f': return c - 'a' + 10, true case c >= 'A' && c <= 'F': return c - 'A' + 10, true } return 0, false } func firstNonEmpty(values ...string) string { for _, value := range values { if value != "" { return value } } return "" } // Redacted is the connection as it may be logged: the wallet and its relay, no secret. A // connection string that reaches a log is a wallet that can be drained, so there is no String // method to call by accident. func (c Connection) Redacted() string { return "nostr+walletconnect://" + nostr.Hex(c.Wallet[:]) + "?relay=" + c.RelayURL + "&secret=REDACTED" }