admin_test.go raw
1 package bridge
2
3 import (
4 "context"
5 "encoding/json"
6 "net"
7 "strings"
8 "testing"
9 "time"
10
11 "git.smesh.lol/nostrino/pkg/billing"
12 "git.smesh.lol/nostrino/pkg/listing"
13 "git.smesh.lol/nostrino/pkg/tunnel"
14 )
15
16 func adminServer() *Server {
17 return &Server{
18 cfg: Config{
19 Version: "test-0.3.0", Chains: []string{"btc", "blake"},
20 Nodes: map[string]Node{"btc": {Addr: "127.0.0.1:1"}, "blake": {Addr: "127.0.0.1:2"}},
21 Logf: func(string, ...any) {},
22 },
23 conns: make(map[net.Conn]struct{}),
24 done: make(chan struct{}),
25 pid: 7,
26 health: newHealthState(time.Now(), []string{"btc", "blake"}),
27 }
28 }
29
30 func runAdmin(t *testing.T, srv *Server, command string) (map[string]any, error) {
31 t.Helper()
32
33 body, err := json.Marshal(map[string]any{"cmd": command})
34
35 if err != nil {
36 t.Fatal(err)
37 }
38
39 reply, err := srv.adminCommand(context.Background(), [32]byte{1}, body)
40
41 if err != nil {
42 return nil, err
43 }
44
45 var out map[string]any
46
47 if err := json.Unmarshal(reply, &out); err != nil {
48 t.Fatalf("reply is not JSON: %v (%s)", err, reply)
49 }
50
51 if out["ok"] != true {
52 t.Fatalf("reply not ok: %v", out)
53 }
54
55 return out, nil
56 }
57
58 // TestAdminCommandsAnswer: the control channel exists so an operator never has to guess, so every
59 // command answers, including the ones that refuse.
60 func TestAdminCommandsAnswer(t *testing.T) {
61 srv := adminServer()
62
63 version, err := runAdmin(t, srv, "version")
64
65 if err != nil || version["version"] != "test-0.3.0" {
66 t.Fatalf("version: %v %v", version, err)
67 }
68
69 health, err := runAdmin(t, srv, "health")
70
71 if err != nil || health["health"] == nil {
72 t.Fatalf("health: %v %v", health, err)
73 }
74
75 // Without an update channel configured, the update commands refuse with a reason rather than
76 // doing something half-configured.
77 if _, err := runAdmin(t, srv, "update-check"); err == nil || !strings.Contains(err.Error(), "no update channel") {
78 t.Fatalf("update-check without config: %v", err)
79 }
80
81 if _, err := runAdmin(t, srv, "update-apply"); err == nil || !strings.Contains(err.Error(), "no update channel") {
82 t.Fatalf("update-apply without config: %v", err)
83 }
84
85 if _, err := runAdmin(t, srv, "drop-tables"); err == nil || !strings.Contains(err.Error(), "unknown command") {
86 t.Fatalf("unknown command: %v", err)
87 }
88 }
89
90 // TestTheAdminChannelIsOffWithoutTheDebugFlag: the listener is only given admin keys when the
91 // gateway was started with the capability, so there is no code path that receives a command on a
92 // production gateway.
93 func TestTheAdminChannelIsOffWithoutTheDebugFlag(t *testing.T) {
94 // Start would not install the handler; the observable state on a server configured without
95 // admins is that the tunnel listener has no admin handler configured.
96 listen := tunnel.ListenConfig{}
97
98 if listen.Admin != nil || len(listen.Admins) != 0 {
99 t.Fatal("an admin handler was configured without the debug flag")
100 }
101 }
102
103 // TestEveryAdministratorCanCommand: a gateway may be run by more than one person, and each of
104 // their keys is equally able to ask questions and to replace the binary. Nothing in the dispatch
105 // is tied to a single operator key.
106 func TestEveryAdministratorCanCommand(t *testing.T) {
107 srv := adminServer()
108 first, second := [32]byte{1}, [32]byte{2}
109
110 for _, peer := range [][32]byte{first, second} {
111 body, err := json.Marshal(map[string]any{"cmd": "version"})
112
113 if err != nil {
114 t.Fatal(err)
115 }
116
117 reply, err := srv.adminCommand(context.Background(), peer, body)
118
119 if err != nil || !strings.Contains(string(reply), `"ok":true`) {
120 t.Fatalf("administrator %x: %v %s", peer[:2], err, reply)
121 }
122 }
123 }
124
125 // TestOneAdministratorReplacesTheBinaryAtATime: two administrators can press update in the same
126 // second. The second is told who is working instead of queueing behind a download it would then
127 // refuse, and the lock is free again once the first operation has failed or finished.
128 func TestOneAdministratorReplacesTheBinaryAtATime(t *testing.T) {
129 srv := adminServer()
130 done, err := srv.beginControl([32]byte{0xd0, 0x23})
131
132 if err != nil {
133 t.Fatalf("first control: %v", err)
134 }
135
136 if _, err := srv.beginControl([32]byte{0x18, 0x56}); err == nil ||
137 !strings.Contains(err.Error(), "already replacing") {
138 t.Fatalf("second control while the first is running: %v", err)
139 }
140
141 done()
142
143 if _, err := srv.beginControl([32]byte{0x18, 0x56}); err != nil {
144 t.Fatalf("control after release: %v", err)
145 }
146 }
147
148 // TestTheOperatorSetsTheirMarginOverTheControlChannel: the price to list a swap is the gateway
149 // operator's, changed from wherever they are, and the wallet secret never comes back over the
150 // channel even to the person who sent it.
151 func TestTheOperatorSetsTheirMarginOverTheControlChannel(t *testing.T) {
152 srv := adminServer()
153 srv.cfg.BillingPath = t.TempDir() + "/billing.json"
154
155 body, _ := json.Marshal(map[string]any{"cmd": "billing-set", "args": map[string]string{
156 "swap_fee_percent": "0.5",
157 "min_fee_sats": "10",
158 "relay_sats_per_day": "1000",
159 }})
160
161 reply, err := srv.adminCommand(context.Background(), [32]byte{0x18, 0x56}, body)
162
163 if err != nil {
164 t.Fatalf("billing-set: %v", err)
165 }
166
167 if strings.Contains(string(reply), "secret") {
168 t.Fatalf("reply mentions the wallet secret: %s", reply)
169 }
170
171 var out struct {
172 Billing map[string]any `json:"billing"`
173 Example map[string]any `json:"example"`
174 }
175
176 if err := json.Unmarshal(reply, &out); err != nil {
177 t.Fatal(err)
178 }
179
180 if out.Billing["swap_fee_bps"] != float64(50) {
181 t.Fatalf("margin not stored: %v", out.Billing)
182 }
183
184 if out.Example["listing_fee_sats"] != float64(5000) {
185 t.Fatalf("the 0.5%% example is %v", out.Example["listing_fee_sats"])
186 }
187
188 // The price survives a restart, because it is on disk.
189 loaded, err := billing.Load(srv.cfg.BillingPath)
190
191 if err != nil || loaded.SwapFeeBPS != 50 || loaded.RelaySatsPerDay != 1000 {
192 t.Fatalf("stored settings: %+v %v", loaded, err)
193 }
194
195 // An unknown key is refused instead of quietly ignored.
196 bad, _ := json.Marshal(map[string]any{"cmd": "billing-set", "args": map[string]string{"comission": "50"}})
197
198 if _, err := srv.adminCommand(context.Background(), [32]byte{1}, bad); err == nil {
199 t.Fatal("a mistyped setting was accepted")
200 }
201 }
202
203 // TestAListingIsNotLodgedUntilItsInvoiceSettles: the quote is an invoice, the reply says plainly
204 // that nothing is lodged, and a gateway with no wallet refuses to quote rather than listing for
205 // free by accident.
206 func TestAListingIsNotLodgedUntilItsInvoiceSettles(t *testing.T) {
207 srv := adminServer()
208 srv.cfg.BillingPath = t.TempDir() + "/billing.json"
209 srv.cfg.ListingsPath = t.TempDir() + "/listings.json"
210
211 var err error
212
213 srv.listings, err = listing.Open(srv.cfg.ListingsPath)
214
215 if err != nil {
216 t.Fatal(err)
217 }
218
219 // A fee of zero needs no invoice: there is nothing to gate.
220 body, _ := json.Marshal(map[string]any{"cmd": "listing-quote", "args": map[string]string{
221 "id": "swap-1", "btc_sats": "1000000",
222 }})
223
224 reply, err := srv.adminCommand(context.Background(), [32]byte{1}, body)
225
226 if err != nil {
227 t.Fatalf("free quote: %v", err)
228 }
229
230 if !strings.Contains(string(reply), `"lodged":true`) {
231 t.Fatalf("a free listing was not lodgable: %s", reply)
232 }
233
234 // With a margin and no wallet, quoting must fail loudly.
235 set, _ := json.Marshal(map[string]any{"cmd": "billing-set", "args": map[string]string{
236 "swap_fee_percent": "0.5",
237 }})
238
239 if _, err := srv.adminCommand(context.Background(), [32]byte{1}, set); err != nil {
240 t.Fatal(err)
241 }
242
243 if _, err := srv.adminCommand(context.Background(), [32]byte{1}, body); err == nil ||
244 !strings.Contains(err.Error(), "no wallet is configured") {
245 t.Fatalf("a paid quote without a wallet: %v", err)
246 }
247
248 // A listing with no quote at all can never be lodged.
249 if _, err := srv.adminCommand(context.Background(), [32]byte{1},
250 []byte(`{"cmd":"listing-settled","args":{"id":"swap-2"}}`)); err == nil {
251 t.Fatal("settling an unquoted listing was accepted")
252 }
253 }
254