succession.go raw

   1  package deed
   2  
   3  import (
   4  	"encoding/hex"
   5  	"fmt"
   6  	"time"
   7  
   8  	"git.smesh.lol/orly/pkg/nostr/encoders/event"
   9  	"git.smesh.lol/orly/pkg/nostr/encoders/ints"
  10  )
  11  
  12  // Succession label namespace and value. An owner key rotation is a NIP-32 label
  13  // event signed by the outgoing key. A bare key change is not a rotation.
  14  const (
  15  	// SuccessionNamespace is the NIP-32 L namespace.
  16  	SuccessionNamespace = "musiquay.succession"
  17  	// SuccessionLabel is the NIP-32 l value.
  18  	SuccessionLabel = "succession"
  19  	// LabelKind is the NIP-32 label event kind.
  20  	LabelKind = 1985
  21  )
  22  
  23  // Succession is a parsed key-rotation delegation.
  24  type Succession struct {
  25  	Event *event.E
  26  	// Outgoing is the key that signed the delegation.
  27  	Outgoing []byte
  28  	// Incoming is the key named by the p tag.
  29  	Incoming []byte
  30  	// ScopeCoordinate is the optional a-tag coordinate; empty means the
  31  	// delegation covers every asset owned by the outgoing key.
  32  	ScopeCoordinate string
  33  	// ScopeAsset is the optional asset tag; empty means unscoped.
  34  	ScopeAsset string
  35  	// Prev is an optional previous delegation id.
  36  	Prev string
  37  	// Expires is the optional unix expiry; zero means no expiry.
  38  	Expires int64
  39  }
  40  
  41  // ParseSuccession structurally validates a succession delegation.
  42  func ParseSuccession(ev *event.E) (*Succession, error) {
  43  	if ev == nil {
  44  		return nil, fmt.Errorf("deed: nil succession delegation")
  45  	}
  46  	if ev.Kind != LabelKind {
  47  		return nil, fmt.Errorf("deed: kind %d is not a NIP-32 label", ev.Kind)
  48  	}
  49  	if valid, err := ev.Verify(); err != nil {
  50  		return nil, fmt.Errorf("deed: verify succession: %w", err)
  51  	} else if !valid {
  52  		return nil, fmt.Errorf("deed: succession signature invalid")
  53  	}
  54  	if !hasLabel(ev, SuccessionNamespace, SuccessionLabel) {
  55  		return nil, fmt.Errorf("deed: event is not a %s label", SuccessionNamespace)
  56  	}
  57  	p := ev.Tags.GetFirst([]byte("p"))
  58  	if p == nil {
  59  		return nil, fmt.Errorf("deed: succession delegation has no incoming p tag")
  60  	}
  61  	incoming, err := hex.DecodeString(string(p.ValueHex()))
  62  	if err != nil || len(incoming) != 32 {
  63  		return nil, fmt.Errorf("deed: succession delegation has an invalid incoming key")
  64  	}
  65  	s := &Succession{
  66  		Event:           ev,
  67  		Outgoing:        append([]byte(nil), ev.Pubkey...),
  68  		Incoming:        incoming,
  69  		ScopeCoordinate: tagValue(ev, TagCoordinate),
  70  		ScopeAsset:      tagValue(ev, TagAsset),
  71  		Prev:            tagValue(ev, "e"),
  72  	}
  73  	if s.ScopeAsset != "" && !IsAssetID(s.ScopeAsset) {
  74  		return nil, fmt.Errorf("deed: succession delegation has an invalid asset scope")
  75  	}
  76  	if raw := tagValue(ev, "expiration"); raw != "" {
  77  		n := ints.New(0)
  78  		rem, err := n.Unmarshal([]byte(raw))
  79  		if err != nil || len(rem) > 0 {
  80  			return nil, fmt.Errorf("deed: succession delegation has an invalid expiration")
  81  		}
  82  		s.Expires = n.Int64()
  83  	}
  84  	if s.Expires != 0 && s.Expires <= time.Now().Unix() {
  85  		return nil, fmt.Errorf("deed: succession delegation expired")
  86  	}
  87  	if equalBytes(s.Outgoing, s.Incoming) {
  88  		return nil, fmt.Errorf("deed: succession delegation names the same key")
  89  	}
  90  	return s, nil
  91  }
  92  
  93  // hasLabel reports whether a NIP-32 event carries the namespace and value.
  94  func hasLabel(ev *event.E, namespace, value string) bool {
  95  	okNamespace := false
  96  	for _, t := range ev.Tags.GetAll([]byte("L")) {
  97  		if string(t.Value()) == namespace {
  98  			okNamespace = true
  99  			break
 100  		}
 101  	}
 102  	if !okNamespace {
 103  		return false
 104  	}
 105  	for _, t := range ev.Tags.GetAll([]byte("l")) {
 106  		if string(t.Value()) != value {
 107  			continue
 108  		}
 109  		// The third element is the namespace, when present.
 110  		if len(t.T) >= 3 && string(t.T[2]) != namespace {
 111  			continue
 112  		}
 113  		return true
 114  	}
 115  	return false
 116  }
 117  
 118  // ResolveSuccessor follows a succession chain from original to target.
 119  //
 120  // The assetID, when non-empty, filters out delegations scoped to another asset.
 121  // An unscoped delegation applies to every asset. Expired delegations are
 122  // ignored. The chain must be continuous: each hop's Outgoing must be the key
 123  // reached by the previous hop.
 124  func ResolveSuccessor(original, target []byte, assetID string, delegations []*event.E) (bool, error) {
 125  	if equalBytes(original, target) {
 126  		return true, nil
 127  	}
 128  	parsed := make([]*Succession, 0, len(delegations))
 129  	for _, ev := range delegations {
 130  		s, err := ParseSuccession(ev)
 131  		if err != nil {
 132  			continue
 133  		}
 134  		if s.ScopeAsset != "" && assetID != "" && s.ScopeAsset != assetID {
 135  			continue
 136  		}
 137  		parsed = append(parsed, s)
 138  	}
 139  
 140  	// Breadth-first over the delegation graph, with a visited set so a cycle
 141  	// cannot loop.
 142  	visited := map[string]bool{string(original): true}
 143  	frontier := [][]byte{original}
 144  	for len(frontier) > 0 {
 145  		next := make([][]byte, 0, len(parsed))
 146  		for _, cur := range frontier {
 147  			for _, s := range parsed {
 148  				if !equalBytes(s.Outgoing, cur) {
 149  					continue
 150  				}
 151  				if equalBytes(s.Incoming, target) {
 152  					return true, nil
 153  				}
 154  				if visited[string(s.Incoming)] {
 155  					continue
 156  				}
 157  				visited[string(s.Incoming)] = true
 158  				next = append(next, s.Incoming)
 159  			}
 160  		}
 161  		frontier = next
 162  	}
 163  	return false, fmt.Errorf("deed: no valid succession path from %x to %x", original, target)
 164  }
 165