package bridge import ( "context" "encoding/json" "fmt" "time" "git.smesh.lol/nostrino/pkg/billing" "git.smesh.lol/nostrino/pkg/nostr" "git.smesh.lol/nostrino/pkg/relay" ) // checkSubscription asks a relay how much paid access this gateway has left. // // It is the gateway's side of the keysend subscription: the payment already said who paid, and // this asks how long it bought. A relay that does not answer, or does not charge, is not a // failure — it is reported as unknown, and the tunnel keeps working. func (s *Server) checkSubscription(ctx context.Context, relayURL, relayKeyHex string) (RelayHealth, bool) { if relayKeyHex == "" { return RelayHealth{}, false } var relayKey [32]byte raw, err := hexDecode(relayKeyHex) if err != nil || len(raw) != 32 { return RelayHealth{}, false } copy(relayKey[:], raw) transport, err := relay.DialTransport(relayURL) if err != nil { return RelayHealth{}, false } client, err := relay.New(transport, s.cfg.Key, relay.Options{RelayURL: relayURL}) if err != nil { return RelayHealth{}, false } defer client.Close() id := s.listener.PubKey() sub, err := client.Subscribe(nostr.Filter{ Kinds: []int{billing.KindControl}, Authors: []string{relayKeyHex}, Tags: map[string][]string{"p": {nostr.Hex(id[:])}}, }) if err != nil { return RelayHealth{}, false } waitCtx, cancel := context.WithTimeout(ctx, 8*time.Second) defer cancel() if err := client.WaitEOSE(waitCtx, sub); err != nil { return RelayHealth{}, false } event := &nostr.Event{ Kind: billing.KindControl, CreatedAt: time.Now().Unix(), Tags: nostr.Tags{{billing.TagTopic, billing.TopicSubscription}, {"p", relayKeyHex}}, Content: "{}", } if err := event.Sign(s.cfg.Key); err != nil { return RelayHealth{}, false } if err := client.Publish(waitCtx, event); err != nil { return RelayHealth{}, false } want := nostr.Hex(event.ID[:]) for { select { case <-waitCtx.Done(): return RelayHealth{}, false case answer, ok := <-sub.Events: if !ok { return RelayHealth{}, false } health, matched := decodeSubscription(answer, want) if matched { return health, true } } } } // decodeSubscription reads one answer to a subscription query. func decodeSubscription(event *nostr.Event, requestID string) (RelayHealth, bool) { matched := false for _, tag := range event.Tags { if len(tag) >= 2 && tag[0] == "e" && tag[1] == requestID { matched = true } } if !matched { return RelayHealth{}, false } var answer struct { Paid bool `json:"paid"` RemainingSeconds int64 `json:"remaining_seconds"` PaidUntil string `json:"paid_until"` RateSatsPerDay int64 `json:"rate_sats_per_day"` Blocked bool `json:"blocked"` } if err := json.Unmarshal([]byte(event.Content), &answer); err != nil { return RelayHealth{}, false } return RelayHealth{ Paid: answer.Paid, Blocked: answer.Blocked, RemainingSeconds: answer.RemainingSeconds, PaidUntil: answer.PaidUntil, RateSatsPerDay: answer.RateSatsPerDay, }, true } // subscriptionWarning says what a gateway operator needs to see before access lapses: nothing while // there is time, the countdown when it is short, and a plain reason when it has lapsed. func subscriptionWarning(health RelayHealth) string { switch { case health.Blocked: return "the relay has blocked this gateway; ask its operator" case health.RateSatsPerDay > 0 && !health.Paid: return fmt.Sprintf("no paid access at %d sats/day: renew with a keysend whose preimage is this gateway's key", health.RateSatsPerDay) case health.RateSatsPerDay > 0 && health.RemainingSeconds < int64(24*time.Hour/time.Second): return fmt.Sprintf("%.1f hours of paid access left", float64(health.RemainingSeconds)/3600) } return "" } func hexDecode(text string) ([]byte, error) { if len(text)%2 != 0 { return nil, fmt.Errorf("odd number of hex characters") } out := make([]byte, len(text)/2) 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 }