gate.go raw

   1  // Package listing is the gate between a maker's money and a swap being lodged.
   2  //
   3  // The rule is one sentence: nothing is listed until the invoice for it is paid. That needs a record
   4  // of which invoice belongs to which listing, because the payment arrives as a lightning payment
   5  // with a hash and the listing arrives as an event with an id — the gate is what ties the two
   6  // together, and it is the only place that can answer "was this listing paid for".
   7  package listing
   8  
   9  import (
  10  	"encoding/json"
  11  	"errors"
  12  	"fmt"
  13  	"os"
  14  	"path/filepath"
  15  	"sort"
  16  	"time"
  17  )
  18  
  19  // Quote is one listing that is waiting to be paid for, or that has been.
  20  type Quote struct {
  21  	// ID is the swap being listed. It is the maker's identifier, and the key a listing is
  22  	// published under, so one identity ties the invoice, the payment and the event together.
  23  	ID string `json:"id"`
  24  	// PaymentHash is the reference: a lightning invoice is paid by its hash, so the hash is what
  25  	// the invoice check is asked about.
  26  	PaymentHash string `json:"payment_hash"`
  27  	Invoice     string `json:"invoice"`
  28  	AmountSats  int64  `json:"amount_sats"`
  29  	// FeeBPS is the margin that produced AmountSats, kept so a maker can be shown why a fee is
  30  	// what it is after a price change.
  31  	FeeBPS    int    `json:"fee_bps"`
  32  	CreatedAt string `json:"created_at"`
  33  	PaidAt    string `json:"paid_at,omitempty"`
  34  }
  35  
  36  // Gate is the set of quotes for one gateway, stored beside the rest of its configuration.
  37  type Gate struct {
  38  	Path   string            `json:"-"`
  39  	Quotes map[string]*Quote `json:"quotes"`
  40  }
  41  
  42  // Open reads the gate's file. A missing file is an empty gate.
  43  func Open(path string) (*Gate, error) {
  44  	gate := &Gate{Path: path, Quotes: map[string]*Quote{}}
  45  
  46  	body, err := os.ReadFile(path)
  47  
  48  	if errors.Is(err, os.ErrNotExist) {
  49  		return gate, nil
  50  	}
  51  
  52  	if err != nil {
  53  		return nil, fmt.Errorf("listing: %w", err)
  54  	}
  55  
  56  	if err := json.Unmarshal(body, gate); err != nil {
  57  		return nil, fmt.Errorf("listing: %s: %w", path, err)
  58  	}
  59  
  60  	gate.Path = path
  61  
  62  	if gate.Quotes == nil {
  63  		gate.Quotes = map[string]*Quote{}
  64  	}
  65  
  66  	return gate, nil
  67  }
  68  
  69  // Save writes the gate atomically, so a crash cannot leave a listing paid for and forgotten.
  70  func (g *Gate) Save() error {
  71  	if g.Path == "" {
  72  		return nil
  73  	}
  74  
  75  	body, err := json.MarshalIndent(g, "", "  ")
  76  
  77  	if err != nil {
  78  		return fmt.Errorf("listing: %w", err)
  79  	}
  80  
  81  	if err := os.MkdirAll(filepath.Dir(g.Path), 0o700); err != nil {
  82  		return fmt.Errorf("listing: %w", err)
  83  	}
  84  
  85  	stage, err := os.CreateTemp(filepath.Dir(g.Path), ".listings-*")
  86  
  87  	if err != nil {
  88  		return fmt.Errorf("listing: %w", err)
  89  	}
  90  
  91  	name := stage.Name()
  92  
  93  	if _, err := stage.Write(append(body, '\n')); err != nil {
  94  		stage.Close()
  95  		os.Remove(name)
  96  
  97  		return fmt.Errorf("listing: %w", err)
  98  	}
  99  
 100  	if err := stage.Sync(); err != nil {
 101  		stage.Close()
 102  		os.Remove(name)
 103  
 104  		return fmt.Errorf("listing: %w", err)
 105  	}
 106  
 107  	if err := stage.Close(); err != nil {
 108  		os.Remove(name)
 109  
 110  		return fmt.Errorf("listing: %w", err)
 111  	}
 112  
 113  	if err := os.Chmod(name, 0o600); err != nil {
 114  		os.Remove(name)
 115  
 116  		return fmt.Errorf("listing: %w", err)
 117  	}
 118  
 119  	if err := os.Rename(name, g.Path); err != nil {
 120  		os.Remove(name)
 121  
 122  		return fmt.Errorf("listing: %w", err)
 123  	}
 124  
 125  	return nil
 126  }
 127  
 128  // Record stores a quote, refusing to replace one that has already been paid: a paid listing must not
 129  // be re-quoted into an unpaid state, which would be a way to un-pay it.
 130  func (g *Gate) Record(quote Quote) error {
 131  	if quote.ID == "" {
 132  		return errors.New("listing: a quote needs the swap id it is for")
 133  	}
 134  
 135  	if quote.PaymentHash == "" || quote.Invoice == "" {
 136  		return errors.New("listing: a quote needs an invoice and its payment hash")
 137  	}
 138  
 139  	if quote.AmountSats < 0 {
 140  		return errors.New("listing: a quote cannot have a negative fee")
 141  	}
 142  
 143  	if existing, ok := g.Quotes[quote.ID]; ok && existing.PaidAt != "" {
 144  		return fmt.Errorf("listing: %s is already paid for (%s)", quote.ID, existing.PaidAt)
 145  	}
 146  
 147  	if quote.CreatedAt == "" {
 148  		quote.CreatedAt = time.Now().UTC().Format(time.RFC3339)
 149  	}
 150  
 151  	stored := quote
 152  	g.Quotes[quote.ID] = &stored
 153  
 154  	return g.Save()
 155  }
 156  
 157  // Settle marks a listing paid. It is called only after the wallet says the invoice settled, so it
 158  // records a fact rather than a claim.
 159  func (g *Gate) Settle(id string, at time.Time) error {
 160  	quote, ok := g.Quotes[id]
 161  
 162  	if !ok {
 163  		return fmt.Errorf("listing: no quote for %s", id)
 164  	}
 165  
 166  	if quote.PaidAt != "" {
 167  		return nil
 168  	}
 169  
 170  	quote.PaidAt = at.UTC().Format(time.RFC3339)
 171  
 172  	return g.Save()
 173  }
 174  
 175  // Lodged reports whether a listing may be published: a zero fee is free and needs no quote.
 176  func (g *Gate) Lodged(id string) bool {
 177  	quote, ok := g.Quotes[id]
 178  
 179  	if !ok {
 180  		return false
 181  	}
 182  
 183  	return quote.PaidAt != ""
 184  }
 185  
 186  // Pending lists the unpaid quotes, oldest first, for an operator who wants to see what is waiting.
 187  func (g *Gate) Pending() []Quote {
 188  	var out []Quote
 189  
 190  	for _, quote := range g.Quotes {
 191  		if quote.PaidAt == "" {
 192  			out = append(out, *quote)
 193  		}
 194  	}
 195  
 196  	sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt < out[j].CreatedAt })
 197  
 198  	return out
 199  }
 200