subscription.go raw

   1  package bridge
   2  
   3  import (
   4  	"context"
   5  	"encoding/json"
   6  	"fmt"
   7  	"time"
   8  
   9  	"git.smesh.lol/nostrino/pkg/billing"
  10  	"git.smesh.lol/nostrino/pkg/nostr"
  11  	"git.smesh.lol/nostrino/pkg/relay"
  12  )
  13  
  14  // checkSubscription asks a relay how much paid access this gateway has left.
  15  //
  16  // It is the gateway's side of the keysend subscription: the payment already said who paid, and
  17  // this asks how long it bought. A relay that does not answer, or does not charge, is not a
  18  // failure — it is reported as unknown, and the tunnel keeps working.
  19  func (s *Server) checkSubscription(ctx context.Context, relayURL, relayKeyHex string) (RelayHealth, bool) {
  20  	if relayKeyHex == "" {
  21  		return RelayHealth{}, false
  22  	}
  23  
  24  	var relayKey [32]byte
  25  
  26  	raw, err := hexDecode(relayKeyHex)
  27  
  28  	if err != nil || len(raw) != 32 {
  29  		return RelayHealth{}, false
  30  	}
  31  
  32  	copy(relayKey[:], raw)
  33  
  34  	transport, err := relay.DialTransport(relayURL)
  35  
  36  	if err != nil {
  37  		return RelayHealth{}, false
  38  	}
  39  
  40  	client, err := relay.New(transport, s.cfg.Key, relay.Options{RelayURL: relayURL})
  41  
  42  	if err != nil {
  43  		return RelayHealth{}, false
  44  	}
  45  
  46  	defer client.Close()
  47  
  48  	id := s.listener.PubKey()
  49  	sub, err := client.Subscribe(nostr.Filter{
  50  		Kinds:   []int{billing.KindControl},
  51  		Authors: []string{relayKeyHex},
  52  		Tags:    map[string][]string{"p": {nostr.Hex(id[:])}},
  53  	})
  54  
  55  	if err != nil {
  56  		return RelayHealth{}, false
  57  	}
  58  
  59  	waitCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
  60  	defer cancel()
  61  
  62  	if err := client.WaitEOSE(waitCtx, sub); err != nil {
  63  		return RelayHealth{}, false
  64  	}
  65  
  66  	event := &nostr.Event{
  67  		Kind:      billing.KindControl,
  68  		CreatedAt: time.Now().Unix(),
  69  		Tags:      nostr.Tags{{billing.TagTopic, billing.TopicSubscription}, {"p", relayKeyHex}},
  70  		Content:   "{}",
  71  	}
  72  
  73  	if err := event.Sign(s.cfg.Key); err != nil {
  74  		return RelayHealth{}, false
  75  	}
  76  
  77  	if err := client.Publish(waitCtx, event); err != nil {
  78  		return RelayHealth{}, false
  79  	}
  80  
  81  	want := nostr.Hex(event.ID[:])
  82  
  83  	for {
  84  		select {
  85  		case <-waitCtx.Done():
  86  			return RelayHealth{}, false
  87  		case answer, ok := <-sub.Events:
  88  			if !ok {
  89  				return RelayHealth{}, false
  90  			}
  91  
  92  			health, matched := decodeSubscription(answer, want)
  93  
  94  			if matched {
  95  				return health, true
  96  			}
  97  		}
  98  	}
  99  }
 100  
 101  // decodeSubscription reads one answer to a subscription query.
 102  func decodeSubscription(event *nostr.Event, requestID string) (RelayHealth, bool) {
 103  	matched := false
 104  
 105  	for _, tag := range event.Tags {
 106  		if len(tag) >= 2 && tag[0] == "e" && tag[1] == requestID {
 107  			matched = true
 108  		}
 109  	}
 110  
 111  	if !matched {
 112  		return RelayHealth{}, false
 113  	}
 114  
 115  	var answer struct {
 116  		Paid             bool   `json:"paid"`
 117  		RemainingSeconds int64  `json:"remaining_seconds"`
 118  		PaidUntil        string `json:"paid_until"`
 119  		RateSatsPerDay   int64  `json:"rate_sats_per_day"`
 120  		Blocked          bool   `json:"blocked"`
 121  	}
 122  
 123  	if err := json.Unmarshal([]byte(event.Content), &answer); err != nil {
 124  		return RelayHealth{}, false
 125  	}
 126  
 127  	return RelayHealth{
 128  		Paid:             answer.Paid,
 129  		Blocked:          answer.Blocked,
 130  		RemainingSeconds: answer.RemainingSeconds,
 131  		PaidUntil:        answer.PaidUntil,
 132  		RateSatsPerDay:   answer.RateSatsPerDay,
 133  	}, true
 134  }
 135  
 136  // subscriptionWarning says what a gateway operator needs to see before access lapses: nothing while
 137  // there is time, the countdown when it is short, and a plain reason when it has lapsed.
 138  func subscriptionWarning(health RelayHealth) string {
 139  	switch {
 140  	case health.Blocked:
 141  		return "the relay has blocked this gateway; ask its operator"
 142  	case health.RateSatsPerDay > 0 && !health.Paid:
 143  		return fmt.Sprintf("no paid access at %d sats/day: renew with a keysend whose preimage is this gateway's key",
 144  			health.RateSatsPerDay)
 145  	case health.RateSatsPerDay > 0 && health.RemainingSeconds < int64(24*time.Hour/time.Second):
 146  		return fmt.Sprintf("%.1f hours of paid access left", float64(health.RemainingSeconds)/3600)
 147  	}
 148  
 149  	return ""
 150  }
 151  
 152  func hexDecode(text string) ([]byte, error) {
 153  	if len(text)%2 != 0 {
 154  		return nil, fmt.Errorf("odd number of hex characters")
 155  	}
 156  
 157  	out := make([]byte, len(text)/2)
 158  
 159  	for i := 0; i < len(out); i++ {
 160  		hi, ok := hexDigit(text[2*i])
 161  
 162  		if !ok {
 163  			return nil, fmt.Errorf("not hex")
 164  		}
 165  
 166  		lo, ok := hexDigit(text[2*i+1])
 167  
 168  		if !ok {
 169  			return nil, fmt.Errorf("not hex")
 170  		}
 171  
 172  		out[i] = hi<<4 | lo
 173  	}
 174  
 175  	return out, nil
 176  }
 177  
 178  func hexDigit(c byte) (byte, bool) {
 179  	switch {
 180  	case c >= '0' && c <= '9':
 181  		return c - '0', true
 182  	case c >= 'a' && c <= 'f':
 183  		return c - 'a' + 10, true
 184  	case c >= 'A' && c <= 'F':
 185  		return c - 'A' + 10, true
 186  	}
 187  
 188  	return 0, false
 189  }
 190