package net import ( "encoding/json" "os" "path/filepath" "strconv" "strings" "time" "git.smesh.lol/torly/pkg/nostr" ) // kindControl is the intercepted kind. A control message is answered and then forgotten: it is // never stored, never broadcast to subscribers, and never acknowledged as a stored event. const kindControl = 23199 // Control topics. const ( controlSubscription = "subscription" controlConfig = "config" ) // Ledger is the relay's record of paid gateway time, written by the billing sidecar and read by // the relay. It is the same file shape the sidecar produces, so the two processes agree by reading // one document rather than by talking to each other. type Ledger struct { RateSatsPerDay int64 `json:"rate_sats_per_day"` Subscriptions map[string]Subscription `json:"subscriptions"` Watermarks map[string]int64 `json:"watermarks,omitempty"` // Blocked gateways are refused even while paid: payment buys time, not permission, and the // operator's decision does not erase what was paid. Blocked map[string]bool `json:"blocked,omitempty"` } // Subscription is one gateway's paid access. type Subscription struct { Gateway string `json:"gateway"` PaidUntil string `json:"paid_until"` TotalSats int64 `json:"total_sats"` } // ledgerPath is where the relay looks for the ledger. func (s *server) ledgerPath() string { if path := strings.TrimSpace(os.Getenv("TORLY_LEDGER_FILE")); path != "" { return path } if s.data.Cfg.DataDir == "" { return "" } return filepath.Join(s.data.Cfg.DataDir, "subscriptions.json") } // ledger reads the ledger. A missing file means the relay is not charging for access, which is a // policy decision, not an error. func (s *server) ledger() Ledger { path := s.ledgerPath() if path == "" { return Ledger{} } body, err := os.ReadFile(path) if err != nil { return Ledger{} } var ledger Ledger if err := json.Unmarshal(body, &ledger); err != nil { return Ledger{} } if ledger.Subscriptions == nil { ledger.Subscriptions = map[string]Subscription{} } return ledger } // subscriptionState reports whether a gateway may publish right now, and how long it has left. // // The default is zero and free: a relay with no rate set — no ledger file, an empty one, or one // that cannot be parsed — charges nothing and admits every gateway it authorises. Turning billing // on must be a deliberate act by the operator, never a side effect of a missing or damaged file. func (s *server) subscriptionState(gateway string) (allowed bool, remaining time.Duration) { ledger := s.ledger() if ledger.RateSatsPerDay <= 0 { return true, 0 } if ledger.Blocked[gateway] { return false, 0 } subscription, ok := ledger.Subscriptions[gateway] if !ok { return false, 0 } until, err := time.Parse(time.RFC3339, subscription.PaidUntil) if err != nil { return false, 0 } now := time.Now() if !until.After(now) { return false, 0 } return true, until.Sub(now) } // authorizedGateway reports whether the policy admits this key as a back end. It is the same list // the presence rule uses, so "who may announce" and "who may ask about their access" cannot drift. func (s *server) authorizedGateway(key string) bool { engine := s.data.Cfg.Policy if engine == nil { return false } for _, rule := range engine.Rules() { if len(rule.Authors) == 0 { continue } for _, kind := range rule.Kinds { if kind != 30333 && kind != 23197 { continue } for _, author := range rule.Authors { if strings.EqualFold(author, key) { return true } } } } return false } // adminKey reports whether this key may change the relay's settings. func (s *server) adminKey(key string) bool { for _, admin := range strings.Split(os.Getenv("TORLY_ADMINS"), ",") { if strings.EqualFold(strings.TrimSpace(admin), key) { return true } } return false } // handleControl answers one intercepted message and returns. It never stores anything: the caller // has already verified the signature, and the answer is sent as a normal event to whoever holds a // matching subscription. func (s *server) handleControl(ev *nostr.Event) { signer := nostr.Hex(ev.PubKey[:]) switch controlTopic(ev) { case controlSubscription: // A relay answers about the key that signed, and about no other key: there is nothing to // spoof because the question is "how long have I got". if !s.authorizedGateway(signer) && !s.adminKey(signer) { return } s.replyControl(ev, signer, controlSubscription, s.subscriptionAnswer(signer)) case controlConfig: if !s.adminKey(signer) { return } applied, err := s.applyConfig(ev) answer := map[string]any{"applied": applied} if err != nil { answer["error"] = err.Error() } s.replyControl(ev, signer, controlConfig, answer) } } // subscriptionAnswer is the body of the answer to a subscription query: the ledger's arithmetic, // about the key that asked. func (s *server) subscriptionAnswer(gateway string) map[string]any { allowed, remaining := s.subscriptionState(gateway) ledger := s.ledger() answer := map[string]any{ "gateway": gateway, "paid": allowed, "remaining_seconds": int64(remaining / time.Second), "rate_sats_per_day": ledger.RateSatsPerDay, "now": time.Now().UTC().Format(time.RFC3339), } if subscription, ok := ledger.Subscriptions[gateway]; ok { answer["paid_until"] = subscription.PaidUntil answer["total_sats"] = subscription.TotalSats } if ledger.Blocked[gateway] { answer["blocked"] = true } return answer } // controlTopic reads the t tag. func controlTopic(ev *nostr.Event) string { for _, tag := range ev.Tags { if len(tag) >= 2 && tag[0] == "t" { return strings.ToLower(tag[1]) } } return "" } // applyConfig changes what can be changed at runtime: the daily rate, and the operator's block // list. Settings that need a restart are refused rather than silently ignored. func (s *server) applyConfig(ev *nostr.Event) (map[string]string, error) { applied := map[string]string{} var body struct { RateSatsPerDay *int64 `json:"rate_sats_per_day"` Block string `json:"block,omitempty"` Unblock string `json:"unblock,omitempty"` } if err := json.Unmarshal([]byte(ev.Content), &body); err != nil { return applied, err } ledger := s.ledger() if body.RateSatsPerDay != nil { rate := *body.RateSatsPerDay if rate < 0 { rate = 0 } ledger.RateSatsPerDay = rate applied["rate_sats_per_day"] = strconv.FormatInt(rate, 10) } if ledger.Blocked == nil { ledger.Blocked = map[string]bool{} } if key := strings.ToLower(strings.TrimSpace(body.Block)); key != "" { ledger.Blocked[key] = true applied["blocked"] = key } if key := strings.ToLower(strings.TrimSpace(body.Unblock)); key != "" { delete(ledger.Blocked, key) applied["unblocked"] = key } path := s.ledgerPath() if path == "" { return applied, os.ErrNotExist } body2, err := json.MarshalIndent(ledger, "", " ") if err != nil { return applied, err } if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return applied, err } if err := os.WriteFile(path, append(body2, '\n'), 0o600); err != nil { return applied, err } return applied, nil } // replyControl signs an answer from the relay and broadcasts it. It reaches the asker because the // asker subscribed to this kind from this relay's key; nobody else's subscription matches the // p tag, so the answer is private in the only sense that matters: it is addressed. func (s *server) replyControl(request *nostr.Event, to, topic string, body map[string]any) { content, err := json.Marshal(body) if err != nil { return } answer := &nostr.Event{ Kind: kindControl, CreatedAt: time.Now().Unix(), Tags: nostr.Tags{ {"t", topic}, {"p", to}, {"e", nostr.Hex(request.ID[:])}, }, Content: string(content), } if err := answer.Sign(s.data.RelaySk); err != nil { return } s.broadcast(answer) } // paidGateway decides whether a gateway may publish a stored or bulk kind. When the relay charges, // an unpaid gateway is refused; the operator's block list is consulted first, so a paid gateway can // still be stopped. func (s *server) paidGateway(key string) (bool, string) { allowed, _ := s.subscriptionState(key) if allowed { return true, "" } ledger := s.ledger() if ledger.Blocked[key] { return false, "blocked: this gateway is not permitted to serve on this relay" } return false, "payment-required: this gateway's access to this relay has lapsed" }