package deed import ( "encoding/hex" "fmt" "strconv" "time" "git.smesh.lol/orly/pkg/nostr/encoders/event" "git.smesh.lol/orly/pkg/nostr/encoders/kind" "git.smesh.lol/orly/pkg/nostr/encoders/tag" "git.smesh.lol/orly/pkg/nostr/encoders/timestamp" "git.smesh.lol/orly/pkg/nostr/interfaces/signer" ) // Tier is the scope of an entitlement deed. type Tier string const ( // TierFan is direct ownership of one asset. TierFan Tier = "fan" // TierRetail is ownership bought through a retailer, still one asset. TierRetail Tier = "retail" // TierSub is a time-boxed channel subscription covering the channel's // catalog, not one asset. TierSub Tier = "sub" ) // Tag names used by the deed. const ( TagBuyer = "p" TagTier = "tier" TagChannel = "channel" TagOrder = "order" TagPayment = "payment" TagPrice = "price" TagExpires = "expires" TagDeed = "deed" TagServer = "server" TagNonce = "nonce" TagExpiration = "expiration" ) // Deed is a parsed and structurally verified kind 3223 entitlement deed. type Deed struct { Event *event.E // AssetID is present for fan and retail deeds and absent for sub deeds. AssetID string // Channel is present for sub deeds and absent otherwise. Channel string Tier Tier // Buyer is the p tag: the only key that can present the deed. Buyer []byte // Order, Payment, and PriceSats are provenance. Order string Payment string PriceSats int64 // Expires is the unix expiry; zero means no expiry. Expires int64 // Seller is the signing key. Seller []byte } // ParseDeed performs the checks that need no external data: kind, signature, // tier, and tag shape. Scope and signer authorization are checked by Verify. func ParseDeed(ev *event.E) (*Deed, error) { if ev == nil { return nil, fmt.Errorf("deed: nil deed") } if ev.Kind != kind.EntitlementDeed.ToU16() { return nil, fmt.Errorf("deed: kind %d is not an entitlement deed", ev.Kind) } if valid, err := ev.Verify(); err != nil { return nil, fmt.Errorf("deed: verify deed: %w", err) } else if !valid { return nil, fmt.Errorf("deed: deed signature invalid") } tier := Tier(tagValue(ev, TagTier)) switch tier { case TierFan, TierRetail, TierSub: default: return nil, fmt.Errorf("deed: unrecognized tier %q", tier) } buyerHex := tagValueHex(ev, TagBuyer) buyer, err := hex.DecodeString(buyerHex) if err != nil || len(buyer) != 32 { return nil, fmt.Errorf("deed: deed has no valid buyer p tag") } d := &Deed{ Event: ev, AssetID: tagValue(ev, TagAsset), Channel: tagValue(ev, TagChannel), Tier: tier, Buyer: buyer, Order: tagValue(ev, TagOrder), Payment: tagValue(ev, TagPayment), Seller: append([]byte(nil), ev.Pubkey...), } if d.AssetID != "" && !IsAssetID(d.AssetID) { return nil, fmt.Errorf("deed: deed asset id %q is invalid", d.AssetID) } if price := tagValue(ev, TagPrice); price != "" { n, err := strconv.ParseInt(price, 10, 64) if err != nil || n < 0 { return nil, fmt.Errorf("deed: deed price %q is invalid", price) } d.PriceSats = n } if exp := tagValue(ev, TagExpires); exp != "" { n, err := strconv.ParseInt(exp, 10, 64) if err != nil { return nil, fmt.Errorf("deed: deed expiry %q is invalid", exp) } d.Expires = n } return d, nil } // DeedVerifyOptions supplies the data a verifier cannot get from the deed. type DeedVerifyOptions struct { // RequestedAssetID is the asset the gate is being asked to serve. It is // always required: the proof names the requested asset, and the deed scope // is compared to it. RequestedAssetID string // Now overrides the clock; nil means time.Now. Now time.Time // AllowedSigners are the keys that may sign this deed for this asset: the // current owner, the authorized retailers, and any key reachable through a // valid succession chain. When empty, the deed is refused. AllowedSigners [][]byte // CatalogHas reports whether the channel's catalog covers the requested // asset. It is required for a sub deed; a nil value fails closed. CatalogHas func(channel, assetID string) bool // Revoked is a best-effort revocation lookup. A nil value means the feed is // unreachable and the deed is honoured. Revoked func(deedID string) bool } // Verify checks the deed's scope, signer, and expiry for a requested asset. func (d *Deed) Verify(o DeedVerifyOptions) error { now := o.Now if now.IsZero() { now = time.Now() } if !IsAssetID(o.RequestedAssetID) { return fmt.Errorf("deed: requested asset id is invalid") } switch d.Tier { case TierFan, TierRetail: // One asset, named exactly once, and it must be the requested one. if d.AssetID == "" { return fmt.Errorf("deed: %s deed has no asset tag", d.Tier) } if d.Channel != "" { return fmt.Errorf("deed: %s deed must not carry a channel tag", d.Tier) } if d.AssetID != o.RequestedAssetID { return fmt.Errorf("deed: deed covers asset %s, not the requested %s", d.AssetID, o.RequestedAssetID) } case TierSub: // A subscription names a channel and must not claim an asset: the // catalog decides coverage, so an asset tag would be a vacuous pass. if d.AssetID != "" { return fmt.Errorf("deed: sub deed must not carry an asset tag") } if d.Channel == "" { return fmt.Errorf("deed: sub deed has no channel tag") } if o.CatalogHas == nil { return fmt.Errorf("deed: sub deed cannot be verified without a channel catalog") } if !o.CatalogHas(d.Channel, o.RequestedAssetID) { return fmt.Errorf("deed: channel %s does not cover asset %s", d.Channel, o.RequestedAssetID) } default: return fmt.Errorf("deed: unrecognized tier %q", d.Tier) } if len(o.AllowedSigners) == 0 { return fmt.Errorf("deed: no authorized signer is known for this asset") } authorized := false for _, k := range o.AllowedSigners { if equalBytes(k, d.Seller) { authorized = true break } } if !authorized { return fmt.Errorf("deed: signer %x is not authorized for this asset", d.Seller) } if d.Expires != 0 && d.Expires <= now.Unix() { return fmt.Errorf("deed: expired at %d", d.Expires) } if o.Revoked != nil && o.Revoked(hex.EncodeToString(d.Event.ID)) { return fmt.Errorf("deed: revoked") } return nil } // IssueOptions describes a deed the seller is minting. type IssueOptions struct { // AssetID is required for fan and retail deeds. AssetID string // Channel is required for sub deeds. Channel string Tier Tier // Buyer is the recipient pubkey. Buyer []byte // Order is the order event id; Payment is the token hash or invoice id. Order string Payment string // PriceSats is the amount settled. PriceSats int64 // Expires is the unix expiry for a sub deed; zero means no expiry. Expires int64 // Extra tags are appended after the standard tags. Extra []*tag.T } // Issue builds and signs a kind 3223 deed. The returned event is the payload // that goes inside the NIP-59 seal; it is not a rumor. func Issue(sign signer.I, o IssueOptions) (*event.E, error) { if len(o.Buyer) != 32 { return nil, fmt.Errorf("deed: buyer must be a 32-byte pubkey") } switch o.Tier { case TierFan, TierRetail: if !IsAssetID(o.AssetID) { return nil, fmt.Errorf("deed: %s deed requires a valid asset id", o.Tier) } if o.Channel != "" { return nil, fmt.Errorf("deed: %s deed must not carry a channel", o.Tier) } case TierSub: if o.AssetID != "" { return nil, fmt.Errorf("deed: sub deed must not carry an asset id") } if o.Channel == "" { return nil, fmt.Errorf("deed: sub deed requires a channel") } default: return nil, fmt.Errorf("deed: unrecognized tier %q", o.Tier) } ev := event.New() ev.Kind = kind.EntitlementDeed.ToU16() ev.CreatedAt = timestamp.Now().I64() ev.Tags = tag.NewS() if o.AssetID != "" { ev.Tags.Append(newTag(TagAsset, o.AssetID)) } if o.Channel != "" { ev.Tags.Append(newTag(TagChannel, o.Channel)) } ev.Tags.Append(newTag(TagBuyer, hex.EncodeToString(o.Buyer))) ev.Tags.Append(newTag(TagTier, string(o.Tier))) if o.Order != "" { ev.Tags.Append(newTag(TagOrder, o.Order)) } if o.Payment != "" { ev.Tags.Append(newTag(TagPayment, o.Payment)) } ev.Tags.Append(newTag(TagPrice, strconv.FormatInt(o.PriceSats, 10), "sat")) if o.Expires != 0 { ev.Tags.Append(newTag(TagExpires, strconv.FormatInt(o.Expires, 10))) } for _, t := range o.Extra { ev.Tags.Append(t) } if err := ev.Sign(sign); err != nil { return nil, fmt.Errorf("deed: sign: %w", err) } return ev, nil } // ID returns the deed event id as hex. func (d *Deed) ID() string { return hex.EncodeToString(d.Event.ID) } // IsSubscription reports whether the deed is time-boxed. func (d *Deed) IsSubscription() bool { return d.Tier == TierSub } // tagValueHex reads a tag value as hex, converting the binary storage form the // tag encoder uses for e and p tags. func tagValueHex(ev *event.E, name string) string { if ev == nil || ev.Tags == nil { return "" } t := ev.Tags.GetFirst([]byte(name)) if t == nil { return "" } return string(t.ValueHex()) }