package bridge import ( "context" "encoding/json" "fmt" "os" "strings" "time" "git.smesh.lol/nostrino/pkg/release" ) // adminRequest is one operator command. type adminRequest struct { Cmd string `json:"cmd"` Args map[string]string `json:"args,omitempty"` } // adminCommand dispatches one operator command. It is reachable only when the gateway was started // with the debug flag and at least one admin key, which the listener enforces before this runs. // // Every command answers. A control channel that goes silent when something is wrong is a channel // an operator has to guess about, and a gateway that has to be shelled into is the problem this // exists to remove. func (s *Server) adminCommand(ctx context.Context, peer [32]byte, body []byte) ([]byte, error) { var request adminRequest if err := json.Unmarshal(body, &request); err != nil { return nil, fmt.Errorf("the command is not JSON: %w", err) } s.cfg.Logf("bridge: admin command %q from %s", request.Cmd, shortHex(peer)) switch request.Cmd { case "version": return json.Marshal(map[string]any{ "ok": true, "version": s.cfg.Version, "chains": s.cfg.Chains, }) case "health": health := s.Health() return json.Marshal(map[string]any{"ok": true, "health": health}) case "update-check": if !s.updateConfigured() { return nil, fmt.Errorf("no update channel configured (-update-url and -update-pubkey)") } manifest, err := release.Check(ctx, s.cfg.Update) if err != nil { return nil, err } return json.Marshal(map[string]any{"ok": true, "manifest": manifest}) case "update-apply": if !s.updateConfigured() { return nil, fmt.Errorf("no update channel configured (-update-url and -update-pubkey)") } done, err := s.beginControl(peer) if err != nil { return nil, err } result, err := release.Apply(ctx, s.cfg.Update) if err != nil { done() return nil, err } s.cfg.Logf("bridge: admin update: installed %s, restarting into it", result.Version) // The reply has to reach the operator before the process becomes the new binary, so the // exec waits a moment. systemd sees the same PID, so nothing restarts it a second time. go func() { time.Sleep(2 * time.Second) if err := release.Exec(result.Path); err != nil { s.cfg.Logf("bridge: admin update: exec: %v", err) } }() return json.Marshal(map[string]any{"ok": true, "update": result}) case "listing-quote": btcSats, err := parseSats(request.Args["btc_sats"]) if err != nil { return nil, err } quote, err := s.quoteListing(ctx, request.Args["id"], btcSats) if err != nil { return nil, err } quote["ok"] = true return json.Marshal(quote) case "listing-settled": settled, err := s.settleListing(ctx, request.Args["id"]) if err != nil { return nil, err } settled["ok"] = true return json.Marshal(settled) case "listings": status := s.listingStatus() status["ok"] = true return json.Marshal(status) case "billing": return s.billingReply(nil) case "billing-set": return s.billingSet(peer, request.Args) case "rollback": done, err := s.beginControl(peer) if err != nil { return nil, err } path, err := os.Executable() if err != nil { done() return nil, err } if err := release.Rollback(path); err != nil { done() return nil, err } s.cfg.Logf("bridge: admin rollback: restarting into the previous binary") go func() { time.Sleep(2 * time.Second) if err := release.Exec(path); err != nil { s.cfg.Logf("bridge: admin rollback: exec: %v", err) } }() return json.Marshal(map[string]any{"ok": true, "rolled_back": path}) default: return nil, fmt.Errorf("unknown command %q: version, health, update-check, update-apply, rollback", request.Cmd) } } // billingReply renders the current prices, with the wallet secret left out and a worked example at // the size an operator is likely to meet. A price nobody can check against a real number is a // price that gets mistyped. func (s *Server) billingReply(example map[string]any) ([]byte, error) { s.billingMu.Lock() defer s.billingMu.Unlock() return s.billingReplyLocked(example) } // billingReplyLocked renders the reply with the settings lock already held. func (s *Server) billingReplyLocked(example map[string]any) ([]byte, error) { shown := s.billing.Redacted() rate := s.billing.SwapFeeBPS minFee := s.billing.MinFeeSats reply := map[string]any{"ok": true, "billing": shown} if example != nil { reply["changed"] = example } // The example is priced at one million sats, a round number an operator can reason about: // 0.5% is 5000 sats. sample := int64(1_000_000) fee := (sample*int64(rate) + 9999) / 10000 if fee < minFee { fee = minFee } reply["example"] = map[string]any{ "btc_sats": sample, "listing_fee_sats": fee, "swap_fee_bps": rate, } return json.Marshal(reply) } // billingSet changes the operator's prices. Only the keys that were named change, and an unknown // key is refused: a mistyped setting must not silently leave the old price in place. func (s *Server) billingSet(peer [32]byte, args map[string]string) ([]byte, error) { if len(args) == 0 { 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)") } s.billingMu.Lock() defer s.billingMu.Unlock() changed := make(map[string]any, len(args)) for key, value := range args { if err := s.billing.Set(key, value); err != nil { return nil, err } // The secret is never echoed back, even to the operator who just sent it. if strings.EqualFold(key, "wallet") { changed[key] = "configured" } else { changed[key] = value } } s.billing.Touch(shortHex(peer)) if s.cfg.BillingPath != "" { if err := s.billing.Save(s.cfg.BillingPath); err != nil { return nil, err } } s.cfg.Logf("bridge: billing updated by %s: %v", shortHex(peer), changed) return s.billingReplyLocked(changed) } func (s *Server) updateConfigured() bool { return s.cfg.Update.ManifestURL != "" && len(s.cfg.Update.PublicKey) > 0 } // beginControl takes the release lock for a command that replaces the running binary, and returns // the function that gives it back. A gateway can have several administrators, so two of them can // press update or rollback at the same instant; the loser is told who is working rather than // blocked behind a download it would then refuse as "not newer". // // The lock is deliberately not released when the command succeeds: the process is about to exec // into the new binary, so there is nothing left to protect. func (s *Server) beginControl(peer [32]byte) (func(), error) { if !s.control.TryLock() { holder, _ := s.controlHolder.Load().(string) if holder == "" { holder = "another administrator" } else { holder = "administrator " + holder } return nil, fmt.Errorf("%s is already replacing the running binary; one control operation at a time", holder) } s.controlHolder.Store(shortHex(peer)) return func() { s.controlHolder.Store("") s.control.Unlock() }, nil } func shortHex(peer [32]byte) string { const digits = "0123456789abcdef" out := make([]byte, 0, 16) for _, b := range peer[:8] { out = append(out, digits[b>>4], digits[b&0xf]) } return strings.ToLower(string(out)) }