nwc.go raw

   1  // Package nwc is a Nostr Wallet Connect (NIP-47) client: one connection string, a few requests,
   2  // and no wallet daemon to integrate.
   3  //
   4  // The gateway and the relay both need to move sats without holding keys: a gateway charges for the
   5  // service it provides, and a relay charges for the tunnel it carries. NWC is the smallest thing
   6  // that lets an operator point either of them at whatever wallet they already run — the connection
   7  // string is the whole integration, and the secret in it can be revoked from the wallet.
   8  //
   9  // Requests are NIP-44 encrypted to the wallet, published as kind 23194; the wallet answers on kind
  10  // 23195 with the request's event id in an "e" tag. Nothing here talks to a Lightning node.
  11  package nwc
  12  
  13  import (
  14  	"context"
  15  	"crypto/rand"
  16  	"encoding/json"
  17  	"fmt"
  18  	"net/url"
  19  	"strings"
  20  	"time"
  21  
  22  	"git.smesh.lol/nostrino/pkg/crypto/secp256k1"
  23  	"git.smesh.lol/nostrino/pkg/nip44"
  24  	"git.smesh.lol/nostrino/pkg/nostr"
  25  	"git.smesh.lol/nostrino/pkg/relay"
  26  )
  27  
  28  // Request kinds from NIP-47.
  29  const (
  30  	KindRequest  = 23194
  31  	KindResponse = 23195
  32  )
  33  
  34  // Methods this package implements.
  35  const (
  36  	MethodPayInvoice       = "pay_invoice"
  37  	MethodPayKeysend       = "pay_keysend"
  38  	MethodMakeInvoice      = "make_invoice"
  39  	MethodLookupInvoice    = "lookup_invoice"
  40  	MethodListTransactions = "list_transactions"
  41  	MethodGetBalance       = "get_balance"
  42  	MethodGetInfo          = "get_info"
  43  )
  44  
  45  // Connection is a parsed `nostr+walletconnect://` string.
  46  type Connection struct {
  47  	// Wallet is the wallet service's public key, the one that answers requests.
  48  	Wallet [32]byte
  49  	// Secret is this client's own key, which is also the wallet's handle on the connection: the
  50  	// wallet authorises it when the string was issued and can revoke it.
  51  	Secret [32]byte
  52  	// RelayURL is where the wallet listens.
  53  	RelayURL string
  54  }
  55  
  56  // ParseURI reads a wallet connect string. The secret is part of it, so the string is a credential
  57  // and belongs in a 0600 file, never in a log line or an event.
  58  func ParseURI(text string) (Connection, error) {
  59  	text = strings.TrimSpace(text)
  60  
  61  	const scheme = "nostr+walletconnect://"
  62  
  63  	if !strings.HasPrefix(text, scheme) {
  64  		return Connection{}, fmt.Errorf("nwc: not a wallet connect string (want %s…)", scheme)
  65  	}
  66  
  67  	rest := text[len(scheme):]
  68  	walletHex := rest
  69  
  70  	if i := strings.IndexAny(rest, "?"); i >= 0 {
  71  		walletHex = rest[:i]
  72  	}
  73  
  74  	wallet, err := parseHexKey(walletHex)
  75  
  76  	if err != nil {
  77  		return Connection{}, fmt.Errorf("nwc: wallet key: %w", err)
  78  	}
  79  
  80  	query := url.Values{}
  81  
  82  	if i := strings.Index(rest, "?"); i >= 0 {
  83  		parsed, err := url.ParseQuery(rest[i+1:])
  84  
  85  		if err != nil {
  86  			return Connection{}, fmt.Errorf("nwc: %w", err)
  87  		}
  88  
  89  		query = parsed
  90  	}
  91  
  92  	relayURL := firstNonEmpty(query.Get("relay"), query.Get("relay_url"))
  93  
  94  	if relayURL == "" {
  95  		return Connection{}, fmt.Errorf("nwc: no relay in the connection string")
  96  	}
  97  
  98  	secretHex := firstNonEmpty(query.Get("secret"), query.Get("secret_key"))
  99  
 100  	if secretHex == "" {
 101  		return Connection{}, fmt.Errorf("nwc: no secret in the connection string")
 102  	}
 103  
 104  	secret, err := parseHexKey(secretHex)
 105  
 106  	if err != nil {
 107  		return Connection{}, fmt.Errorf("nwc: secret: %w", err)
 108  	}
 109  
 110  	return Connection{Wallet: wallet, Secret: secret, RelayURL: relayURL}, nil
 111  }
 112  
 113  // Client is one open wallet connection.
 114  type Client struct {
 115  	conn         Connection
 116  	relay        *relay.Client
 117  	sub          *relay.Subscription
 118  	conversation [32]byte
 119  }
 120  
 121  // Dial connects to the wallet's relay and subscribes to its answers.
 122  func Dial(ctx context.Context, conn Connection, transport relay.Transport) (*Client, error) {
 123  	conversation, err := nip44.ConversationKey(conn.Secret, conn.Wallet)
 124  
 125  	if err != nil {
 126  		return nil, fmt.Errorf("nwc: %w", err)
 127  	}
 128  
 129  	client, err := relay.New(transport, conn.Secret, relay.Options{RelayURL: conn.RelayURL})
 130  
 131  	if err != nil {
 132  		return nil, fmt.Errorf("nwc: %w", err)
 133  	}
 134  
 135  	// Answers are addressed to this key, so one subscription sees every reply that matters.
 136  	self := pubOf(conn.Secret)
 137  	sub, err := client.Subscribe(nostr.Filter{
 138  		Kinds:   []int{KindResponse},
 139  		Authors: []string{nostr.Hex(conn.Wallet[:])},
 140  		Tags:    map[string][]string{"p": {nostr.Hex(self[:])}},
 141  	})
 142  
 143  	if err != nil {
 144  		client.Close()
 145  
 146  		return nil, fmt.Errorf("nwc: subscribe: %w", err)
 147  	}
 148  
 149  	eoseCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
 150  	err = client.WaitEOSE(eoseCtx, sub)
 151  	cancel()
 152  
 153  	if err != nil {
 154  		client.Close()
 155  
 156  		return nil, fmt.Errorf("nwc: subscribe: %w", err)
 157  	}
 158  
 159  	return &Client{conn: conn, relay: client, sub: sub, conversation: conversation}, nil
 160  }
 161  
 162  // Close ends the connection.
 163  func (c *Client) Close() error { return c.relay.Close() }
 164  
 165  // request publishes one encrypted request and waits for the matching answer.
 166  func (c *Client) request(ctx context.Context, method string, params map[string]any) (json.RawMessage, error) {
 167  	payload, err := json.Marshal(map[string]any{"method": method, "params": params})
 168  
 169  	if err != nil {
 170  		return nil, fmt.Errorf("nwc: %w", err)
 171  	}
 172  
 173  	content, err := nip44.Encrypt(c.conversation, payload)
 174  
 175  	if err != nil {
 176  		return nil, fmt.Errorf("nwc: %w", err)
 177  	}
 178  
 179  	event := &nostr.Event{
 180  		Kind:      KindRequest,
 181  		CreatedAt: time.Now().Unix(),
 182  		Tags:      nostr.Tags{{"p", nostr.Hex(c.conn.Wallet[:])}},
 183  		Content:   content,
 184  	}
 185  
 186  	if err := event.Sign(c.conn.Secret); err != nil {
 187  		return nil, fmt.Errorf("nwc: sign: %w", err)
 188  	}
 189  
 190  	if err := c.relay.Publish(ctx, event); err != nil {
 191  		return nil, fmt.Errorf("nwc: publish: %w", err)
 192  	}
 193  
 194  	want := nostr.Hex(event.ID[:])
 195  
 196  	for {
 197  		select {
 198  		case <-ctx.Done():
 199  			return nil, fmt.Errorf("nwc: %s: %w", method, ctx.Err())
 200  		case answer, ok := <-c.sub.Events:
 201  			if !ok {
 202  				return nil, fmt.Errorf("nwc: %s: the wallet connection closed", method)
 203  			}
 204  
 205  			if !hasTag(answer, "e", want) {
 206  				continue
 207  			}
 208  
 209  			return DecodeResponse(c.conn.Secret, c.conn.Wallet, answer)
 210  		}
 211  	}
 212  }
 213  
 214  // DecodeResponse decrypts and validates one answer to a request this client sent.
 215  func DecodeResponse(secret, wallet [32]byte, event *nostr.Event) (json.RawMessage, error) {
 216  	if event.Kind != KindResponse {
 217  		return nil, fmt.Errorf("nwc: kind %d is not a wallet answer", event.Kind)
 218  	}
 219  
 220  	conversation, err := nip44.ConversationKey(secret, wallet)
 221  
 222  	if err != nil {
 223  		return nil, fmt.Errorf("nwc: %w", err)
 224  	}
 225  
 226  	plain, err := nip44.Decrypt(conversation, event.Content)
 227  
 228  	if err != nil {
 229  		return nil, fmt.Errorf("nwc: decrypt: %w", err)
 230  	}
 231  
 232  	var answer struct {
 233  		ResultType string `json:"result_type"`
 234  		Error      *struct {
 235  			Code    string `json:"code"`
 236  			Message string `json:"message"`
 237  		} `json:"error"`
 238  		Result json.RawMessage `json:"result"`
 239  	}
 240  
 241  	if err := json.Unmarshal(plain, &answer); err != nil {
 242  		return nil, fmt.Errorf("nwc: answer is not JSON: %w", err)
 243  	}
 244  
 245  	if answer.Error != nil {
 246  		return nil, fmt.Errorf("nwc: %s: %s", answer.Error.Code, answer.Error.Message)
 247  	}
 248  
 249  	if len(answer.Result) == 0 {
 250  		return nil, fmt.Errorf("nwc: answer has no result")
 251  	}
 252  
 253  	return answer.Result, nil
 254  }
 255  
 256  // PayInvoice pays a bolt11 invoice and returns the preimage.
 257  func (c *Client) PayInvoice(ctx context.Context, invoice string) (string, error) {
 258  	result, err := c.request(ctx, MethodPayInvoice, map[string]any{"invoice": invoice})
 259  
 260  	if err != nil {
 261  		return "", err
 262  	}
 263  
 264  	var paid struct {
 265  		Preimage string `json:"preimage"`
 266  		FeesPaid int64  `json:"fees_paid"`
 267  	}
 268  
 269  	if err := json.Unmarshal(result, &paid); err != nil {
 270  		return "", fmt.Errorf("nwc: pay_invoice answer: %w", err)
 271  	}
 272  
 273  	return paid.Preimage, nil
 274  }
 275  
 276  // PayKeysend pays without an invoice, and chooses the preimage.
 277  //
 278  // A keysend payment carries a preimage the sender picks. That is what makes it useful here: the
 279  // preimage is 32 bytes, exactly the size of a Nostr public key, so a gateway can pay with its own
 280  // key as the preimage and the receiver can tell which gateway paid without a shared account, a
 281  // reference field, or a second message. The preimage is not a secret in this use — it is an
 282  // identity — so it is passed as hex and never derived from a hash of a secret.
 283  func (c *Client) PayKeysend(ctx context.Context, pubkeyHex, preimageHex string, amountSats int64) (string, error) {
 284  	if _, err := parseHexKey(pubkeyHex); err != nil {
 285  		return "", fmt.Errorf("nwc: payee: %w", err)
 286  	}
 287  
 288  	if _, err := parseHexKey(preimageHex); err != nil {
 289  		return "", fmt.Errorf("nwc: preimage: %w", err)
 290  	}
 291  
 292  	result, err := c.request(ctx, MethodPayKeysend, map[string]any{
 293  		"pubkey":   pubkeyHex,
 294  		"preimage": preimageHex,
 295  		"amount":   amountSats * 1000, // NIP-47 amounts are millisats
 296  	})
 297  
 298  	if err != nil {
 299  		return "", err
 300  	}
 301  
 302  	var paid struct {
 303  		Preimage string `json:"preimage"`
 304  	}
 305  
 306  	if err := json.Unmarshal(result, &paid); err != nil {
 307  		return "", fmt.Errorf("nwc: pay_keysend answer: %w", err)
 308  	}
 309  
 310  	return paid.Preimage, nil
 311  }
 312  
 313  // Invoice is an invoice the wallet issued and the state of it.
 314  type Invoice struct {
 315  	Invoice     string `json:"invoice"`
 316  	PaymentHash string `json:"payment_hash"`
 317  	Preimage    string `json:"preimage,omitempty"`
 318  	AmountSats  int64  `json:"amount"`
 319  	SettledAt   int64  `json:"settled_at,omitempty"`
 320  }
 321  
 322  // LookupInvoice asks whether an invoice this wallet issued has been paid. It is how a gateway
 323  // knows to go ahead with a listing that waited for its fee.
 324  func (c *Client) LookupInvoice(ctx context.Context, paymentHash string) (Invoice, error) {
 325  	result, err := c.request(ctx, MethodLookupInvoice, map[string]any{"payment_hash": paymentHash})
 326  
 327  	if err != nil {
 328  		return Invoice{}, err
 329  	}
 330  
 331  	var invoice Invoice
 332  
 333  	if err := json.Unmarshal(result, &invoice); err != nil {
 334  		return Invoice{}, fmt.Errorf("nwc: lookup_invoice answer: %w", err)
 335  	}
 336  
 337  	// NIP-47 amounts are millisats; everything above this layer speaks sats.
 338  	invoice.AmountSats = invoice.AmountSats / 1000
 339  
 340  	return invoice, nil
 341  }
 342  
 343  // Transaction is one payment in or out of the wallet.
 344  type Transaction struct {
 345  	Type        string `json:"type"`
 346  	Invoice     string `json:"invoice,omitempty"`
 347  	Preimage    string `json:"preimage,omitempty"`
 348  	PaymentHash string `json:"payment_hash,omitempty"`
 349  	AmountSats  int64  `json:"amount"`
 350  	SettledAt   int64  `json:"settled_at,omitempty"`
 351  }
 352  
 353  // ListTransactions returns recent payments. A relay uses the incoming side to credit a gateway:
 354  // the preimage names the gateway and the amount buys days at whatever rate it charges.
 355  func (c *Client) ListTransactions(ctx context.Context, limit int) ([]Transaction, error) {
 356  	params := map[string]any{"type": "incoming"}
 357  
 358  	if limit > 0 {
 359  		params["limit"] = limit
 360  	}
 361  
 362  	result, err := c.request(ctx, MethodListTransactions, params)
 363  
 364  	if err != nil {
 365  		return nil, err
 366  	}
 367  
 368  	var listed []Transaction
 369  
 370  	if err := json.Unmarshal(result, &listed); err != nil {
 371  		return nil, fmt.Errorf("nwc: list_transactions answer: %w", err)
 372  	}
 373  
 374  	for i := range listed {
 375  		listed[i].AmountSats = listed[i].AmountSats / 1000
 376  	}
 377  
 378  	return listed, nil
 379  }
 380  
 381  // MakeInvoice asks the wallet for an invoice to be paid, and returns the payment hash with it: the
 382  // hash is the reference a payment is later looked up by, and reading it out of the bolt11 string
 383  // would be a bech32 decoder nobody needs.
 384  func (c *Client) MakeInvoice(ctx context.Context, amountSats int64, description string) (Invoice, error) {
 385  	result, err := c.request(ctx, MethodMakeInvoice, map[string]any{
 386  		"amount":      amountSats * 1000, // NIP-47 amounts are millisats
 387  		"description": description,
 388  	})
 389  
 390  	if err != nil {
 391  		return Invoice{}, err
 392  	}
 393  
 394  	var made Invoice
 395  
 396  	if err := json.Unmarshal(result, &made); err != nil {
 397  		return Invoice{}, fmt.Errorf("nwc: make_invoice answer: %w", err)
 398  	}
 399  
 400  	if made.Invoice == "" {
 401  		return Invoice{}, fmt.Errorf("nwc: the wallet returned no invoice")
 402  	}
 403  
 404  	if made.PaymentHash == "" {
 405  		return Invoice{}, fmt.Errorf("nwc: the wallet returned an invoice with no payment hash")
 406  	}
 407  
 408  	made.AmountSats = made.AmountSats / 1000
 409  
 410  	if made.AmountSats == 0 {
 411  		made.AmountSats = amountSats
 412  	}
 413  
 414  	return made, nil
 415  }
 416  
 417  // Balance is the wallet's spendable balance.
 418  type Balance struct {
 419  	BalanceSats int64 `json:"balance"`
 420  }
 421  
 422  // GetBalance asks the wallet what it has.
 423  func (c *Client) GetBalance(ctx context.Context) (int64, error) {
 424  	result, err := c.request(ctx, MethodGetBalance, nil)
 425  
 426  	if err != nil {
 427  		return 0, err
 428  	}
 429  
 430  	var balance Balance
 431  
 432  	if err := json.Unmarshal(result, &balance); err != nil {
 433  		return 0, fmt.Errorf("nwc: get_balance answer: %w", err)
 434  	}
 435  
 436  	return balance.BalanceSats, nil
 437  }
 438  
 439  // Info is the wallet's self-description.
 440  type Info struct {
 441  	Alias   string   `json:"alias"`
 442  	Methods []string `json:"methods"`
 443  	Network string   `json:"network"`
 444  	PubKey  string   `json:"pubkey"`
 445  }
 446  
 447  // GetInfo asks the wallet what it can do. It is the cheapest proof that a connection string works.
 448  func (c *Client) GetInfo(ctx context.Context) (Info, error) {
 449  	result, err := c.request(ctx, MethodGetInfo, nil)
 450  
 451  	if err != nil {
 452  		return Info{}, err
 453  	}
 454  
 455  	var info Info
 456  
 457  	if err := json.Unmarshal(result, &info); err != nil {
 458  		return Info{}, fmt.Errorf("nwc: get_info answer: %w", err)
 459  	}
 460  
 461  	return info, nil
 462  }
 463  
 464  // RandomSecret returns a fresh client key for a connection that does not have one.
 465  func RandomSecret() ([32]byte, error) {
 466  	var secret [32]byte
 467  
 468  	if _, err := rand.Read(secret[:]); err != nil {
 469  		return secret, err
 470  	}
 471  
 472  	return secret, nil
 473  }
 474  
 475  // SatsPerDay is a price written as an integer number of sats; this keeps callers from inventing
 476  // their own rounding rules.
 477  func SatsPerDay(sats int64) int64 {
 478  	if sats < 0 {
 479  		return 0
 480  	}
 481  
 482  	return sats
 483  }
 484  
 485  // DurationInSats prices a period of access at a daily rate, rounding up: a part day costs a day.
 486  func DurationInSats(ratePerDay int64, period time.Duration) int64 {
 487  	if ratePerDay <= 0 || period <= 0 {
 488  		return 0
 489  	}
 490  
 491  	days := int64((period + 24*time.Hour - 1) / (24 * time.Hour))
 492  
 493  	return ratePerDay * days
 494  }
 495  
 496  func hasTag(event *nostr.Event, name, value string) bool {
 497  	for _, tag := range event.Tags {
 498  		if len(tag) >= 2 && tag[0] == name && tag[1] == value {
 499  			return true
 500  		}
 501  	}
 502  
 503  	return false
 504  }
 505  
 506  func pubOf(secret [32]byte) [32]byte {
 507  	pub, _ := secp256k1.PubKey(secret)
 508  
 509  	return pub
 510  }
 511  
 512  func parseHexKey(text string) ([32]byte, error) {
 513  	var key [32]byte
 514  
 515  	raw, err := hexDecode(strings.TrimSpace(text))
 516  
 517  	if err != nil {
 518  		return key, err
 519  	}
 520  
 521  	if len(raw) != 32 {
 522  		return key, fmt.Errorf("want 64 hex characters, got %d", len(text))
 523  	}
 524  
 525  	copy(key[:], raw)
 526  
 527  	return key, nil
 528  }
 529  
 530  func hexDecode(text string) ([]byte, error) {
 531  	out := make([]byte, len(text)/2)
 532  
 533  	if len(text)%2 != 0 {
 534  		return nil, fmt.Errorf("odd number of hex characters")
 535  	}
 536  
 537  	for i := 0; i < len(out); i++ {
 538  		hi, ok := hexDigit(text[2*i])
 539  
 540  		if !ok {
 541  			return nil, fmt.Errorf("not hex")
 542  		}
 543  
 544  		lo, ok := hexDigit(text[2*i+1])
 545  
 546  		if !ok {
 547  			return nil, fmt.Errorf("not hex")
 548  		}
 549  
 550  		out[i] = hi<<4 | lo
 551  	}
 552  
 553  	return out, nil
 554  }
 555  
 556  func hexDigit(c byte) (byte, bool) {
 557  	switch {
 558  	case c >= '0' && c <= '9':
 559  		return c - '0', true
 560  	case c >= 'a' && c <= 'f':
 561  		return c - 'a' + 10, true
 562  	case c >= 'A' && c <= 'F':
 563  		return c - 'A' + 10, true
 564  	}
 565  
 566  	return 0, false
 567  }
 568  
 569  func firstNonEmpty(values ...string) string {
 570  	for _, value := range values {
 571  		if value != "" {
 572  			return value
 573  		}
 574  	}
 575  
 576  	return ""
 577  }
 578  
 579  // Redacted is the connection as it may be logged: the wallet and its relay, no secret. A
 580  // connection string that reaches a log is a wallet that can be drained, so there is no String
 581  // method to call by accident.
 582  func (c Connection) Redacted() string {
 583  	return "nostr+walletconnect://" + nostr.Hex(c.Wallet[:]) + "?relay=" + c.RelayURL + "&secret=REDACTED"
 584  }
 585