main.go raw

   1  // Command nostrino-relay-billing turns incoming wallet payments into paid gateway time.
   2  //
   3  // It is the piece that closes the loop between a relay's wallet and the ledger the relay reads: it
   4  // asks the wallet for recent incoming payments, credits whichever gateway paid (the keysend
   5  // preimage is that gateway's public key), and writes the ledger file. The relay and this process
   6  // agree by reading one document, so neither has to talk to the other while serving clients.
   7  package main
   8  
   9  import (
  10  	"context"
  11  	"flag"
  12  	"fmt"
  13  	"os"
  14  	"time"
  15  
  16  	"git.smesh.lol/nostrino/pkg/billing"
  17  	"git.smesh.lol/nostrino/pkg/nwc"
  18  	"git.smesh.lol/nostrino/pkg/relay"
  19  )
  20  
  21  func main() {
  22  	var (
  23  		wallet  = flag.String("wallet", "", "NIP-47 connection string for the relay's wallet")
  24  		wallet2 = flag.String("wallet-file", "", "file holding the NIP-47 connection string (preferred: keeps it out of ps)")
  25  		ledger  = flag.String("ledger", "", "ledger file the relay reads (default: <data>/subscriptions.json)")
  26  		rate    = flag.Int64("rate", 0, "sats per day of access; zero keeps the ledger's own rate")
  27  		limit   = flag.Int("limit", 50, "how many recent payments to scan")
  28  		once    = flag.Bool("once", false, "scan once and exit")
  29  		every   = flag.Duration("every", 5*time.Minute, "how often to scan when not -once")
  30  	)
  31  	flag.Parse()
  32  
  33  	if *ledger == "" {
  34  		fmt.Fprintln(os.Stderr, "nostrino-relay-billing: -ledger is required (the relay reads it)")
  35  		os.Exit(2)
  36  	}
  37  
  38  	connection, err := walletString(*wallet, *wallet2)
  39  
  40  	if err != nil {
  41  		fail(err)
  42  	}
  43  
  44  	conn, err := nwc.ParseURI(connection)
  45  
  46  	if err != nil {
  47  		fail(err)
  48  	}
  49  
  50  	for {
  51  		paid, err := scan(conn, *ledger, *rate, *limit)
  52  
  53  		if err != nil {
  54  			fmt.Fprintln(os.Stderr, "nostrino-relay-billing:", err)
  55  		} else {
  56  			fmt.Printf("relay-billing: %d gateway(s) paid up, ledger %s\n", paid, *ledger)
  57  		}
  58  
  59  		if *once {
  60  			if err != nil {
  61  				os.Exit(1)
  62  			}
  63  
  64  			return
  65  		}
  66  
  67  		time.Sleep(*every)
  68  	}
  69  }
  70  
  71  // scan credits one pass over the wallet's incoming payments.
  72  func scan(conn nwc.Connection, ledgerPath string, rate int64, limit int) (int, error) {
  73  	ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
  74  	defer cancel()
  75  
  76  	transport, err := relay.DialTransport(conn.RelayURL)
  77  
  78  	if err != nil {
  79  		return 0, err
  80  	}
  81  
  82  	client, err := nwc.Dial(ctx, conn, transport)
  83  
  84  	if err != nil {
  85  		return 0, err
  86  	}
  87  
  88  	defer client.Close()
  89  
  90  	if _, err := client.GetInfo(ctx); err != nil {
  91  		return 0, fmt.Errorf("wallet is not answering: %w", err)
  92  	}
  93  
  94  	payments, err := client.ListTransactions(ctx, limit)
  95  
  96  	if err != nil {
  97  		return 0, err
  98  	}
  99  
 100  	ledger, err := billing.OpenLedger(ledgerPath, rate)
 101  
 102  	if err != nil {
 103  		return 0, err
 104  	}
 105  
 106  	if err := credit(ledger, payments, time.Now()); err != nil {
 107  		return 0, err
 108  	}
 109  
 110  	if err := ledger.Save(); err != nil {
 111  		return 0, err
 112  	}
 113  
 114  	paid := 0
 115  
 116  	for _, subscription := range ledger.Subscriptions {
 117  		if ledger.Paid(subscription.Gateway, time.Now()) {
 118  			paid++
 119  		}
 120  	}
 121  
 122  	return paid, nil
 123  }
 124  
 125  // credit applies one pass of payments to the ledger. A payment is matched to a gateway by its
 126  // preimage, which the gateway chose to be its own public key.
 127  func credit(ledger *billing.Ledger, payments []nwc.Transaction, now time.Time) error {
 128  	for _, payment := range payments {
 129  		if payment.Type != "" && payment.Type != "incoming" {
 130  			continue
 131  		}
 132  
 133  		if len(payment.Preimage) != 64 {
 134  			// An ordinary invoice payment from a human: not a gateway subscription.
 135  			continue
 136  		}
 137  
 138  		if _, err := ledger.Credit(payment.Preimage, payment.AmountSats, payment.SettledAt, now); err != nil {
 139  			// A payment too small to buy a second, or a rate that is not set: report and keep
 140  			// going, because one odd payment must not stop the rest of the pass.
 141  			fmt.Fprintf(os.Stderr, "nostrino-relay-billing: %v\n", err)
 142  		}
 143  	}
 144  
 145  	return nil
 146  }
 147  
 148  func walletString(inline, path string) (string, error) {
 149  	if path != "" {
 150  		body, err := os.ReadFile(path)
 151  
 152  		if err != nil {
 153  			return "", fmt.Errorf("wallet file: %w", err)
 154  		}
 155  
 156  		return string(body), nil
 157  	}
 158  
 159  	if inline != "" {
 160  		return inline, nil
 161  	}
 162  
 163  	return "", fmt.Errorf("need -wallet or -wallet-file")
 164  }
 165  
 166  func fail(err error) {
 167  	fmt.Fprintln(os.Stderr, "nostrino-relay-billing:", err)
 168  	os.Exit(1)
 169  }
 170