1 package bridge
2 3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "os"
8 "strings"
9 "time"
10 11 "git.smesh.lol/nostrino/pkg/release"
12 )
13 14 // adminRequest is one operator command.
15 type adminRequest struct {
16 Cmd string `json:"cmd"`
17 Args map[string]string `json:"args,omitempty"`
18 }
19 20 // adminCommand dispatches one operator command. It is reachable only when the gateway was started
21 // with the debug flag and at least one admin key, which the listener enforces before this runs.
22 //
23 // Every command answers. A control channel that goes silent when something is wrong is a channel
24 // an operator has to guess about, and a gateway that has to be shelled into is the problem this
25 // exists to remove.
26 func (s *Server) adminCommand(ctx context.Context, peer [32]byte, body []byte) ([]byte, error) {
27 var request adminRequest
28 29 if err := json.Unmarshal(body, &request); err != nil {
30 return nil, fmt.Errorf("the command is not JSON: %w", err)
31 }
32 33 s.cfg.Logf("bridge: admin command %q from %s", request.Cmd, shortHex(peer))
34 35 switch request.Cmd {
36 case "version":
37 return json.Marshal(map[string]any{
38 "ok": true, "version": s.cfg.Version, "chains": s.cfg.Chains,
39 })
40 case "health":
41 health := s.Health()
42 43 return json.Marshal(map[string]any{"ok": true, "health": health})
44 case "update-check":
45 if !s.updateConfigured() {
46 return nil, fmt.Errorf("no update channel configured (-update-url and -update-pubkey)")
47 }
48 49 manifest, err := release.Check(ctx, s.cfg.Update)
50 51 if err != nil {
52 return nil, err
53 }
54 55 return json.Marshal(map[string]any{"ok": true, "manifest": manifest})
56 case "update-apply":
57 if !s.updateConfigured() {
58 return nil, fmt.Errorf("no update channel configured (-update-url and -update-pubkey)")
59 }
60 61 done, err := s.beginControl(peer)
62 63 if err != nil {
64 return nil, err
65 }
66 67 result, err := release.Apply(ctx, s.cfg.Update)
68 69 if err != nil {
70 done()
71 72 return nil, err
73 }
74 75 s.cfg.Logf("bridge: admin update: installed %s, restarting into it", result.Version)
76 77 // The reply has to reach the operator before the process becomes the new binary, so the
78 // exec waits a moment. systemd sees the same PID, so nothing restarts it a second time.
79 go func() {
80 time.Sleep(2 * time.Second)
81 82 if err := release.Exec(result.Path); err != nil {
83 s.cfg.Logf("bridge: admin update: exec: %v", err)
84 }
85 }()
86 87 return json.Marshal(map[string]any{"ok": true, "update": result})
88 case "listing-quote":
89 btcSats, err := parseSats(request.Args["btc_sats"])
90 91 if err != nil {
92 return nil, err
93 }
94 95 quote, err := s.quoteListing(ctx, request.Args["id"], btcSats)
96 97 if err != nil {
98 return nil, err
99 }
100 101 quote["ok"] = true
102 103 return json.Marshal(quote)
104 case "listing-settled":
105 settled, err := s.settleListing(ctx, request.Args["id"])
106 107 if err != nil {
108 return nil, err
109 }
110 111 settled["ok"] = true
112 113 return json.Marshal(settled)
114 case "listings":
115 status := s.listingStatus()
116 status["ok"] = true
117 118 return json.Marshal(status)
119 case "billing":
120 return s.billingReply(nil)
121 case "billing-set":
122 return s.billingSet(peer, request.Args)
123 case "rollback":
124 done, err := s.beginControl(peer)
125 126 if err != nil {
127 return nil, err
128 }
129 130 path, err := os.Executable()
131 132 if err != nil {
133 done()
134 135 return nil, err
136 }
137 138 if err := release.Rollback(path); err != nil {
139 done()
140 141 return nil, err
142 }
143 144 s.cfg.Logf("bridge: admin rollback: restarting into the previous binary")
145 146 go func() {
147 time.Sleep(2 * time.Second)
148 149 if err := release.Exec(path); err != nil {
150 s.cfg.Logf("bridge: admin rollback: exec: %v", err)
151 }
152 }()
153 154 return json.Marshal(map[string]any{"ok": true, "rolled_back": path})
155 default:
156 return nil, fmt.Errorf("unknown command %q: version, health, update-check, update-apply, rollback",
157 request.Cmd)
158 }
159 }
160 161 // billingReply renders the current prices, with the wallet secret left out and a worked example at
162 // the size an operator is likely to meet. A price nobody can check against a real number is a
163 // price that gets mistyped.
164 func (s *Server) billingReply(example map[string]any) ([]byte, error) {
165 s.billingMu.Lock()
166 defer s.billingMu.Unlock()
167 168 return s.billingReplyLocked(example)
169 }
170 171 // billingReplyLocked renders the reply with the settings lock already held.
172 func (s *Server) billingReplyLocked(example map[string]any) ([]byte, error) {
173 shown := s.billing.Redacted()
174 rate := s.billing.SwapFeeBPS
175 minFee := s.billing.MinFeeSats
176 177 reply := map[string]any{"ok": true, "billing": shown}
178 179 if example != nil {
180 reply["changed"] = example
181 }
182 183 // The example is priced at one million sats, a round number an operator can reason about:
184 // 0.5% is 5000 sats.
185 sample := int64(1_000_000)
186 fee := (sample*int64(rate) + 9999) / 10000
187 188 if fee < minFee {
189 fee = minFee
190 }
191 192 reply["example"] = map[string]any{
193 "btc_sats": sample, "listing_fee_sats": fee, "swap_fee_bps": rate,
194 }
195 196 return json.Marshal(reply)
197 }
198 199 // billingSet changes the operator's prices. Only the keys that were named change, and an unknown
200 // key is refused: a mistyped setting must not silently leave the old price in place.
201 func (s *Server) billingSet(peer [32]byte, args map[string]string) ([]byte, error) {
202 if len(args) == 0 {
203 return nil, fmt.Errorf("billing-set needs at least one -arg key=value (wallet, swap_fee_bps, swap_fee_percent, min_fee_sats, relay_sats_per_day)")
204 }
205 206 s.billingMu.Lock()
207 defer s.billingMu.Unlock()
208 209 changed := make(map[string]any, len(args))
210 211 for key, value := range args {
212 if err := s.billing.Set(key, value); err != nil {
213 return nil, err
214 }
215 216 // The secret is never echoed back, even to the operator who just sent it.
217 if strings.EqualFold(key, "wallet") {
218 changed[key] = "configured"
219 } else {
220 changed[key] = value
221 }
222 }
223 224 s.billing.Touch(shortHex(peer))
225 226 if s.cfg.BillingPath != "" {
227 if err := s.billing.Save(s.cfg.BillingPath); err != nil {
228 return nil, err
229 }
230 }
231 232 s.cfg.Logf("bridge: billing updated by %s: %v", shortHex(peer), changed)
233 234 return s.billingReplyLocked(changed)
235 }
236 237 func (s *Server) updateConfigured() bool {
238 return s.cfg.Update.ManifestURL != "" && len(s.cfg.Update.PublicKey) > 0
239 }
240 241 // beginControl takes the release lock for a command that replaces the running binary, and returns
242 // the function that gives it back. A gateway can have several administrators, so two of them can
243 // press update or rollback at the same instant; the loser is told who is working rather than
244 // blocked behind a download it would then refuse as "not newer".
245 //
246 // The lock is deliberately not released when the command succeeds: the process is about to exec
247 // into the new binary, so there is nothing left to protect.
248 func (s *Server) beginControl(peer [32]byte) (func(), error) {
249 if !s.control.TryLock() {
250 holder, _ := s.controlHolder.Load().(string)
251 252 if holder == "" {
253 holder = "another administrator"
254 } else {
255 holder = "administrator " + holder
256 }
257 258 return nil, fmt.Errorf("%s is already replacing the running binary; one control operation at a time", holder)
259 }
260 261 s.controlHolder.Store(shortHex(peer))
262 263 return func() {
264 s.controlHolder.Store("")
265 s.control.Unlock()
266 }, nil
267 }
268 269 func shortHex(peer [32]byte) string {
270 const digits = "0123456789abcdef"
271 272 out := make([]byte, 0, 16)
273 274 for _, b := range peer[:8] {
275 out = append(out, digits[b>>4], digits[b&0xf])
276 }
277 278 return strings.ToLower(string(out))
279 }
280