deed.go raw

   1  package deed
   2  
   3  import (
   4  	"encoding/hex"
   5  	"fmt"
   6  	"strconv"
   7  	"time"
   8  
   9  	"git.smesh.lol/orly/pkg/nostr/encoders/event"
  10  	"git.smesh.lol/orly/pkg/nostr/encoders/kind"
  11  	"git.smesh.lol/orly/pkg/nostr/encoders/tag"
  12  	"git.smesh.lol/orly/pkg/nostr/encoders/timestamp"
  13  	"git.smesh.lol/orly/pkg/nostr/interfaces/signer"
  14  )
  15  
  16  // Tier is the scope of an entitlement deed.
  17  type Tier string
  18  
  19  const (
  20  	// TierFan is direct ownership of one asset.
  21  	TierFan Tier = "fan"
  22  	// TierRetail is ownership bought through a retailer, still one asset.
  23  	TierRetail Tier = "retail"
  24  	// TierSub is a time-boxed channel subscription covering the channel's
  25  	// catalog, not one asset.
  26  	TierSub Tier = "sub"
  27  )
  28  
  29  // Tag names used by the deed.
  30  const (
  31  	TagBuyer      = "p"
  32  	TagTier       = "tier"
  33  	TagChannel    = "channel"
  34  	TagOrder      = "order"
  35  	TagPayment    = "payment"
  36  	TagPrice      = "price"
  37  	TagExpires    = "expires"
  38  	TagDeed       = "deed"
  39  	TagServer     = "server"
  40  	TagNonce      = "nonce"
  41  	TagExpiration = "expiration"
  42  )
  43  
  44  // Deed is a parsed and structurally verified kind 3223 entitlement deed.
  45  type Deed struct {
  46  	Event *event.E
  47  	// AssetID is present for fan and retail deeds and absent for sub deeds.
  48  	AssetID string
  49  	// Channel is present for sub deeds and absent otherwise.
  50  	Channel string
  51  	Tier    Tier
  52  	// Buyer is the p tag: the only key that can present the deed.
  53  	Buyer []byte
  54  	// Order, Payment, and PriceSats are provenance.
  55  	Order     string
  56  	Payment   string
  57  	PriceSats int64
  58  	// Expires is the unix expiry; zero means no expiry.
  59  	Expires int64
  60  	// Seller is the signing key.
  61  	Seller []byte
  62  }
  63  
  64  // ParseDeed performs the checks that need no external data: kind, signature,
  65  // tier, and tag shape. Scope and signer authorization are checked by Verify.
  66  func ParseDeed(ev *event.E) (*Deed, error) {
  67  	if ev == nil {
  68  		return nil, fmt.Errorf("deed: nil deed")
  69  	}
  70  	if ev.Kind != kind.EntitlementDeed.ToU16() {
  71  		return nil, fmt.Errorf("deed: kind %d is not an entitlement deed", ev.Kind)
  72  	}
  73  	if valid, err := ev.Verify(); err != nil {
  74  		return nil, fmt.Errorf("deed: verify deed: %w", err)
  75  	} else if !valid {
  76  		return nil, fmt.Errorf("deed: deed signature invalid")
  77  	}
  78  
  79  	tier := Tier(tagValue(ev, TagTier))
  80  	switch tier {
  81  	case TierFan, TierRetail, TierSub:
  82  	default:
  83  		return nil, fmt.Errorf("deed: unrecognized tier %q", tier)
  84  	}
  85  
  86  	buyerHex := tagValueHex(ev, TagBuyer)
  87  	buyer, err := hex.DecodeString(buyerHex)
  88  	if err != nil || len(buyer) != 32 {
  89  		return nil, fmt.Errorf("deed: deed has no valid buyer p tag")
  90  	}
  91  
  92  	d := &Deed{
  93  		Event:   ev,
  94  		AssetID: tagValue(ev, TagAsset),
  95  		Channel: tagValue(ev, TagChannel),
  96  		Tier:    tier,
  97  		Buyer:   buyer,
  98  		Order:   tagValue(ev, TagOrder),
  99  		Payment: tagValue(ev, TagPayment),
 100  		Seller:  append([]byte(nil), ev.Pubkey...),
 101  	}
 102  	if d.AssetID != "" && !IsAssetID(d.AssetID) {
 103  		return nil, fmt.Errorf("deed: deed asset id %q is invalid", d.AssetID)
 104  	}
 105  	if price := tagValue(ev, TagPrice); price != "" {
 106  		n, err := strconv.ParseInt(price, 10, 64)
 107  		if err != nil || n < 0 {
 108  			return nil, fmt.Errorf("deed: deed price %q is invalid", price)
 109  		}
 110  		d.PriceSats = n
 111  	}
 112  	if exp := tagValue(ev, TagExpires); exp != "" {
 113  		n, err := strconv.ParseInt(exp, 10, 64)
 114  		if err != nil {
 115  			return nil, fmt.Errorf("deed: deed expiry %q is invalid", exp)
 116  		}
 117  		d.Expires = n
 118  	}
 119  	return d, nil
 120  }
 121  
 122  // DeedVerifyOptions supplies the data a verifier cannot get from the deed.
 123  type DeedVerifyOptions struct {
 124  	// RequestedAssetID is the asset the gate is being asked to serve. It is
 125  	// always required: the proof names the requested asset, and the deed scope
 126  	// is compared to it.
 127  	RequestedAssetID string
 128  	// Now overrides the clock; nil means time.Now.
 129  	Now time.Time
 130  	// AllowedSigners are the keys that may sign this deed for this asset: the
 131  	// current owner, the authorized retailers, and any key reachable through a
 132  	// valid succession chain. When empty, the deed is refused.
 133  	AllowedSigners [][]byte
 134  	// CatalogHas reports whether the channel's catalog covers the requested
 135  	// asset. It is required for a sub deed; a nil value fails closed.
 136  	CatalogHas func(channel, assetID string) bool
 137  	// Revoked is a best-effort revocation lookup. A nil value means the feed is
 138  	// unreachable and the deed is honoured.
 139  	Revoked func(deedID string) bool
 140  }
 141  
 142  // Verify checks the deed's scope, signer, and expiry for a requested asset.
 143  func (d *Deed) Verify(o DeedVerifyOptions) error {
 144  	now := o.Now
 145  	if now.IsZero() {
 146  		now = time.Now()
 147  	}
 148  	if !IsAssetID(o.RequestedAssetID) {
 149  		return fmt.Errorf("deed: requested asset id is invalid")
 150  	}
 151  
 152  	switch d.Tier {
 153  	case TierFan, TierRetail:
 154  		// One asset, named exactly once, and it must be the requested one.
 155  		if d.AssetID == "" {
 156  			return fmt.Errorf("deed: %s deed has no asset tag", d.Tier)
 157  		}
 158  		if d.Channel != "" {
 159  			return fmt.Errorf("deed: %s deed must not carry a channel tag", d.Tier)
 160  		}
 161  		if d.AssetID != o.RequestedAssetID {
 162  			return fmt.Errorf("deed: deed covers asset %s, not the requested %s", d.AssetID, o.RequestedAssetID)
 163  		}
 164  	case TierSub:
 165  		// A subscription names a channel and must not claim an asset: the
 166  		// catalog decides coverage, so an asset tag would be a vacuous pass.
 167  		if d.AssetID != "" {
 168  			return fmt.Errorf("deed: sub deed must not carry an asset tag")
 169  		}
 170  		if d.Channel == "" {
 171  			return fmt.Errorf("deed: sub deed has no channel tag")
 172  		}
 173  		if o.CatalogHas == nil {
 174  			return fmt.Errorf("deed: sub deed cannot be verified without a channel catalog")
 175  		}
 176  		if !o.CatalogHas(d.Channel, o.RequestedAssetID) {
 177  			return fmt.Errorf("deed: channel %s does not cover asset %s", d.Channel, o.RequestedAssetID)
 178  		}
 179  	default:
 180  		return fmt.Errorf("deed: unrecognized tier %q", d.Tier)
 181  	}
 182  
 183  	if len(o.AllowedSigners) == 0 {
 184  		return fmt.Errorf("deed: no authorized signer is known for this asset")
 185  	}
 186  	authorized := false
 187  	for _, k := range o.AllowedSigners {
 188  		if equalBytes(k, d.Seller) {
 189  			authorized = true
 190  			break
 191  		}
 192  	}
 193  	if !authorized {
 194  		return fmt.Errorf("deed: signer %x is not authorized for this asset", d.Seller)
 195  	}
 196  
 197  	if d.Expires != 0 && d.Expires <= now.Unix() {
 198  		return fmt.Errorf("deed: expired at %d", d.Expires)
 199  	}
 200  	if o.Revoked != nil && o.Revoked(hex.EncodeToString(d.Event.ID)) {
 201  		return fmt.Errorf("deed: revoked")
 202  	}
 203  	return nil
 204  }
 205  
 206  // IssueOptions describes a deed the seller is minting.
 207  type IssueOptions struct {
 208  	// AssetID is required for fan and retail deeds.
 209  	AssetID string
 210  	// Channel is required for sub deeds.
 211  	Channel string
 212  	Tier    Tier
 213  	// Buyer is the recipient pubkey.
 214  	Buyer []byte
 215  	// Order is the order event id; Payment is the token hash or invoice id.
 216  	Order   string
 217  	Payment string
 218  	// PriceSats is the amount settled.
 219  	PriceSats int64
 220  	// Expires is the unix expiry for a sub deed; zero means no expiry.
 221  	Expires int64
 222  	// Extra tags are appended after the standard tags.
 223  	Extra []*tag.T
 224  }
 225  
 226  // Issue builds and signs a kind 3223 deed. The returned event is the payload
 227  // that goes inside the NIP-59 seal; it is not a rumor.
 228  func Issue(sign signer.I, o IssueOptions) (*event.E, error) {
 229  	if len(o.Buyer) != 32 {
 230  		return nil, fmt.Errorf("deed: buyer must be a 32-byte pubkey")
 231  	}
 232  	switch o.Tier {
 233  	case TierFan, TierRetail:
 234  		if !IsAssetID(o.AssetID) {
 235  			return nil, fmt.Errorf("deed: %s deed requires a valid asset id", o.Tier)
 236  		}
 237  		if o.Channel != "" {
 238  			return nil, fmt.Errorf("deed: %s deed must not carry a channel", o.Tier)
 239  		}
 240  	case TierSub:
 241  		if o.AssetID != "" {
 242  			return nil, fmt.Errorf("deed: sub deed must not carry an asset id")
 243  		}
 244  		if o.Channel == "" {
 245  			return nil, fmt.Errorf("deed: sub deed requires a channel")
 246  		}
 247  	default:
 248  		return nil, fmt.Errorf("deed: unrecognized tier %q", o.Tier)
 249  	}
 250  
 251  	ev := event.New()
 252  	ev.Kind = kind.EntitlementDeed.ToU16()
 253  	ev.CreatedAt = timestamp.Now().I64()
 254  	ev.Tags = tag.NewS()
 255  	if o.AssetID != "" {
 256  		ev.Tags.Append(newTag(TagAsset, o.AssetID))
 257  	}
 258  	if o.Channel != "" {
 259  		ev.Tags.Append(newTag(TagChannel, o.Channel))
 260  	}
 261  	ev.Tags.Append(newTag(TagBuyer, hex.EncodeToString(o.Buyer)))
 262  	ev.Tags.Append(newTag(TagTier, string(o.Tier)))
 263  	if o.Order != "" {
 264  		ev.Tags.Append(newTag(TagOrder, o.Order))
 265  	}
 266  	if o.Payment != "" {
 267  		ev.Tags.Append(newTag(TagPayment, o.Payment))
 268  	}
 269  	ev.Tags.Append(newTag(TagPrice, strconv.FormatInt(o.PriceSats, 10), "sat"))
 270  	if o.Expires != 0 {
 271  		ev.Tags.Append(newTag(TagExpires, strconv.FormatInt(o.Expires, 10)))
 272  	}
 273  	for _, t := range o.Extra {
 274  		ev.Tags.Append(t)
 275  	}
 276  	if err := ev.Sign(sign); err != nil {
 277  		return nil, fmt.Errorf("deed: sign: %w", err)
 278  	}
 279  	return ev, nil
 280  }
 281  
 282  // ID returns the deed event id as hex.
 283  func (d *Deed) ID() string { return hex.EncodeToString(d.Event.ID) }
 284  
 285  // IsSubscription reports whether the deed is time-boxed.
 286  func (d *Deed) IsSubscription() bool { return d.Tier == TierSub }
 287  
 288  // tagValueHex reads a tag value as hex, converting the binary storage form the
 289  // tag encoder uses for e and p tags.
 290  func tagValueHex(ev *event.E, name string) string {
 291  	if ev == nil || ev.Tags == nil {
 292  		return ""
 293  	}
 294  	t := ev.Tags.GetFirst([]byte(name))
 295  	if t == nil {
 296  		return ""
 297  	}
 298  	return string(t.ValueHex())
 299  }
 300