asset.go raw

   1  // Package deed implements musiquay asset identity, entitlement deeds, deed
   2  // presentation proofs, and owner key succession.
   3  //
   4  // The package is deliberately usable without a relay: a host that has onboarded
   5  // a catalogue and pinned the author keys can verify a deed offline. Anything it
   6  // cannot check locally is expressed as a function field, so a cold host can
   7  // supply a network-backed lookup and fail closed when the lookup fails.
   8  package deed
   9  
  10  import (
  11  	"crypto/sha256"
  12  	"encoding/hex"
  13  	"fmt"
  14  	"sort"
  15  	"strings"
  16  
  17  	"git.smesh.lol/orly/pkg/nostr/encoders/event"
  18  	"git.smesh.lol/orly/pkg/nostr/encoders/kind"
  19  	"git.smesh.lol/orly/pkg/nostr/encoders/tag"
  20  )
  21  
  22  const (
  23  	// AssetIDDomain is the domain separator for the asset id derivation.
  24  	AssetIDDomain = "musiquay.asset.v1"
  25  
  26  	// TagAsset is the tag naming an asset id on track, album, edition, deed,
  27  	// receipt, and aggregate events.
  28  	TagAsset = "asset"
  29  	// TagSource is the 3224 tag naming the first asset event id.
  30  	TagSource = "source"
  31  	// TagOwner is the 3224 tag naming the current owner.
  32  	TagOwner = "owner"
  33  	// TagPrev is the 3224 tag naming the previous record id.
  34  	TagPrev = "prev"
  35  	// TagSuccession is the 3224 tag naming the succession delegation id.
  36  	TagSuccession = "succession"
  37  	// TagCoordinate is the addressable coordinate tag ("a").
  38  	TagCoordinate = "a"
  39  	// TagD is the addressable d tag, reused by 3224 as the asset id.
  40  	TagD = "d"
  41  	// TagRetailer names a retailer authorized to sell an asset, on a 3224
  42  	// record or on the asset event itself.
  43  	TagRetailer = "retailer"
  44  	// TagStandalone marks an edition that is sold independently and therefore
  45  	// owns its own asset id.
  46  	TagStandalone = "standalone"
  47  )
  48  
  49  // Asset kinds that can own an asset id.
  50  var assetKinds = map[uint16]bool{
  51  	kind.Track.ToU16():   true,
  52  	kind.Album.ToU16():   true,
  53  	kind.Edition.ToU16(): true,
  54  }
  55  
  56  // DeriveAssetID returns the stable asset id for the event that first published
  57  // an asset: hex(SHA-256("musiquay.asset.v1|" || <event id>)).
  58  //
  59  // firstEventID may be a raw 32-byte id or its 64-character hex form.
  60  func DeriveAssetID(firstEventID []byte) (string, error) {
  61  	var raw []byte
  62  	switch len(firstEventID) {
  63  	case 32:
  64  		raw = firstEventID
  65  	case 64:
  66  		var err error
  67  		if raw, err = hex.DecodeString(string(firstEventID)); err != nil {
  68  			return "", fmt.Errorf("deed: asset source id: %w", err)
  69  		}
  70  	default:
  71  		return "", fmt.Errorf("deed: asset source id must be 32 bytes or 64 hex characters, got %d", len(firstEventID))
  72  	}
  73  	h := sha256.New()
  74  	h.Write([]byte(AssetIDDomain))
  75  	h.Write([]byte("|"))
  76  	h.Write(raw)
  77  	return hex.EncodeToString(h.Sum(nil)), nil
  78  }
  79  
  80  // IsAssetID reports whether s is a 64-character lower-case hex asset id.
  81  func IsAssetID(s string) bool {
  82  	if len(s) != 64 {
  83  		return false
  84  	}
  85  	_, err := hex.DecodeString(s)
  86  	return err == nil && strings.ToLower(s) == s
  87  }
  88  
  89  // AssetRecord is a parsed and structurally verified kind 3224 event.
  90  type AssetRecord struct {
  91  	Event *event.E
  92  	// AssetID is the d tag.
  93  	AssetID string
  94  	// Source is the hex id of the first asset event.
  95  	Source string
  96  	// Owner is the key named by the owner tag, or the record signer when absent.
  97  	Owner []byte
  98  	// Coordinate is the current addressable coordinate, "kind:pubkey:d".
  99  	Coordinate string
 100  	// Prev is the previous record id, empty for the root.
 101  	Prev string
 102  	// Succession is the succession delegation id, empty for the root.
 103  	Succession string
 104  	// Retailers are keys authorized to sell the asset.
 105  	Retailers [][]byte
 106  }
 107  
 108  // ParseAssetRecord performs the checks that need no external data: kind,
 109  // signature, asset id derivation, and tag shape. Chain anchoring is done by
 110  // Chain.Resolve.
 111  func ParseAssetRecord(ev *event.E) (*AssetRecord, error) {
 112  	if ev == nil {
 113  		return nil, fmt.Errorf("deed: nil asset record")
 114  	}
 115  	if ev.Kind != kind.AssetIdentity.ToU16() {
 116  		return nil, fmt.Errorf("deed: kind %d is not an asset identity record", ev.Kind)
 117  	}
 118  	if valid, err := ev.Verify(); err != nil {
 119  		return nil, fmt.Errorf("deed: verify asset record: %w", err)
 120  	} else if !valid {
 121  		return nil, fmt.Errorf("deed: asset record signature invalid")
 122  	}
 123  	assetID := tagValue(ev, TagD)
 124  	if !IsAssetID(assetID) {
 125  		return nil, fmt.Errorf("deed: asset record has an invalid d tag %q", assetID)
 126  	}
 127  	source := tagValue(ev, TagSource)
 128  	if len(source) != 64 {
 129  		return nil, fmt.Errorf("deed: asset record has no valid source tag")
 130  	}
 131  	derived, err := DeriveAssetID([]byte(source))
 132  	if err != nil {
 133  		return nil, err
 134  	}
 135  	if derived != assetID {
 136  		return nil, fmt.Errorf("deed: asset id %s does not derive from source %s", assetID, source)
 137  	}
 138  	r := &AssetRecord{
 139  		Event:      ev,
 140  		AssetID:    assetID,
 141  		Source:     source,
 142  		Coordinate: tagValue(ev, TagCoordinate),
 143  		Prev:       tagValue(ev, TagPrev),
 144  		Succession: tagValue(ev, TagSuccession),
 145  	}
 146  	if owner := tagValue(ev, TagOwner); owner != "" {
 147  		raw, err := hex.DecodeString(owner)
 148  		if err != nil || len(raw) != 32 {
 149  			return nil, fmt.Errorf("deed: asset record has an invalid owner tag")
 150  		}
 151  		r.Owner = raw
 152  	} else {
 153  		r.Owner = append([]byte(nil), ev.Pubkey...)
 154  	}
 155  	if r.Coordinate != "" {
 156  		k, pub, d, err := splitCoordinate(r.Coordinate)
 157  		if err != nil {
 158  			return nil, err
 159  		}
 160  		if !assetKinds[k] {
 161  			return nil, fmt.Errorf("deed: asset record coordinate kind %d is not an asset kind", k)
 162  		}
 163  		if d == "" || pub == "" {
 164  			return nil, fmt.Errorf("deed: asset record coordinate %q is incomplete", r.Coordinate)
 165  		}
 166  	}
 167  	for _, t := range ev.Tags.GetAll([]byte(TagRetailer)) {
 168  		raw, err := hex.DecodeString(string(t.Value()))
 169  		if err != nil || len(raw) != 32 {
 170  			return nil, fmt.Errorf("deed: asset record has an invalid retailer tag")
 171  		}
 172  		r.Retailers = append(r.Retailers, raw)
 173  	}
 174  	return r, nil
 175  }
 176  
 177  // splitCoordinate parses "kind:pubkey:d".
 178  func splitCoordinate(a string) (k uint16, pub, d string, err error) {
 179  	parts := strings.SplitN(a, ":", 3)
 180  	if len(parts) != 3 {
 181  		return 0, "", "", fmt.Errorf("deed: coordinate %q must be kind:pubkey:d", a)
 182  	}
 183  	var kk uint32
 184  	if _, err = fmt.Sscanf(parts[0], "%d", &kk); err != nil || kk > 65535 {
 185  		return 0, "", "", fmt.Errorf("deed: coordinate %q has an invalid kind", a)
 186  	}
 187  	if len(parts[1]) != 64 {
 188  		return 0, "", "", fmt.Errorf("deed: coordinate %q has an invalid pubkey", a)
 189  	}
 190  	if _, err = hex.DecodeString(parts[1]); err != nil {
 191  		return 0, "", "", fmt.Errorf("deed: coordinate %q has an invalid pubkey", a)
 192  	}
 193  	if parts[2] == "" {
 194  		return 0, "", "", fmt.Errorf("deed: coordinate %q has an empty d tag", a)
 195  	}
 196  	return uint16(kk), parts[1], parts[2], nil
 197  }
 198  
 199  // Chain accumulates asset records and succession delegations so a host can
 200  // resolve an asset id to the latest valid record.
 201  type Chain struct {
 202  	records     []*AssetRecord
 203  	byID        map[string]*AssetRecord
 204  	delegations map[string]*event.E
 205  }
 206  
 207  // NewChain returns an empty chain.
 208  func NewChain() *Chain {
 209  	return &Chain{
 210  		byID:        make(map[string]*AssetRecord),
 211  		delegations: make(map[string]*event.E),
 212  	}
 213  }
 214  
 215  // AddRecord parses and adds a 3224 event. A record that fails the structural
 216  // checks is returned as an error and not added.
 217  func (c *Chain) AddRecord(ev *event.E) (*AssetRecord, error) {
 218  	r, err := ParseAssetRecord(ev)
 219  	if err != nil {
 220  		return nil, err
 221  	}
 222  	id := hex.EncodeToString(r.Event.ID)
 223  	if prev, ok := c.byID[id]; ok {
 224  		return prev, nil
 225  	}
 226  	c.byID[id] = r
 227  	c.records = append(c.records, r)
 228  	return r, nil
 229  }
 230  
 231  // AddDelegation adds a succession delegation. Invalid delegations are ignored,
 232  // because a rogue key may publish one and it must not poison a valid chain.
 233  func (c *Chain) AddDelegation(ev *event.E) error {
 234  	d, err := ParseSuccession(ev)
 235  	if err != nil {
 236  		return err
 237  	}
 238  	c.delegations[hex.EncodeToString(d.Event.ID)] = ev
 239  	return nil
 240  }
 241  
 242  // Resolve returns the latest valid record for an asset id, given the author of
 243  // the source event.
 244  //
 245  // The root record must be signed by the source author and carry no prev. Each
 246  // successor must be signed by the outgoing record's author and carry a prev
 247  // pointing at the outgoing record plus a succession delegation signed by that
 248  // same outgoing key and naming the successor. A self-rooted record from a rogue
 249  // key, a bare key change without a delegation, and a signed delegation that
 250  // does not name the successor are all rejected.
 251  func (c *Chain) Resolve(assetID string, sourceAuthor []byte) (*AssetRecord, error) {
 252  	if len(sourceAuthor) != 32 {
 253  		return nil, fmt.Errorf("deed: source author must be a 32-byte pubkey")
 254  	}
 255  
 256  	var roots []*AssetRecord
 257  	for _, r := range c.records {
 258  		if r.AssetID != assetID {
 259  			continue
 260  		}
 261  		if r.Prev != "" {
 262  			continue
 263  		}
 264  		if !equalBytes(r.Event.Pubkey, sourceAuthor) {
 265  			continue
 266  		}
 267  		roots = append(roots, r)
 268  	}
 269  	if len(roots) == 0 {
 270  		return nil, fmt.Errorf("deed: no valid root record for asset %s signed by the source author", assetID)
 271  	}
 272  	sort.Slice(roots, func(i, j int) bool { return newer(roots[i].Event, roots[j].Event) })
 273  
 274  	// Choose the best tip reachable from a valid root. Branches are permitted;
 275  	// the newest valid tip wins.
 276  	var best *AssetRecord
 277  	for _, root := range roots {
 278  		tip := c.walk(root)
 279  		if best == nil || newer(tip.Event, best.Event) {
 280  			best = tip
 281  		}
 282  	}
 283  	if best == nil {
 284  		return nil, fmt.Errorf("deed: no valid record for asset %s", assetID)
 285  	}
 286  	return best, nil
 287  }
 288  
 289  // walk follows succession edges from a root, refusing any edge that is not
 290  // signed by the outgoing key and authorized by a delegation.
 291  func (c *Chain) walk(root *AssetRecord) *AssetRecord {
 292  	current := root
 293  	seen := map[string]bool{hex.EncodeToString(root.Event.ID): true}
 294  	for {
 295  		var next *AssetRecord
 296  		for _, r := range c.records {
 297  			if r.Prev != hex.EncodeToString(current.Event.ID) {
 298  				continue
 299  			}
 300  			if seen[hex.EncodeToString(r.Event.ID)] {
 301  				continue
 302  			}
 303  			if !equalBytes(r.Event.Pubkey, current.Event.Pubkey) {
 304  				// The successor must hold a delegation. A record signed by the
 305  				// outgoing key means the same key republished, which is allowed
 306  				// only if it also carries a delegation naming itself — pointless
 307  				// but harmless. A record signed by a third key without a valid
 308  				// delegation is never accepted.
 309  				if r.Succession == "" {
 310  					continue
 311  				}
 312  				del, ok := c.delegations[r.Succession]
 313  				if !ok {
 314  					continue
 315  				}
 316  				d, err := ParseSuccession(del)
 317  				if err != nil {
 318  					continue
 319  				}
 320  				if !equalBytes(d.Outgoing, current.Event.Pubkey) {
 321  					continue
 322  				}
 323  				if !equalBytes(d.Incoming, r.Event.Pubkey) {
 324  					continue
 325  				}
 326  				if d.ScopeAsset != "" && d.ScopeAsset != r.AssetID {
 327  					continue
 328  				}
 329  			}
 330  			if next == nil || newer(r.Event, next.Event) {
 331  				next = r
 332  			}
 333  		}
 334  		if next == nil {
 335  			return current
 336  		}
 337  		seen[hex.EncodeToString(next.Event.ID)] = true
 338  		current = next
 339  	}
 340  }
 341  
 342  // newer orders events by created_at, tie-broken by the lower id.
 343  func newer(a, b *event.E) bool {
 344  	if a.CreatedAt != b.CreatedAt {
 345  		return a.CreatedAt > b.CreatedAt
 346  	}
 347  	return string(a.ID) < string(b.ID)
 348  }
 349  
 350  func tagValue(ev *event.E, name string) string {
 351  	if ev == nil || ev.Tags == nil {
 352  		return ""
 353  	}
 354  	t := ev.Tags.GetFirst([]byte(name))
 355  	if t == nil {
 356  		return ""
 357  	}
 358  	return string(t.Value())
 359  }
 360  
 361  func equalBytes(a, b []byte) bool {
 362  	if len(a) != len(b) {
 363  		return false
 364  	}
 365  	var v byte
 366  	for i := range a {
 367  		v |= a[i] ^ b[i]
 368  	}
 369  	return v == 0
 370  }
 371  
 372  // newTag is a small helper for callers that build events.
 373  func newTag(elems ...string) *tag.T {
 374  	t := tag.New()
 375  	for _, e := range elems {
 376  		t.T = append(t.T, []byte(e))
 377  	}
 378  	return t
 379  }
 380