config.go raw

   1  // Package billing holds what an operator charges and what they pay: the margin on a swap listing,
   2  // the rate for tunnel access, and the wallet that moves the sats.
   3  //
   4  // It is a file because it must be edited by an operator who is not at the machine — the gateway's
   5  // control channel writes it — and because a price that lives only in memory is a price that resets
   6  // on the next restart. The wallet connection string is a credential: the file is written 0600 and
   7  // every read of it redacts the secret.
   8  package billing
   9  
  10  import (
  11  	"encoding/json"
  12  	"errors"
  13  	"fmt"
  14  	"os"
  15  	"path/filepath"
  16  	"strings"
  17  	"time"
  18  
  19  	"git.smesh.lol/nostrino/pkg/nwc"
  20  )
  21  
  22  // Settings is one gateway's or relay's money configuration.
  23  type Settings struct {
  24  	// Wallet is the NIP-47 connection string. Empty means no wallet is connected, in which case
  25  	// nothing is charged: a gateway that cannot take payment must not pretend to.
  26  	Wallet string `json:"wallet,omitempty"`
  27  	// SwapFeeBPS is the operator's margin on a swap listing, in basis points of the BTC leg:
  28  	// 50 is 0.5%, 100 is 1%.
  29  	SwapFeeBPS int `json:"swap_fee_bps"`
  30  	// MinFeeSats is the floor, so a tiny swap still costs something to register.
  31  	MinFeeSats int64 `json:"min_fee_sats"`
  32  	// RelaySatsPerDay is what tunnel access costs, per day, in sats. On a gateway it is the price
  33  	// it pays its relay; a relay publishes it as what it charges.
  34  	RelaySatsPerDay int64 `json:"relay_sats_per_day"`
  35  	// UpdatedAt and UpdatedBy record who changed the price and when, because a price is the kind
  36  	// of thing that needs explaining later.
  37  	UpdatedAt string `json:"updated_at,omitempty"`
  38  	UpdatedBy string `json:"updated_by,omitempty"`
  39  }
  40  
  41  // MaxFeeBPS is the highest margin this software will accept. A typo that turns 0.5% into 50%
  42  // would be a fee nobody agreed to, so the bound is enforced rather than documented.
  43  const MaxFeeBPS = 2000
  44  
  45  // Load reads the settings file. A missing file is an empty configuration, not an error: a new
  46  // gateway starts with no prices and no wallet.
  47  func Load(path string) (Settings, error) {
  48  	body, err := os.ReadFile(path)
  49  
  50  	if errors.Is(err, os.ErrNotExist) {
  51  		return Settings{}, nil
  52  	}
  53  
  54  	if err != nil {
  55  		return Settings{}, fmt.Errorf("billing: %w", err)
  56  	}
  57  
  58  	var settings Settings
  59  
  60  	if err := json.Unmarshal(body, &settings); err != nil {
  61  		return Settings{}, fmt.Errorf("billing: %s: %w", path, err)
  62  	}
  63  
  64  	if err := settings.Validate(); err != nil {
  65  		return Settings{}, fmt.Errorf("billing: %s: %w", path, err)
  66  	}
  67  
  68  	return settings, nil
  69  }
  70  
  71  // Save writes the settings atomically: a crash in the middle of a price change must leave either
  72  // the old price or the new one, never a half-written file.
  73  func (s Settings) Save(path string) error {
  74  	if err := s.Validate(); err != nil {
  75  		return err
  76  	}
  77  
  78  	body, err := json.MarshalIndent(s, "", "  ")
  79  
  80  	if err != nil {
  81  		return fmt.Errorf("billing: %w", err)
  82  	}
  83  
  84  	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
  85  		return fmt.Errorf("billing: %w", err)
  86  	}
  87  
  88  	stage, err := os.CreateTemp(filepath.Dir(path), ".billing-*")
  89  
  90  	if err != nil {
  91  		return fmt.Errorf("billing: %w", err)
  92  	}
  93  
  94  	name := stage.Name()
  95  
  96  	if err := os.Chmod(name, 0o600); err != nil {
  97  		stage.Close()
  98  		os.Remove(name)
  99  
 100  		return fmt.Errorf("billing: %w", err)
 101  	}
 102  
 103  	if _, err := stage.Write(append(body, '\n')); err != nil {
 104  		stage.Close()
 105  		os.Remove(name)
 106  
 107  		return fmt.Errorf("billing: %w", err)
 108  	}
 109  
 110  	if err := stage.Sync(); err != nil {
 111  		stage.Close()
 112  		os.Remove(name)
 113  
 114  		return fmt.Errorf("billing: %w", err)
 115  	}
 116  
 117  	if err := stage.Close(); err != nil {
 118  		os.Remove(name)
 119  
 120  		return fmt.Errorf("billing: %w", err)
 121  	}
 122  
 123  	if err := os.Rename(name, path); err != nil {
 124  		os.Remove(name)
 125  
 126  		return fmt.Errorf("billing: %w", err)
 127  	}
 128  
 129  	return nil
 130  }
 131  
 132  // Validate refuses a configuration that would charge something the operator did not mean.
 133  func (s *Settings) Validate() error {
 134  	if s.SwapFeeBPS < 0 || s.SwapFeeBPS > MaxFeeBPS {
 135  		return fmt.Errorf("swap fee is %d basis points, outside 0..%d", s.SwapFeeBPS, MaxFeeBPS)
 136  	}
 137  
 138  	if s.MinFeeSats < 0 {
 139  		return fmt.Errorf("minimum fee is %d sats", s.MinFeeSats)
 140  	}
 141  
 142  	if s.RelaySatsPerDay < 0 {
 143  		return fmt.Errorf("relay rate is %d sats per day", s.RelaySatsPerDay)
 144  	}
 145  
 146  	if s.Wallet != "" {
 147  		if _, err := nwc.ParseURI(s.Wallet); err != nil {
 148  			return err
 149  		}
 150  	}
 151  
 152  	return nil
 153  }
 154  
 155  // ListingFee is what this gateway charges to register a swap of the given BTC size: the operator's
 156  // margin, with a floor.
 157  func (s Settings) ListingFee(btcSats int64) int64 {
 158  	if btcSats <= 0 || s.SwapFeeBPS <= 0 {
 159  		return 0
 160  	}
 161  
 162  	// Round up: a fee that rounds to zero is a fee that is not charged.
 163  	fee := (btcSats*int64(s.SwapFeeBPS) + 9999) / 10000
 164  
 165  	if fee < s.MinFeeSats {
 166  		fee = s.MinFeeSats
 167  	}
 168  
 169  	return fee
 170  }
 171  
 172  // AccessFee prices a period of tunnel access at the daily rate, rounding part days up.
 173  func (s Settings) AccessFee(period time.Duration) int64 {
 174  	if s.RelaySatsPerDay <= 0 || period <= 0 {
 175  		return 0
 176  	}
 177  
 178  	day := 24 * time.Hour
 179  	days := int64((period + day - 1) / day)
 180  
 181  	return s.RelaySatsPerDay * days
 182  }
 183  
 184  // Redacted is the settings as they may be shown or logged: the wallet is identified by its public
 185  // key and relay, never by the secret that is half of the connection string.
 186  func (s Settings) Redacted() map[string]any {
 187  	out := map[string]any{
 188  		"swap_fee_bps":       s.SwapFeeBPS,
 189  		"swap_fee_percent":   float64(s.SwapFeeBPS) / 100,
 190  		"min_fee_sats":       s.MinFeeSats,
 191  		"relay_sats_per_day": s.RelaySatsPerDay,
 192  		"wallet_configured":  s.Wallet != "",
 193  	}
 194  
 195  	if s.UpdatedAt != "" {
 196  		out["updated_at"] = s.UpdatedAt
 197  	}
 198  
 199  	if s.UpdatedBy != "" {
 200  		out["updated_by"] = s.UpdatedBy
 201  	}
 202  
 203  	if s.Wallet != "" {
 204  		if conn, err := nwc.ParseURI(s.Wallet); err == nil {
 205  			out["wallet_pubkey"] = hexKey(conn.Wallet)
 206  			out["wallet_relay"] = conn.RelayURL
 207  		}
 208  	}
 209  
 210  	return out
 211  }
 212  
 213  // Set applies one key=value change. Unknown keys are refused rather than ignored: an operator who
 214  // mistypes a setting must be told, not silently charged the old price.
 215  func (s *Settings) Set(key, value string) error {
 216  	value = strings.TrimSpace(value)
 217  
 218  	switch strings.ToLower(strings.TrimSpace(key)) {
 219  	case "swap_fee_bps":
 220  		n, err := parseInt(value)
 221  
 222  		if err != nil {
 223  			return fmt.Errorf("swap_fee_bps: %w", err)
 224  		}
 225  
 226  		if n < 0 || n > MaxFeeBPS {
 227  			return fmt.Errorf("swap_fee_bps must be 0..%d", MaxFeeBPS)
 228  		}
 229  
 230  		s.SwapFeeBPS = int(n)
 231  	case "swap_fee_percent":
 232  		// Accept percent because that is how an operator says it; store basis points because
 233  		// that is how it is charged.
 234  		f, err := parseFloat(value)
 235  
 236  		if err != nil {
 237  			return fmt.Errorf("swap_fee_percent: %w", err)
 238  		}
 239  
 240  		if f < 0 || f > float64(MaxFeeBPS)/100 {
 241  			return fmt.Errorf("swap_fee_percent must be 0..%g", float64(MaxFeeBPS)/100)
 242  		}
 243  
 244  		s.SwapFeeBPS = int(f*100 + 0.5)
 245  	case "min_fee_sats":
 246  		n, err := parseInt(value)
 247  
 248  		if err != nil {
 249  			return fmt.Errorf("min_fee_sats: %w", err)
 250  		}
 251  
 252  		if n < 0 {
 253  			return errors.New("min_fee_sats cannot be negative")
 254  		}
 255  
 256  		s.MinFeeSats = n
 257  	case "relay_sats_per_day":
 258  		n, err := parseInt(value)
 259  
 260  		if err != nil {
 261  			return fmt.Errorf("relay_sats_per_day: %w", err)
 262  		}
 263  
 264  		if n < 0 {
 265  			return errors.New("relay_sats_per_day cannot be negative")
 266  		}
 267  
 268  		s.RelaySatsPerDay = n
 269  	case "wallet":
 270  		if value == "" || strings.EqualFold(value, "none") {
 271  			s.Wallet = ""
 272  			break
 273  		}
 274  
 275  		// Validated, then stored exactly as given: the secret is part of the credential and a
 276  		// redacted copy would be a wallet that can never be used again.
 277  		if _, err := nwc.ParseURI(value); err != nil {
 278  			return fmt.Errorf("wallet: %w", err)
 279  		}
 280  
 281  		s.Wallet = value
 282  	default:
 283  		return fmt.Errorf("unknown setting %q: wallet, swap_fee_bps, swap_fee_percent, min_fee_sats, relay_sats_per_day", key)
 284  	}
 285  
 286  	return s.Validate()
 287  }
 288  
 289  // Touch records who changed the settings and when.
 290  func (s *Settings) Touch(by string) {
 291  	s.UpdatedAt = time.Now().UTC().Format(time.RFC3339)
 292  	s.UpdatedBy = by
 293  }
 294  
 295  func parseInt(text string) (int64, error) {
 296  	var n int64
 297  
 298  	if _, err := fmt.Sscanf(text, "%d", &n); err != nil {
 299  		return 0, errors.New("not a whole number")
 300  	}
 301  
 302  	return n, nil
 303  }
 304  
 305  func parseFloat(text string) (float64, error) {
 306  	var f float64
 307  
 308  	if _, err := fmt.Sscanf(text, "%f", &f); err != nil {
 309  		return 0, errors.New("not a number")
 310  	}
 311  
 312  	return f, nil
 313  }
 314  
 315  func hexKey(key [32]byte) string {
 316  	const digits = "0123456789abcdef"
 317  
 318  	out := make([]byte, 64)
 319  
 320  	for i, b := range key {
 321  		out[2*i] = digits[b>>4]
 322  		out[2*i+1] = digits[b&0xf]
 323  	}
 324  
 325  	return string(out)
 326  }
 327