rental.go raw

   1  // Package rental implements time-boxed streaming access.
   2  //
   3  // A rental is a payment for a window, not an entitlement. The host opens a
   4  // window keyed by (buyer, asset) when a NUT-24 payment settles, serves inside
   5  // it, and issues a receipt with mode = stream. When the window expires the next
   6  // request is challenged again. Ownership is never modelled here: a fan set or a
   7  // deed is the only durable entitlement.
   8  package rental
   9  
  10  import (
  11  	"context"
  12  	"encoding/json"
  13  	"fmt"
  14  	"strconv"
  15  	"sync"
  16  	"time"
  17  
  18  	"git.smesh.lol/orly/pkg/musiquay/deed"
  19  	"git.smesh.lol/orly/pkg/musiquay/nutreq"
  20  	"git.smesh.lol/orly/pkg/nostr/encoders/hex"
  21  )
  22  
  23  // Store persists rental windows. database.Database satisfies it.
  24  type Store interface {
  25  	GetMarker(key string) ([]byte, error)
  26  	SetMarker(key string, value []byte) error
  27  }
  28  
  29  // Window is one buyer's access to one asset until Expires.
  30  type Window struct {
  31  	Buyer   string `json:"buyer"`
  32  	Asset   string `json:"asset"`
  33  	Expires int64  `json:"expires"`
  34  	Amount  int64  `json:"amount_sats"`
  35  	Token   string `json:"token_hash,omitempty"`
  36  }
  37  
  38  func windowKey(buyerHex, assetID string) string {
  39  	return "musiquay:rental:" + buyerHex + ":" + assetID
  40  }
  41  
  42  // Manager opens and checks rental windows.
  43  type Manager struct {
  44  	store  Store
  45  	bucket time.Duration
  46  	mu     sync.Mutex
  47  	now    func() time.Time
  48  }
  49  
  50  // New creates a manager. bucket is the maximum window length; 600 seconds is
  51  // the suggested host policy.
  52  func New(store Store, bucket time.Duration) *Manager {
  53  	if bucket <= 0 {
  54  		bucket = 10 * time.Minute
  55  	}
  56  	return &Manager{store: store, bucket: bucket, now: time.Now}
  57  }
  58  
  59  // Bucket is the host's window length.
  60  func (m *Manager) Bucket() time.Duration { return m.bucket }
  61  
  62  // Challenge builds the NUT-24 request for one bucket.
  63  func (m *Manager) Challenge(assetID string, priceSats int64, mintURL string) (string, error) {
  64  	if !deed.IsAssetID(assetID) {
  65  		return "", fmt.Errorf("rental: invalid asset id")
  66  	}
  67  	if priceSats <= 0 {
  68  		return "", fmt.Errorf("rental: price must be positive")
  69  	}
  70  	return nutreq.New(uint64(priceSats), mintURL, "musiquay rental").EncodeA()
  71  }
  72  
  73  // Open records a paid window. The expiry is capped at now+bucket so a client
  74  // cannot buy an arbitrarily long rental at one bucket's price.
  75  func (m *Manager) Open(ctx context.Context, buyer []byte, assetID string, requested time.Duration, amountSats int64) (*Window, error) {
  76  	if len(buyer) != 32 {
  77  		return nil, fmt.Errorf("rental: invalid buyer")
  78  	}
  79  	if !deed.IsAssetID(assetID) {
  80  		return nil, fmt.Errorf("rental: invalid asset id")
  81  	}
  82  	if requested <= 0 || requested > m.bucket {
  83  		requested = m.bucket
  84  	}
  85  	w := &Window{
  86  		Buyer:   hex.Enc(buyer),
  87  		Asset:   assetID,
  88  		Expires: m.now().Add(requested).Unix(),
  89  		Amount:  amountSats,
  90  	}
  91  	b, err := json.Marshal(w)
  92  	if err != nil {
  93  		return nil, err
  94  	}
  95  	m.mu.Lock()
  96  	err = m.store.SetMarker(windowKey(w.Buyer, assetID), b)
  97  	m.mu.Unlock()
  98  	if err != nil {
  99  		return nil, err
 100  	}
 101  	return w, nil
 102  }
 103  
 104  // Valid reports whether unexpired access exists.
 105  func (m *Manager) Valid(ctx context.Context, buyer []byte, assetID string) bool {
 106  	w := m.window(buyer, assetID)
 107  	if w == nil {
 108  		return false
 109  	}
 110  	return w.Expires > m.now().Unix()
 111  }
 112  
 113  // Remaining returns the seconds left, or zero.
 114  func (m *Manager) Remaining(ctx context.Context, buyer []byte, assetID string) int64 {
 115  	w := m.window(buyer, assetID)
 116  	if w == nil {
 117  		return 0
 118  	}
 119  	left := w.Expires - m.now().Unix()
 120  	if left < 0 {
 121  		return 0
 122  	}
 123  	return left
 124  }
 125  
 126  func (m *Manager) window(buyer []byte, assetID string) *Window {
 127  	if len(buyer) != 32 {
 128  		return nil
 129  	}
 130  	b, err := m.store.GetMarker(windowKey(hex.Enc(buyer), assetID))
 131  	if err != nil || len(b) == 0 {
 132  		return nil
 133  	}
 134  	var w Window
 135  	if err = json.Unmarshal(b, &w); err != nil {
 136  		return nil
 137  	}
 138  	return &w
 139  }
 140  
 141  // ReceiptAmount returns the settled amount and the window for a stream receipt.
 142  func (m *Manager) ReceiptAmount(buyer []byte, assetID string) (int64, int64) {
 143  	w := m.window(buyer, assetID)
 144  	if w == nil {
 145  		return 0, 0
 146  	}
 147  	return w.Amount, w.Expires
 148  }
 149  
 150  // FormatDuration is a small helper for the challenge description.
 151  func FormatDuration(d time.Duration) string {
 152  	return strconv.FormatInt(int64(d/time.Second), 10) + "s"
 153  }
 154