package billing import ( "encoding/json" "fmt" "strings" "time" ) // KindControl is the kind a relay and a gateway use for control messages it must not store: a // subscription query, a price change. The relay intercepts it, answers the signer, and forgets it. const KindControl = 23199 // Control tags. const ( // TagTopic names what the message is about, so one kind can carry several controls without // them being ambiguous. TagTopic = "t" // TopicSubscription asks how much access the signer has left. TopicSubscription = "subscription" // TopicConfig applies settings to the relay (admin keys only). TopicConfig = "config" ) // SubscriptionQuery is what a gateway asks its relay, and the answer. The signature is the // identity: a relay answers about the key that signed, and about no other key, so there is // nothing in the message a caller could spoof. type SubscriptionQuery struct{} // SubscriptionAnswer is what a relay says about the signer's paid time. type SubscriptionAnswer struct { Gateway string `json:"gateway"` Paid bool `json:"paid"` RemainingSeconds int64 `json:"remaining_seconds"` PaidUntil string `json:"paid_until,omitempty"` RateSatsPerDay int64 `json:"rate_sats_per_day,omitempty"` Now string `json:"now,omitempty"` } // Answer builds the answer for one gateway from the ledger. func (l *Ledger) Answer(gateway string, now time.Time) SubscriptionAnswer { gateway = strings.ToLower(strings.TrimSpace(gateway)) answer := SubscriptionAnswer{ Gateway: gateway, Now: now.UTC().Format(time.RFC3339), RateSatsPerDay: l.RateSatsPerDay, Paid: l.Paid(gateway, now), } if subscription, ok := l.Subscriptions[gateway]; ok { answer.PaidUntil = subscription.PaidUntil } answer.RemainingSeconds = int64(l.Remaining(gateway, now) / time.Second) return answer } // Encode renders an answer or a config acknowledgement for a control reply. func Encode(value any) ([]byte, error) { body, err := json.Marshal(value) if err != nil { return nil, fmt.Errorf("billing: %w", err) } return body, nil }