// Package deed implements musiquay asset identity, entitlement deeds, deed // presentation proofs, and owner key succession. // // The package is deliberately usable without a relay: a host that has onboarded // a catalogue and pinned the author keys can verify a deed offline. Anything it // cannot check locally is expressed as a function field, so a cold host can // supply a network-backed lookup and fail closed when the lookup fails. package deed import ( "crypto/sha256" "encoding/hex" "fmt" "sort" "strings" "git.smesh.lol/orly/pkg/nostr/encoders/event" "git.smesh.lol/orly/pkg/nostr/encoders/kind" "git.smesh.lol/orly/pkg/nostr/encoders/tag" ) const ( // AssetIDDomain is the domain separator for the asset id derivation. AssetIDDomain = "musiquay.asset.v1" // TagAsset is the tag naming an asset id on track, album, edition, deed, // receipt, and aggregate events. TagAsset = "asset" // TagSource is the 3224 tag naming the first asset event id. TagSource = "source" // TagOwner is the 3224 tag naming the current owner. TagOwner = "owner" // TagPrev is the 3224 tag naming the previous record id. TagPrev = "prev" // TagSuccession is the 3224 tag naming the succession delegation id. TagSuccession = "succession" // TagCoordinate is the addressable coordinate tag ("a"). TagCoordinate = "a" // TagD is the addressable d tag, reused by 3224 as the asset id. TagD = "d" // TagRetailer names a retailer authorized to sell an asset, on a 3224 // record or on the asset event itself. TagRetailer = "retailer" // TagStandalone marks an edition that is sold independently and therefore // owns its own asset id. TagStandalone = "standalone" ) // Asset kinds that can own an asset id. var assetKinds = map[uint16]bool{ kind.Track.ToU16(): true, kind.Album.ToU16(): true, kind.Edition.ToU16(): true, } // DeriveAssetID returns the stable asset id for the event that first published // an asset: hex(SHA-256("musiquay.asset.v1|" || )). // // firstEventID may be a raw 32-byte id or its 64-character hex form. func DeriveAssetID(firstEventID []byte) (string, error) { var raw []byte switch len(firstEventID) { case 32: raw = firstEventID case 64: var err error if raw, err = hex.DecodeString(string(firstEventID)); err != nil { return "", fmt.Errorf("deed: asset source id: %w", err) } default: return "", fmt.Errorf("deed: asset source id must be 32 bytes or 64 hex characters, got %d", len(firstEventID)) } h := sha256.New() h.Write([]byte(AssetIDDomain)) h.Write([]byte("|")) h.Write(raw) return hex.EncodeToString(h.Sum(nil)), nil } // IsAssetID reports whether s is a 64-character lower-case hex asset id. func IsAssetID(s string) bool { if len(s) != 64 { return false } _, err := hex.DecodeString(s) return err == nil && strings.ToLower(s) == s } // AssetRecord is a parsed and structurally verified kind 3224 event. type AssetRecord struct { Event *event.E // AssetID is the d tag. AssetID string // Source is the hex id of the first asset event. Source string // Owner is the key named by the owner tag, or the record signer when absent. Owner []byte // Coordinate is the current addressable coordinate, "kind:pubkey:d". Coordinate string // Prev is the previous record id, empty for the root. Prev string // Succession is the succession delegation id, empty for the root. Succession string // Retailers are keys authorized to sell the asset. Retailers [][]byte } // ParseAssetRecord performs the checks that need no external data: kind, // signature, asset id derivation, and tag shape. Chain anchoring is done by // Chain.Resolve. func ParseAssetRecord(ev *event.E) (*AssetRecord, error) { if ev == nil { return nil, fmt.Errorf("deed: nil asset record") } if ev.Kind != kind.AssetIdentity.ToU16() { return nil, fmt.Errorf("deed: kind %d is not an asset identity record", ev.Kind) } if valid, err := ev.Verify(); err != nil { return nil, fmt.Errorf("deed: verify asset record: %w", err) } else if !valid { return nil, fmt.Errorf("deed: asset record signature invalid") } assetID := tagValue(ev, TagD) if !IsAssetID(assetID) { return nil, fmt.Errorf("deed: asset record has an invalid d tag %q", assetID) } source := tagValue(ev, TagSource) if len(source) != 64 { return nil, fmt.Errorf("deed: asset record has no valid source tag") } derived, err := DeriveAssetID([]byte(source)) if err != nil { return nil, err } if derived != assetID { return nil, fmt.Errorf("deed: asset id %s does not derive from source %s", assetID, source) } r := &AssetRecord{ Event: ev, AssetID: assetID, Source: source, Coordinate: tagValue(ev, TagCoordinate), Prev: tagValue(ev, TagPrev), Succession: tagValue(ev, TagSuccession), } if owner := tagValue(ev, TagOwner); owner != "" { raw, err := hex.DecodeString(owner) if err != nil || len(raw) != 32 { return nil, fmt.Errorf("deed: asset record has an invalid owner tag") } r.Owner = raw } else { r.Owner = append([]byte(nil), ev.Pubkey...) } if r.Coordinate != "" { k, pub, d, err := splitCoordinate(r.Coordinate) if err != nil { return nil, err } if !assetKinds[k] { return nil, fmt.Errorf("deed: asset record coordinate kind %d is not an asset kind", k) } if d == "" || pub == "" { return nil, fmt.Errorf("deed: asset record coordinate %q is incomplete", r.Coordinate) } } for _, t := range ev.Tags.GetAll([]byte(TagRetailer)) { raw, err := hex.DecodeString(string(t.Value())) if err != nil || len(raw) != 32 { return nil, fmt.Errorf("deed: asset record has an invalid retailer tag") } r.Retailers = append(r.Retailers, raw) } return r, nil } // splitCoordinate parses "kind:pubkey:d". func splitCoordinate(a string) (k uint16, pub, d string, err error) { parts := strings.SplitN(a, ":", 3) if len(parts) != 3 { return 0, "", "", fmt.Errorf("deed: coordinate %q must be kind:pubkey:d", a) } var kk uint32 if _, err = fmt.Sscanf(parts[0], "%d", &kk); err != nil || kk > 65535 { return 0, "", "", fmt.Errorf("deed: coordinate %q has an invalid kind", a) } if len(parts[1]) != 64 { return 0, "", "", fmt.Errorf("deed: coordinate %q has an invalid pubkey", a) } if _, err = hex.DecodeString(parts[1]); err != nil { return 0, "", "", fmt.Errorf("deed: coordinate %q has an invalid pubkey", a) } if parts[2] == "" { return 0, "", "", fmt.Errorf("deed: coordinate %q has an empty d tag", a) } return uint16(kk), parts[1], parts[2], nil } // Chain accumulates asset records and succession delegations so a host can // resolve an asset id to the latest valid record. type Chain struct { records []*AssetRecord byID map[string]*AssetRecord delegations map[string]*event.E } // NewChain returns an empty chain. func NewChain() *Chain { return &Chain{ byID: make(map[string]*AssetRecord), delegations: make(map[string]*event.E), } } // AddRecord parses and adds a 3224 event. A record that fails the structural // checks is returned as an error and not added. func (c *Chain) AddRecord(ev *event.E) (*AssetRecord, error) { r, err := ParseAssetRecord(ev) if err != nil { return nil, err } id := hex.EncodeToString(r.Event.ID) if prev, ok := c.byID[id]; ok { return prev, nil } c.byID[id] = r c.records = append(c.records, r) return r, nil } // AddDelegation adds a succession delegation. Invalid delegations are ignored, // because a rogue key may publish one and it must not poison a valid chain. func (c *Chain) AddDelegation(ev *event.E) error { d, err := ParseSuccession(ev) if err != nil { return err } c.delegations[hex.EncodeToString(d.Event.ID)] = ev return nil } // Resolve returns the latest valid record for an asset id, given the author of // the source event. // // The root record must be signed by the source author and carry no prev. Each // successor must be signed by the outgoing record's author and carry a prev // pointing at the outgoing record plus a succession delegation signed by that // same outgoing key and naming the successor. A self-rooted record from a rogue // key, a bare key change without a delegation, and a signed delegation that // does not name the successor are all rejected. func (c *Chain) Resolve(assetID string, sourceAuthor []byte) (*AssetRecord, error) { if len(sourceAuthor) != 32 { return nil, fmt.Errorf("deed: source author must be a 32-byte pubkey") } var roots []*AssetRecord for _, r := range c.records { if r.AssetID != assetID { continue } if r.Prev != "" { continue } if !equalBytes(r.Event.Pubkey, sourceAuthor) { continue } roots = append(roots, r) } if len(roots) == 0 { return nil, fmt.Errorf("deed: no valid root record for asset %s signed by the source author", assetID) } sort.Slice(roots, func(i, j int) bool { return newer(roots[i].Event, roots[j].Event) }) // Choose the best tip reachable from a valid root. Branches are permitted; // the newest valid tip wins. var best *AssetRecord for _, root := range roots { tip := c.walk(root) if best == nil || newer(tip.Event, best.Event) { best = tip } } if best == nil { return nil, fmt.Errorf("deed: no valid record for asset %s", assetID) } return best, nil } // walk follows succession edges from a root, refusing any edge that is not // signed by the outgoing key and authorized by a delegation. func (c *Chain) walk(root *AssetRecord) *AssetRecord { current := root seen := map[string]bool{hex.EncodeToString(root.Event.ID): true} for { var next *AssetRecord for _, r := range c.records { if r.Prev != hex.EncodeToString(current.Event.ID) { continue } if seen[hex.EncodeToString(r.Event.ID)] { continue } if !equalBytes(r.Event.Pubkey, current.Event.Pubkey) { // The successor must hold a delegation. A record signed by the // outgoing key means the same key republished, which is allowed // only if it also carries a delegation naming itself — pointless // but harmless. A record signed by a third key without a valid // delegation is never accepted. if r.Succession == "" { continue } del, ok := c.delegations[r.Succession] if !ok { continue } d, err := ParseSuccession(del) if err != nil { continue } if !equalBytes(d.Outgoing, current.Event.Pubkey) { continue } if !equalBytes(d.Incoming, r.Event.Pubkey) { continue } if d.ScopeAsset != "" && d.ScopeAsset != r.AssetID { continue } } if next == nil || newer(r.Event, next.Event) { next = r } } if next == nil { return current } seen[hex.EncodeToString(next.Event.ID)] = true current = next } } // newer orders events by created_at, tie-broken by the lower id. func newer(a, b *event.E) bool { if a.CreatedAt != b.CreatedAt { return a.CreatedAt > b.CreatedAt } return string(a.ID) < string(b.ID) } func tagValue(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.Value()) } func equalBytes(a, b []byte) bool { if len(a) != len(b) { return false } var v byte for i := range a { v |= a[i] ^ b[i] } return v == 0 } // newTag is a small helper for callers that build events. func newTag(elems ...string) *tag.T { t := tag.New() for _, e := range elems { t.T = append(t.T, []byte(e)) } return t }