package main import ( "encoding/hex" "encoding/json" "os" "path/filepath" "testing" "time" "github.com/nbd-wtf/go-nostr" ) // A real invoice produced by this wallet, with the payment hash as recorded by // the wallet itself (Alby Hub's transactions table). The payment hash is // sha256(preimage), so the two are independent and this is a true oracle. const ( testInvoice = "lnbc90n1p4vk36jhp5h7w2vtz3jnqd5h8thhr9qs3fpa8k2uczf5df68205da3rfp9nmaqnp4qf0pqvflcvcn99wjr5kq45nsffzpjfqmac3f7nm6ddph6uqzn5stqpp59lav9jkvznj78ucrjns040wzf0c24vg6m8wturzrmlalmle68w9qsp5cdscre7tducplmzqapx5v4ur22kldulxzw9vn8jvvpryt3h643ks9qyysgqcqzp2xqyz5vqrzjqvdnqyc82a9maxu6c7mee0shqr33u4z9z04wpdwhf96gxzpln8jcrapyqqqqqqzx4cqqqqqqqqqqqqqq2qrzjqw9fu4j39mycmg440ztkraa03u5qhtuc5zfgydsv6ml38qd4azymlapyqqqqqqq67yqqqqlgqqqq86qqjq8eu3n2yr4hhfyvak0lrn2akanqhp7kknn43qcy99q9gldgxkaeu529xfzzxpv8ysm794nauhtd4auwly2c6t43427mvezrapswr88rcp6un06y" testPaymentHash = "2ffac2cacc14e5e3f30394e0fabdc24bf0aab11ad9dcbe0c43dffbfdff3a3b8a" ) func TestPaymentHashFromInvoice(t *testing.T) { got, err := paymentHashFromInvoice(testInvoice) if err != nil { t.Fatalf("paymentHashFromInvoice: %v", err) } if got != testPaymentHash { t.Fatalf("payment hash mismatch\n got: %s\nwant: %s", got, testPaymentHash) } } func TestPaymentHashFromInvoiceRejectsGarbage(t *testing.T) { for _, bad := range []string{"", "notaninvoice", "lnbc1", "lnbc90n1qqqqqqqq"} { if _, err := paymentHashFromInvoice(bad); err == nil { t.Fatalf("expected an error for %q", bad) } } } // buildZapRequest creates a signed zap request for tests. func buildZapRequest(t *testing.T, sk string, amountMsat int64, tags [][]string) (string, *ZapRequest) { t.Helper() ev := nostr.Event{ Kind: zapRequestKind, CreatedAt: nostr.Now(), Content: "test zap", } for _, tg := range tags { ev.Tags = append(ev.Tags, nostr.Tag(tg)) } // amount tag must match the query amount when present. ev.Tags = append(ev.Tags, nostr.Tag{"amount", itoa(amountMsat)}) ev.Tags = append(ev.Tags, nostr.Tag{"relays", "wss://relay.example.com"}) if err := ev.Sign(sk); err != nil { t.Fatalf("sign zap request: %v", err) } raw := ev.String() var zr ZapRequest if err := json.Unmarshal([]byte(raw), &zr); err != nil { t.Fatalf("unmarshal zap request: %v", err) } return raw, &zr } func itoa(n int64) string { if n == 0 { return "0" } neg := n < 0 if neg { n = -n } var b [20]byte i := len(b) for n > 0 { i-- b[i] = byte('0' + n%10) n /= 10 } if neg { i-- b[i] = '-' } return string(b[i:]) } func TestValidateZapRequest(t *testing.T) { sk := nostr.GeneratePrivateKey() pk, _ := nostr.GetPublicKey(sk) amount := int64(21000) raw, zr := buildZapRequest(t, sk, amount, [][]string{{"p", pk}}) _ = raw relays, err := validateZapRequest(zr, uint64(amount), "") if err != nil { t.Fatalf("valid zap request rejected: %v", err) } if len(relays) != 1 || relays[0] != "wss://relay.example.com" { t.Fatalf("unexpected relays: %v", relays) } // Amount mismatch must be rejected. if _, err := validateZapRequest(zr, uint64(amount)+1, ""); err == nil { t.Fatal("expected an amount mismatch error") } // Tampered signature must be rejected. bad := *zr bad.Sig = "00" + zr.Sig[2:] if _, err := validateZapRequest(&bad, uint64(amount), ""); err == nil { t.Fatal("expected an invalid signature error") } // Missing p tag must be rejected. _, zrNoP := buildZapRequest(t, sk, amount, nil) if _, err := validateZapRequest(zrNoP, uint64(amount), ""); err == nil { t.Fatal("expected a missing p tag error") } // Stale created_at must be rejected. _, zrStale := buildZapRequest(t, sk, amount, [][]string{{"p", pk}}) zrStale.CreatedAt = time.Now().Add(-48 * time.Hour).Unix() if _, err := validateZapRequest(zrStale, uint64(amount), ""); err == nil { t.Fatal("expected a stale created_at error") } } // TestReceiptMatchesAdvertisedKey is the property clients enforce: the receipt // must be signed by the pubkey the payRequest advertised, and its description // tag must hash to the invoice's description hash. func TestReceiptMatchesAdvertisedKey(t *testing.T) { dir := t.TempDir() z, err := newZapServer("aa"+repeat("bb", 31), filepath.Join(dir, "zaps.json")) if err != nil { t.Fatalf("newZapServer: %v", err) } sk := nostr.GeneratePrivateKey() pk, _ := nostr.GetPublicKey(sk) raw, zr := buildZapRequest(t, sk, 21000, [][]string{{"p", pk}, {"e", repeat("ab", 32)}}) ev, err := z.buildReceipt(zr, raw, testInvoice, "deadbeef", time.Now()) if err != nil { t.Fatalf("buildReceipt: %v", err) } if ev.PubKey != z.pubkey { t.Fatalf("receipt pubkey %s != advertised %s", ev.PubKey, z.pubkey) } if ok, err := ev.CheckSignature(); err != nil || !ok { t.Fatalf("receipt signature invalid: ok=%v err=%v", ok, err) } // Appendix E: kind, empty content, description == the zap request, P tag. if ev.Kind != zapReceiptKind { t.Fatalf("receipt kind = %d, want %d", ev.Kind, zapReceiptKind) } if ev.Content != "" { t.Fatalf("receipt content should be empty, got %q", ev.Content) } var desc, bolt11, pTag string var pUpper bool for _, tg := range ev.Tags { switch tg[0] { case "description": desc = tg[1] case "bolt11": bolt11 = tg[1] case "P": pUpper = true case "p": pTag = tg[1] } } if desc != raw { t.Fatal("description tag is not the exact zap request bytes") } if bolt11 != testInvoice { t.Fatal("bolt11 tag does not match the invoice") } if !pUpper { t.Fatal("receipt is missing the P (sender) tag") } if pTag != pk { t.Fatalf("receipt p tag = %s, want the recipient %s", pTag, pk) } } // TestZapStateRoundTrip covers persistence and the do-not-receipt-twice guard. func TestZapStateRoundTrip(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "zaps.json") z, err := newZapServer("cc"+repeat("dd", 31), path) if err != nil { t.Fatalf("newZapServer: %v", err) } p := &pendingZap{ PaymentHash: testPaymentHash, ZapRequest: `{"kind":9734}`, Relays: []string{"wss://relay.example.com"}, AmountMsat: 21000, Invoice: testInvoice, CreatedAt: time.Now(), } if err := z.remember(p); err != nil { t.Fatalf("remember: %v", err) } if !z.hasPending(testPaymentHash) { t.Fatal("pending zap not recorded") } // Reload from disk. z2, err := newZapServer("cc"+repeat("dd", 31), path) if err != nil { t.Fatalf("reload: %v", err) } got := z2.pending(testPaymentHash) if got == nil { t.Fatal("pending zap did not survive a reload") } if got.Invoice != testInvoice || got.AmountMsat != 21000 { t.Fatalf("reloaded zap mismatch: %+v", got) } if err := z2.markReceipted(testPaymentHash, "eventid"); err != nil { t.Fatalf("markReceipted: %v", err) } if z2.hasPending(testPaymentHash) { t.Fatal("zap still pending after being receipted") } if !z2.alreadyReceipted(testPaymentHash) { t.Fatal("receipt not recorded") } } // TestParseAndValidateZapCanonicalises is a regression test for a real hole // found in manual testing: the description hash was originally taken over the // raw `nostr` query bytes, so a client could pair a valid signed event with // arbitrary extra JSON and get an invoice committing to text no receipt could // ever match. The hash must cover the canonical encoding the id/signature sign. func TestParseAndValidateZapCanonicalises(t *testing.T) { sk := nostr.GeneratePrivateKey() pk, _ := nostr.GetPublicKey(sk) amount := int64(21000) raw, _ := buildZapRequest(t, sk, amount, [][]string{{"p", pk}}) zr, canonical, relays, err := parseAndValidateZap(raw, uint64(amount)) if err != nil { t.Fatalf("valid zap request rejected: %v", err) } if len(relays) == 0 { t.Fatal("no relays returned") } // The canonical form must round-trip to an event that still verifies; that // is what makes it safe to hash. var reZR ZapRequest if err := json.Unmarshal([]byte(canonical), &reZR); err != nil { t.Fatalf("canonical form is not JSON: %v", err) } if reZR.ID != zr.ID || reZR.Sig != zr.Sig || reZR.PubKey != zr.PubKey { t.Fatalf("canonical form changed the identity:\n %+v\n %+v", reZR, zr) } if ok, err := zapEvent(&reZR).CheckSignature(); err != nil || !ok { t.Fatalf("canonical form does not verify: ok=%v err=%v", ok, err) } // Trailing whitespace must not change the canonical form or the hash. _, canonical2, _, err := parseAndValidateZap(raw+"\n ", uint64(amount)) if err != nil { t.Fatalf("whitespace-padded request rejected: %v", err) } if canonical2 != canonical { t.Fatal("whitespace changed the canonical form") } // A tampered id (whose signature no longer matches) must be rejected. This // is the case that exposed the original bug during manual testing. var tampered ZapRequest if err := json.Unmarshal([]byte(raw), &tampered); err != nil { t.Fatal(err) } if tampered.ID[0] == '1' { tampered.ID = "2" + tampered.ID[1:] } else { tampered.ID = "1" + tampered.ID[1:] } tamperedRaw, err := json.Marshal(tampered) if err != nil { t.Fatal(err) } if _, _, _, err := parseAndValidateZap(string(tamperedRaw), uint64(amount)); err == nil { t.Fatal("tampered event id was accepted") } } func repeat(s string, n int) string { out := make([]byte, 0, len(s)*n) for i := 0; i < n; i++ { out = append(out, s...) } return string(out) } // TestZapKeyIsStable ensures the advertised nostrPubkey does not change across // restarts, since clients reject a receipt signed by a different key. func TestZapKeyIsStable(t *testing.T) { secret := "ee" + repeat("ff", 31) a, err := loadOrCreateZapKey(secret) if err != nil { t.Fatalf("loadOrCreateZapKey: %v", err) } b, err := loadOrCreateZapKey(secret) if err != nil { t.Fatalf("loadOrCreateZapKey: %v", err) } if a != b { t.Fatal("derived zap key is not stable") } c, _ := loadOrCreateZapKey("11" + repeat("22", 31)) if a == c { t.Fatal("different NWC secrets produced the same zap key") } os.Setenv("ZAP_SECRET", secret) defer os.Unsetenv("ZAP_SECRET") explicit, err := loadOrCreateZapKey("ignored") if err != nil { t.Fatalf("explicit ZAP_SECRET: %v", err) } if explicit != secret { t.Fatal("ZAP_SECRET was not honoured") } } // TestPublicHostRefusesUnknownHosts covers a real hole: the Host header was // reflected verbatim into the callback and metadata, so a request could mint a // payRequest (and an invoice from this wallet) claiming to be a lightning // address on someone else's domain. func TestPublicHostRefusesUnknownHosts(t *testing.T) { saveDomain, saveAllowed, saveUser := config.Domain, config.AllowedHosts, config.Username defer func() { config.Domain, config.AllowedHosts, config.Username = saveDomain, saveAllowed, saveUser }() config.Domain = "mleku.dev" config.AllowedHosts = []string{"mleku.dev", "smesh.lol"} config.Username = "me" // Served hosts are accepted, including with a port (which must be stripped). for in, want := range map[string]string{ "mleku.dev": "mleku.dev", "smesh.lol": "smesh.lol", "MLEKU.DEV": "mleku.dev", "mleku.dev:443": "mleku.dev", "mleku.dev:8096": "mleku.dev", "mleku.dev.": "mleku.dev", } { got, err := publicHost(in) if err != nil { t.Fatalf("publicHost(%q) rejected a served host: %v", in, err) } if got != want { t.Fatalf("publicHost(%q) = %q, want %q", in, got, want) } } // Anything else must be refused rather than reflected. for _, bad := range []string{ "evil.com", "mleku.dev.evil.com", "evil.com#mleku.dev", "mleku.dev/path", "not a host", "a..b", "-x.dev", "mleku..dev", } { if got, err := publicHost(bad); err == nil { t.Fatalf("publicHost(%q) accepted an unserved host as %q", bad, got) } } // No Host at all falls back to the configured domain. got, err := publicHost("") if err != nil || got != "mleku.dev" { t.Fatalf("empty host = %q, %v; want mleku.dev", got, err) } } // TestValidUsername ensures the catch-all route cannot invent addresses such as // the empty username (which produced "@mleku.dev") or arbitrary users. func TestValidUsername(t *testing.T) { saveUser := config.Username defer func() { config.Username = saveUser }() config.Username = "me" if err := validUsername("me"); err != nil { t.Fatalf("configured username rejected: %v", err) } for _, bad := range []string{"", "someoneelse", "ME", "me ", "../me", "@"} { if err := validUsername(bad); err == nil { t.Fatalf("username %q was accepted", bad) } } } // TestPendingCap bounds unpaid-zap state so invoice spam cannot grow it forever. func TestPendingCap(t *testing.T) { dir := t.TempDir() z, err := newZapServer("ab"+repeat("cd", 31), filepath.Join(dir, "zaps.json")) if err != nil { t.Fatal(err) } for i := 0; i < maxPendingZaps; i++ { h := repeat("00", 32) h = hex.EncodeToString(append([]byte{byte(i >> 8), byte(i)}, make([]byte, 30)...)) if err := z.remember(&pendingZap{PaymentHash: h, CreatedAt: time.Now()}); err != nil { t.Fatalf("remember %d: %v", i, err) } } if err := z.remember(&pendingZap{PaymentHash: repeat("ff", 32), CreatedAt: time.Now()}); err == nil { t.Fatal("expected the pending cap to reject a new zap") } // Re-remembering an existing hash must still succeed once full. if err := z.remember(&pendingZap{PaymentHash: repeat("00", 32), CreatedAt: time.Now()}); err != nil { t.Fatalf("updating an existing pending zap failed: %v", err) } }