1 package billing
2 3 import (
4 "encoding/json"
5 "fmt"
6 "strings"
7 "time"
8 )
9 10 // KindControl is the kind a relay and a gateway use for control messages it must not store: a
11 // subscription query, a price change. The relay intercepts it, answers the signer, and forgets it.
12 const KindControl = 23199
13 14 // Control tags.
15 const (
16 // TagTopic names what the message is about, so one kind can carry several controls without
17 // them being ambiguous.
18 TagTopic = "t"
19 // TopicSubscription asks how much access the signer has left.
20 TopicSubscription = "subscription"
21 // TopicConfig applies settings to the relay (admin keys only).
22 TopicConfig = "config"
23 )
24 25 // SubscriptionQuery is what a gateway asks its relay, and the answer. The signature is the
26 // identity: a relay answers about the key that signed, and about no other key, so there is
27 // nothing in the message a caller could spoof.
28 type SubscriptionQuery struct{}
29 30 // SubscriptionAnswer is what a relay says about the signer's paid time.
31 type SubscriptionAnswer struct {
32 Gateway string `json:"gateway"`
33 Paid bool `json:"paid"`
34 RemainingSeconds int64 `json:"remaining_seconds"`
35 PaidUntil string `json:"paid_until,omitempty"`
36 RateSatsPerDay int64 `json:"rate_sats_per_day,omitempty"`
37 Now string `json:"now,omitempty"`
38 }
39 40 // Answer builds the answer for one gateway from the ledger.
41 func (l *Ledger) Answer(gateway string, now time.Time) SubscriptionAnswer {
42 gateway = strings.ToLower(strings.TrimSpace(gateway))
43 44 answer := SubscriptionAnswer{
45 Gateway: gateway,
46 Now: now.UTC().Format(time.RFC3339),
47 RateSatsPerDay: l.RateSatsPerDay,
48 Paid: l.Paid(gateway, now),
49 }
50 51 if subscription, ok := l.Subscriptions[gateway]; ok {
52 answer.PaidUntil = subscription.PaidUntil
53 }
54 55 answer.RemainingSeconds = int64(l.Remaining(gateway, now) / time.Second)
56 57 return answer
58 }
59 60 // Encode renders an answer or a config acknowledgement for a control reply.
61 func Encode(value any) ([]byte, error) {
62 body, err := json.Marshal(value)
63 64 if err != nil {
65 return nil, fmt.Errorf("billing: %w", err)
66 }
67 68 return body, nil
69 }
70