package bridge import ( "context" "encoding/json" "net" "strings" "testing" "time" "git.smesh.lol/nostrino/pkg/billing" "git.smesh.lol/nostrino/pkg/listing" "git.smesh.lol/nostrino/pkg/tunnel" ) func adminServer() *Server { return &Server{ cfg: Config{ Version: "test-0.3.0", Chains: []string{"btc", "blake"}, Nodes: map[string]Node{"btc": {Addr: "127.0.0.1:1"}, "blake": {Addr: "127.0.0.1:2"}}, Logf: func(string, ...any) {}, }, conns: make(map[net.Conn]struct{}), done: make(chan struct{}), pid: 7, health: newHealthState(time.Now(), []string{"btc", "blake"}), } } func runAdmin(t *testing.T, srv *Server, command string) (map[string]any, error) { t.Helper() body, err := json.Marshal(map[string]any{"cmd": command}) if err != nil { t.Fatal(err) } reply, err := srv.adminCommand(context.Background(), [32]byte{1}, body) if err != nil { return nil, err } var out map[string]any if err := json.Unmarshal(reply, &out); err != nil { t.Fatalf("reply is not JSON: %v (%s)", err, reply) } if out["ok"] != true { t.Fatalf("reply not ok: %v", out) } return out, nil } // TestAdminCommandsAnswer: the control channel exists so an operator never has to guess, so every // command answers, including the ones that refuse. func TestAdminCommandsAnswer(t *testing.T) { srv := adminServer() version, err := runAdmin(t, srv, "version") if err != nil || version["version"] != "test-0.3.0" { t.Fatalf("version: %v %v", version, err) } health, err := runAdmin(t, srv, "health") if err != nil || health["health"] == nil { t.Fatalf("health: %v %v", health, err) } // Without an update channel configured, the update commands refuse with a reason rather than // doing something half-configured. if _, err := runAdmin(t, srv, "update-check"); err == nil || !strings.Contains(err.Error(), "no update channel") { t.Fatalf("update-check without config: %v", err) } if _, err := runAdmin(t, srv, "update-apply"); err == nil || !strings.Contains(err.Error(), "no update channel") { t.Fatalf("update-apply without config: %v", err) } if _, err := runAdmin(t, srv, "drop-tables"); err == nil || !strings.Contains(err.Error(), "unknown command") { t.Fatalf("unknown command: %v", err) } } // TestTheAdminChannelIsOffWithoutTheDebugFlag: the listener is only given admin keys when the // gateway was started with the capability, so there is no code path that receives a command on a // production gateway. func TestTheAdminChannelIsOffWithoutTheDebugFlag(t *testing.T) { // Start would not install the handler; the observable state on a server configured without // admins is that the tunnel listener has no admin handler configured. listen := tunnel.ListenConfig{} if listen.Admin != nil || len(listen.Admins) != 0 { t.Fatal("an admin handler was configured without the debug flag") } } // TestEveryAdministratorCanCommand: a gateway may be run by more than one person, and each of // their keys is equally able to ask questions and to replace the binary. Nothing in the dispatch // is tied to a single operator key. func TestEveryAdministratorCanCommand(t *testing.T) { srv := adminServer() first, second := [32]byte{1}, [32]byte{2} for _, peer := range [][32]byte{first, second} { body, err := json.Marshal(map[string]any{"cmd": "version"}) if err != nil { t.Fatal(err) } reply, err := srv.adminCommand(context.Background(), peer, body) if err != nil || !strings.Contains(string(reply), `"ok":true`) { t.Fatalf("administrator %x: %v %s", peer[:2], err, reply) } } } // TestOneAdministratorReplacesTheBinaryAtATime: two administrators can press update in the same // second. The second is told who is working instead of queueing behind a download it would then // refuse, and the lock is free again once the first operation has failed or finished. func TestOneAdministratorReplacesTheBinaryAtATime(t *testing.T) { srv := adminServer() done, err := srv.beginControl([32]byte{0xd0, 0x23}) if err != nil { t.Fatalf("first control: %v", err) } if _, err := srv.beginControl([32]byte{0x18, 0x56}); err == nil || !strings.Contains(err.Error(), "already replacing") { t.Fatalf("second control while the first is running: %v", err) } done() if _, err := srv.beginControl([32]byte{0x18, 0x56}); err != nil { t.Fatalf("control after release: %v", err) } } // TestTheOperatorSetsTheirMarginOverTheControlChannel: the price to list a swap is the gateway // operator's, changed from wherever they are, and the wallet secret never comes back over the // channel even to the person who sent it. func TestTheOperatorSetsTheirMarginOverTheControlChannel(t *testing.T) { srv := adminServer() srv.cfg.BillingPath = t.TempDir() + "/billing.json" body, _ := json.Marshal(map[string]any{"cmd": "billing-set", "args": map[string]string{ "swap_fee_percent": "0.5", "min_fee_sats": "10", "relay_sats_per_day": "1000", }}) reply, err := srv.adminCommand(context.Background(), [32]byte{0x18, 0x56}, body) if err != nil { t.Fatalf("billing-set: %v", err) } if strings.Contains(string(reply), "secret") { t.Fatalf("reply mentions the wallet secret: %s", reply) } var out struct { Billing map[string]any `json:"billing"` Example map[string]any `json:"example"` } if err := json.Unmarshal(reply, &out); err != nil { t.Fatal(err) } if out.Billing["swap_fee_bps"] != float64(50) { t.Fatalf("margin not stored: %v", out.Billing) } if out.Example["listing_fee_sats"] != float64(5000) { t.Fatalf("the 0.5%% example is %v", out.Example["listing_fee_sats"]) } // The price survives a restart, because it is on disk. loaded, err := billing.Load(srv.cfg.BillingPath) if err != nil || loaded.SwapFeeBPS != 50 || loaded.RelaySatsPerDay != 1000 { t.Fatalf("stored settings: %+v %v", loaded, err) } // An unknown key is refused instead of quietly ignored. bad, _ := json.Marshal(map[string]any{"cmd": "billing-set", "args": map[string]string{"comission": "50"}}) if _, err := srv.adminCommand(context.Background(), [32]byte{1}, bad); err == nil { t.Fatal("a mistyped setting was accepted") } } // TestAListingIsNotLodgedUntilItsInvoiceSettles: the quote is an invoice, the reply says plainly // that nothing is lodged, and a gateway with no wallet refuses to quote rather than listing for // free by accident. func TestAListingIsNotLodgedUntilItsInvoiceSettles(t *testing.T) { srv := adminServer() srv.cfg.BillingPath = t.TempDir() + "/billing.json" srv.cfg.ListingsPath = t.TempDir() + "/listings.json" var err error srv.listings, err = listing.Open(srv.cfg.ListingsPath) if err != nil { t.Fatal(err) } // A fee of zero needs no invoice: there is nothing to gate. body, _ := json.Marshal(map[string]any{"cmd": "listing-quote", "args": map[string]string{ "id": "swap-1", "btc_sats": "1000000", }}) reply, err := srv.adminCommand(context.Background(), [32]byte{1}, body) if err != nil { t.Fatalf("free quote: %v", err) } if !strings.Contains(string(reply), `"lodged":true`) { t.Fatalf("a free listing was not lodgable: %s", reply) } // With a margin and no wallet, quoting must fail loudly. set, _ := json.Marshal(map[string]any{"cmd": "billing-set", "args": map[string]string{ "swap_fee_percent": "0.5", }}) if _, err := srv.adminCommand(context.Background(), [32]byte{1}, set); err != nil { t.Fatal(err) } if _, err := srv.adminCommand(context.Background(), [32]byte{1}, body); err == nil || !strings.Contains(err.Error(), "no wallet is configured") { t.Fatalf("a paid quote without a wallet: %v", err) } // A listing with no quote at all can never be lodged. if _, err := srv.adminCommand(context.Background(), [32]byte{1}, []byte(`{"cmd":"listing-settled","args":{"id":"swap-2"}}`)); err == nil { t.Fatal("settling an unquoted listing was accepted") } }