// Package billing holds what an operator charges and what they pay: the margin on a swap listing, // the rate for tunnel access, and the wallet that moves the sats. // // It is a file because it must be edited by an operator who is not at the machine — the gateway's // control channel writes it — and because a price that lives only in memory is a price that resets // on the next restart. The wallet connection string is a credential: the file is written 0600 and // every read of it redacts the secret. package billing import ( "encoding/json" "errors" "fmt" "os" "path/filepath" "strings" "time" "git.smesh.lol/nostrino/pkg/nwc" ) // Settings is one gateway's or relay's money configuration. type Settings struct { // Wallet is the NIP-47 connection string. Empty means no wallet is connected, in which case // nothing is charged: a gateway that cannot take payment must not pretend to. Wallet string `json:"wallet,omitempty"` // SwapFeeBPS is the operator's margin on a swap listing, in basis points of the BTC leg: // 50 is 0.5%, 100 is 1%. SwapFeeBPS int `json:"swap_fee_bps"` // MinFeeSats is the floor, so a tiny swap still costs something to register. MinFeeSats int64 `json:"min_fee_sats"` // RelaySatsPerDay is what tunnel access costs, per day, in sats. On a gateway it is the price // it pays its relay; a relay publishes it as what it charges. RelaySatsPerDay int64 `json:"relay_sats_per_day"` // UpdatedAt and UpdatedBy record who changed the price and when, because a price is the kind // of thing that needs explaining later. UpdatedAt string `json:"updated_at,omitempty"` UpdatedBy string `json:"updated_by,omitempty"` } // MaxFeeBPS is the highest margin this software will accept. A typo that turns 0.5% into 50% // would be a fee nobody agreed to, so the bound is enforced rather than documented. const MaxFeeBPS = 2000 // Load reads the settings file. A missing file is an empty configuration, not an error: a new // gateway starts with no prices and no wallet. func Load(path string) (Settings, error) { body, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return Settings{}, nil } if err != nil { return Settings{}, fmt.Errorf("billing: %w", err) } var settings Settings if err := json.Unmarshal(body, &settings); err != nil { return Settings{}, fmt.Errorf("billing: %s: %w", path, err) } if err := settings.Validate(); err != nil { return Settings{}, fmt.Errorf("billing: %s: %w", path, err) } return settings, nil } // Save writes the settings atomically: a crash in the middle of a price change must leave either // the old price or the new one, never a half-written file. func (s Settings) Save(path string) error { if err := s.Validate(); err != nil { return err } body, err := json.MarshalIndent(s, "", " ") if err != nil { return fmt.Errorf("billing: %w", err) } if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return fmt.Errorf("billing: %w", err) } stage, err := os.CreateTemp(filepath.Dir(path), ".billing-*") if err != nil { return fmt.Errorf("billing: %w", err) } name := stage.Name() if err := os.Chmod(name, 0o600); err != nil { stage.Close() os.Remove(name) return fmt.Errorf("billing: %w", err) } if _, err := stage.Write(append(body, '\n')); err != nil { stage.Close() os.Remove(name) return fmt.Errorf("billing: %w", err) } if err := stage.Sync(); err != nil { stage.Close() os.Remove(name) return fmt.Errorf("billing: %w", err) } if err := stage.Close(); err != nil { os.Remove(name) return fmt.Errorf("billing: %w", err) } if err := os.Rename(name, path); err != nil { os.Remove(name) return fmt.Errorf("billing: %w", err) } return nil } // Validate refuses a configuration that would charge something the operator did not mean. func (s *Settings) Validate() error { if s.SwapFeeBPS < 0 || s.SwapFeeBPS > MaxFeeBPS { return fmt.Errorf("swap fee is %d basis points, outside 0..%d", s.SwapFeeBPS, MaxFeeBPS) } if s.MinFeeSats < 0 { return fmt.Errorf("minimum fee is %d sats", s.MinFeeSats) } if s.RelaySatsPerDay < 0 { return fmt.Errorf("relay rate is %d sats per day", s.RelaySatsPerDay) } if s.Wallet != "" { if _, err := nwc.ParseURI(s.Wallet); err != nil { return err } } return nil } // ListingFee is what this gateway charges to register a swap of the given BTC size: the operator's // margin, with a floor. func (s Settings) ListingFee(btcSats int64) int64 { if btcSats <= 0 || s.SwapFeeBPS <= 0 { return 0 } // Round up: a fee that rounds to zero is a fee that is not charged. fee := (btcSats*int64(s.SwapFeeBPS) + 9999) / 10000 if fee < s.MinFeeSats { fee = s.MinFeeSats } return fee } // AccessFee prices a period of tunnel access at the daily rate, rounding part days up. func (s Settings) AccessFee(period time.Duration) int64 { if s.RelaySatsPerDay <= 0 || period <= 0 { return 0 } day := 24 * time.Hour days := int64((period + day - 1) / day) return s.RelaySatsPerDay * days } // Redacted is the settings as they may be shown or logged: the wallet is identified by its public // key and relay, never by the secret that is half of the connection string. func (s Settings) Redacted() map[string]any { out := map[string]any{ "swap_fee_bps": s.SwapFeeBPS, "swap_fee_percent": float64(s.SwapFeeBPS) / 100, "min_fee_sats": s.MinFeeSats, "relay_sats_per_day": s.RelaySatsPerDay, "wallet_configured": s.Wallet != "", } if s.UpdatedAt != "" { out["updated_at"] = s.UpdatedAt } if s.UpdatedBy != "" { out["updated_by"] = s.UpdatedBy } if s.Wallet != "" { if conn, err := nwc.ParseURI(s.Wallet); err == nil { out["wallet_pubkey"] = hexKey(conn.Wallet) out["wallet_relay"] = conn.RelayURL } } return out } // Set applies one key=value change. Unknown keys are refused rather than ignored: an operator who // mistypes a setting must be told, not silently charged the old price. func (s *Settings) Set(key, value string) error { value = strings.TrimSpace(value) switch strings.ToLower(strings.TrimSpace(key)) { case "swap_fee_bps": n, err := parseInt(value) if err != nil { return fmt.Errorf("swap_fee_bps: %w", err) } if n < 0 || n > MaxFeeBPS { return fmt.Errorf("swap_fee_bps must be 0..%d", MaxFeeBPS) } s.SwapFeeBPS = int(n) case "swap_fee_percent": // Accept percent because that is how an operator says it; store basis points because // that is how it is charged. f, err := parseFloat(value) if err != nil { return fmt.Errorf("swap_fee_percent: %w", err) } if f < 0 || f > float64(MaxFeeBPS)/100 { return fmt.Errorf("swap_fee_percent must be 0..%g", float64(MaxFeeBPS)/100) } s.SwapFeeBPS = int(f*100 + 0.5) case "min_fee_sats": n, err := parseInt(value) if err != nil { return fmt.Errorf("min_fee_sats: %w", err) } if n < 0 { return errors.New("min_fee_sats cannot be negative") } s.MinFeeSats = n case "relay_sats_per_day": n, err := parseInt(value) if err != nil { return fmt.Errorf("relay_sats_per_day: %w", err) } if n < 0 { return errors.New("relay_sats_per_day cannot be negative") } s.RelaySatsPerDay = n case "wallet": if value == "" || strings.EqualFold(value, "none") { s.Wallet = "" break } // Validated, then stored exactly as given: the secret is part of the credential and a // redacted copy would be a wallet that can never be used again. if _, err := nwc.ParseURI(value); err != nil { return fmt.Errorf("wallet: %w", err) } s.Wallet = value default: return fmt.Errorf("unknown setting %q: wallet, swap_fee_bps, swap_fee_percent, min_fee_sats, relay_sats_per_day", key) } return s.Validate() } // Touch records who changed the settings and when. func (s *Settings) Touch(by string) { s.UpdatedAt = time.Now().UTC().Format(time.RFC3339) s.UpdatedBy = by } func parseInt(text string) (int64, error) { var n int64 if _, err := fmt.Sscanf(text, "%d", &n); err != nil { return 0, errors.New("not a whole number") } return n, nil } func parseFloat(text string) (float64, error) { var f float64 if _, err := fmt.Sscanf(text, "%f", &f); err != nil { return 0, errors.New("not a number") } return f, nil } func hexKey(key [32]byte) string { const digits = "0123456789abcdef" out := make([]byte, 64) for i, b := range key { out[2*i] = digits[b>>4] out[2*i+1] = digits[b&0xf] } return string(out) }