directory_client

package
v0.20.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2025 License: Unlicense Imports: 5 Imported by: 0

README

Directory Client Library

High-level Go client library for the Distributed Directory Consensus Protocol (NIP-XX).

Overview

This package provides a convenient API for working with directory events, managing identity resolution, tracking key delegations, and computing trust scores. It builds on the lower-level directory protocol package.

Features

  • Identity Resolution: Track and resolve delegate keys to their primary identities
  • Trust Management: Calculate aggregate trust scores from multiple trust acts
  • Replication Filtering: Determine which relays to trust for event replication
  • Event Collection: Convenient utilities for extracting specific event types
  • Trust Graph: Build and analyze trust relationship networks
  • Thread-Safe: All components support concurrent access

Installation

import "next.orly.dev/pkg/protocol/directory-client"

Quick Start

Identity Resolution
// Create an identity resolver
resolver := directory_client.NewIdentityResolver()

// Process events to build identity mappings
for _, event := range events {
    resolver.ProcessEvent(event)
}

// Resolve identity behind a delegate key
actualIdentity := resolver.ResolveIdentity(delegateKey)

// Check if a key is a delegate
if resolver.IsDelegateKey(pubkey) {
    tag, _ := resolver.GetIdentityTag(pubkey)
    fmt.Printf("Delegate belongs to: %s\n", tag.Identity)
}

// Get all delegates for an identity
delegates := resolver.GetDelegatesForIdentity(identityPubkey)

// Filter events by identity (including delegates)
filteredEvents := resolver.FilterEventsByIdentity(events, identityPubkey)
Trust Management
// Create a trust calculator
calculator := directory_client.NewTrustCalculator()

// Add trust acts
for _, event := range trustEvents {
    if act, err := directory.ParseTrustAct(event); err == nil {
        calculator.AddAct(act)
    }
}

// Calculate aggregate trust score (0-100)
score := calculator.CalculateTrust(targetPubkey)

// Get active (non-expired) trust acts
activeActs := calculator.GetActiveTrustActs(targetPubkey)
Replication Filtering
// Create filter with minimum trust score threshold
filter := directory_client.NewReplicationFilter(50)

// Add trust acts
for _, act := range trustActs {
    filter.AddTrustAct(act)
}

// Check if should replicate from a relay
if filter.ShouldReplicate(relayPubkey) {
    // Proceed with replication
}

// Get all trusted relays
trustedRelays := filter.GetTrustedRelays()

// Filter events to only trusted sources
trustedEvents := filter.FilterEvents(events)
Event Collection
// Create event collector
collector := directory_client.NewEventCollector(events)

// Extract specific event types
identities := collector.RelayIdentities()
trustActs := collector.TrustActs()
groupTagActs := collector.GroupTagActs()
keyAds := collector.PublicKeyAdvertisements()
requests := collector.ReplicationRequests()
responses := collector.ReplicationResponses()

// Find specific events
identity, found := directory_client.FindRelayIdentity(events, "wss://relay.example.com/")
trustActs := directory_client.FindTrustActsForRelay(events, targetPubkey)
groupActs := directory_client.FindGroupTagActsByGroup(events, "premium")
Trust Graph Analysis
// Build trust graph from events
graph := directory_client.BuildTrustGraph(events)

// Find who trusts a relay
trustedBy := graph.GetTrustedBy(targetPubkey)
fmt.Printf("Trusted by %d relays\n", len(trustedBy))

// Find who a relay trusts
targets := graph.GetTrustTargets(sourcePubkey)
fmt.Printf("Trusts %d relays\n", len(targets))

// Get all trust acts from a source
acts := graph.GetTrustActs(sourcePubkey)

API Reference

IdentityResolver

Manages identity resolution and key delegation tracking.

Methods:

  • NewIdentityResolver() *IdentityResolver - Create new instance
  • ProcessEvent(ev *event.E) - Process event to extract identity info
  • ResolveIdentity(pubkey string) string - Resolve delegate to identity
  • ResolveEventIdentity(ev *event.E) string - Resolve event's identity
  • IsDelegateKey(pubkey string) bool - Check if key is a delegate
  • IsIdentityKey(pubkey string) bool - Check if key has delegates
  • GetDelegatesForIdentity(identity string) []string - Get all delegates
  • GetIdentityTag(delegate string) (*IdentityTag, error) - Get identity tag
  • GetPublicKeyAdvertisements(identity string) []*PublicKeyAdvertisement - Get key ads
  • FilterEventsByIdentity(events []*event.E, identity string) []*event.E - Filter events
  • ClearCache() - Clear all cached mappings
  • GetStats() Stats - Get statistics
TrustCalculator

Computes aggregate trust scores from multiple trust acts.

Methods:

  • NewTrustCalculator() *TrustCalculator - Create new instance
  • AddAct(act *TrustAct) - Add a trust act
  • CalculateTrust(pubkey string) float64 - Calculate trust score (0-100)
  • GetActs(pubkey string) []*TrustAct - Get all acts for pubkey
  • GetActiveTrustActs(pubkey string) []*TrustAct - Get non-expired acts
  • Clear() - Remove all acts
  • GetAllPubkeys() []string - Get all tracked pubkeys

Trust Score Weights:

  • High: 100
  • Medium: 50
  • Low: 25
ReplicationFilter

Manages replication decisions based on trust scores.

Methods:

  • NewReplicationFilter(minTrustScore float64) *ReplicationFilter - Create new instance
  • AddTrustAct(act *TrustAct) - Add trust act and update trusted relays
  • ShouldReplicate(pubkey string) bool - Check if relay is trusted
  • GetTrustedRelays() []string - Get all trusted relay pubkeys
  • GetTrustScore(pubkey string) float64 - Get trust score for relay
  • SetMinTrustScore(minScore float64) - Update threshold
  • GetMinTrustScore() float64 - Get current threshold
  • FilterEvents(events []*event.E) []*event.E - Filter to trusted events
EventCollector

Utility for collecting specific types of directory events.

Methods:

  • NewEventCollector(events []*event.E) *EventCollector - Create new instance
  • RelayIdentities() []*RelayIdentity - Get all relay identities
  • TrustActs() []*TrustAct - Get all trust acts
  • GroupTagActs() []*GroupTagAct - Get all group tag acts
  • PublicKeyAdvertisements() []*PublicKeyAdvertisement - Get all key ads
  • ReplicationRequests() []*ReplicationRequest - Get all requests
  • ReplicationResponses() []*ReplicationResponse - Get all responses
Helper Functions

Event Filtering:

  • IsDirectoryEvent(ev *event.E) bool - Check if event is directory event
  • FilterDirectoryEvents(events []*event.E) []*event.E - Filter to directory events
  • ParseDirectoryEvent(ev *event.E) (interface{}, error) - Parse any directory event

Event Finding:

  • FindRelayIdentity(events, relayURL) (*RelayIdentity, bool) - Find identity by URL
  • FindTrustActsForRelay(events, targetPubkey) []*TrustAct - Find trust acts
  • FindGroupTagActsForRelay(events, targetPubkey) []*GroupTagAct - Find group acts
  • FindGroupTagActsByGroup(events, groupTag) []*GroupTagAct - Find by group

URL Utilities:

  • NormalizeRelayURL(url string) string - Ensure trailing slash

Trust Graph:

  • NewTrustGraph() *TrustGraph - Create new graph
  • BuildTrustGraph(events []*event.E) *TrustGraph - Build from events
  • AddTrustAct(act *TrustAct) - Add trust act to graph
  • GetTrustActs(source string) []*TrustAct - Get acts from source
  • GetTrustedBy(target string) []string - Get who trusts target
  • GetTrustTargets(source string) []string - Get who source trusts

Thread Safety

All components are thread-safe and can be used concurrently from multiple goroutines. Internal state is protected by read-write mutexes (sync.RWMutex).

Performance Considerations

  • IdentityResolver: Maintains in-memory caches. Use ClearCache() if needed
  • TrustCalculator: Stores all trust acts in memory. Consider periodic cleanup of expired acts
  • ReplicationFilter: Minimal memory overhead, recalculates trust on each act addition

Integration

This package works with:

  • directory protocol package: For parsing and creating events
  • event package: For event structures
  • EventStore: Can be integrated with any event storage system

License

See LICENSE file.

Documentation

Overview

Package directory_client provides a client library for the Distributed Directory Consensus Protocol (NIP-XX).

This package offers a high-level API for working with directory events, managing identity resolution, tracking key delegations, and computing trust scores. It builds on the lower-level directory protocol package.

Basic Usage

// Create an identity resolver
resolver := directory_client.NewIdentityResolver()

// Parse and track events
event := getDirectoryEvent()
resolver.ProcessEvent(event)

// Resolve identity behind a delegate key
actualIdentity := resolver.ResolveIdentity(delegateKey)

// Check if a key is a delegate
isDelegate := resolver.IsDelegateKey(pubkey)

Trust Management

// Create a trust calculator
calculator := directory_client.NewTrustCalculator()

// Add trust acts
trustAct := directory.ParseTrustAct(event)
calculator.AddAct(trustAct)

// Calculate aggregate trust score
score := calculator.CalculateTrust(targetPubkey)

Replication Filtering

// Create a replication filter
filter := directory_client.NewReplicationFilter(50) // min trust score of 50

// Add trust acts to influence replication decisions
filter.AddTrustAct(trustAct)

// Check if should replicate from a relay
if filter.ShouldReplicate(relayPubkey) {
	// Proceed with replication
}

Event Filtering

// Filter directory events from a stream
events := getEvents()
directoryEvents := directory_client.FilterDirectoryEvents(events)

// Check if an event is a directory event
if directory_client.IsDirectoryEvent(event) {
	// Handle directory event
}

Package directory_client provides a high-level client API for the Distributed Directory Consensus Protocol (NIP-XX).

Overview

This package builds on top of the lower-level directory protocol package to provide convenient utilities for:

  • Identity resolution and key delegation tracking
  • Trust score calculation and aggregation
  • Replication filtering based on trust relationships
  • Event collection and filtering
  • Trust graph construction and analysis

Architecture

The client library consists of several main components:

**IdentityResolver**: Tracks mappings between delegate keys and primary identities, enabling resolution of the actual identity behind any signing key. It processes Identity Tags (I tags) from events and maintains a cache of delegation relationships.

**TrustCalculator**: Computes aggregate trust scores from multiple trust acts using a weighted average approach. Trust levels (high/medium/low) are mapped to numeric weights and non-expired acts are combined to produce an overall trust score.

**ReplicationFilter**: Uses trust scores to determine which relays should be trusted for event replication. It maintains a set of trusted relays based on a configurable minimum trust score threshold.

**EventCollector**: Provides convenient methods to extract and parse specific types of directory events from a collection.

**TrustGraph**: Represents trust relationships as a directed graph, enabling analysis of trust networks and transitive trust paths.

Thread Safety

All components are thread-safe and can be used concurrently from multiple goroutines. Internal state is protected by read-write mutexes.

Example: Identity Resolution

resolver := directory_client.NewIdentityResolver()

// Process events to build identity mappings
for _, event := range events {
	resolver.ProcessEvent(event)
}

// Resolve identity behind a delegate key
actualIdentity := resolver.ResolveIdentity(delegateKey)

// Check delegation status
if resolver.IsDelegateKey(pubkey) {
	tag, _ := resolver.GetIdentityTag(pubkey)
	fmt.Printf("Delegate %s belongs to identity %s\n",
		pubkey, tag.Identity)
}

Example: Trust Management

calculator := directory_client.NewTrustCalculator()

// Add trust acts
for _, event := range trustEvents {
	if act, err := directory.ParseTrustAct(event); err == nil {
		calculator.AddAct(act)
	}
}

// Calculate trust score
score := calculator.CalculateTrust(targetPubkey)
fmt.Printf("Trust score: %.1f\n", score)

Example: Replication Filtering

// Create filter with minimum trust score of 50
filter := directory_client.NewReplicationFilter(50)

// Add trust acts to influence decisions
for _, act := range trustActs {
	filter.AddTrustAct(act)
}

// Check if should replicate from a relay
if filter.ShouldReplicate(relayPubkey) {
	// Proceed with replication
	events := fetchEventsFromRelay(relayPubkey)
	// ...
}

Example: Event Collection

collector := directory_client.NewEventCollector(events)

// Extract specific event types
identities := collector.RelayIdentities()
trustActs := collector.TrustActs()
keyAds := collector.PublicKeyAdvertisements()

// Find specific events
if identity, found := directory_client.FindRelayIdentity(
	events, "wss://relay.example.com/"); found {
	fmt.Printf("Found relay identity: %s\n", identity.RelayURL)
}

Example: Trust Graph Analysis

graph := directory_client.BuildTrustGraph(events)

// Find who trusts a specific relay
trustedBy := graph.GetTrustedBy(targetPubkey)
fmt.Printf("Trusted by %d relays\n", len(trustedBy))

// Find who a relay trusts
targets := graph.GetTrustTargets(sourcePubkey)
fmt.Printf("Trusts %d relays\n", len(targets))

Integration with Directory Protocol

This package is designed to work seamlessly with the lower-level directory protocol package (next.orly.dev/pkg/protocol/directory). Use the protocol package for:

  • Parsing individual directory events
  • Creating new directory events
  • Validating event structure
  • Working with event content and tags

Use the client package for:

  • Managing collections of events
  • Tracking identity relationships
  • Computing trust metrics
  • Filtering events for replication
  • Analyzing trust networks

Performance Considerations

The IdentityResolver maintains in-memory caches of identity mappings. For large numbers of identities and delegates, memory usage will grow proportionally. Use ClearCache() if you need to free memory.

The TrustCalculator stores all trust acts in memory. For long-running applications processing many trust acts, consider periodically clearing expired acts or implementing a sliding window approach.

See the NIP-XX specification for details on the protocol:

docs/NIP-XX-distributed-directory-consensus.md

See the directory protocol package for low-level event handling:

pkg/protocol/directory/

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FilterDirectoryEvents

func FilterDirectoryEvents(events []*event.E) (filtered []*event.E)

FilterDirectoryEvents filters a slice of events to only directory events.

func FindGroupTagActsByGroup

func FindGroupTagActsByGroup(events []*event.E, groupID string) (acts []*directory.GroupTagAct)

FindGroupTagActsByGroup finds all group tag acts for a specific group.

func FindGroupTagActsForRelay

func FindGroupTagActsForRelay(events []*event.E, targetPubkey string) (acts []*directory.GroupTagAct)

FindGroupTagActsForRelay finds all group tag acts targeting a specific relay. Note: This function needs to be updated based on the actual GroupTagAct structure which doesn't have a Target field. The filtering logic should be clarified.

func FindRelayIdentity

func FindRelayIdentity(events []*event.E, relayURL string) (*directory.RelayIdentityAnnouncement, bool)

FindRelayIdentity finds a relay identity by relay URL.

func FindTrustActsForRelay

func FindTrustActsForRelay(events []*event.E, targetPubkey string) (acts []*directory.TrustAct)

FindTrustActsForRelay finds all trust acts targeting a specific relay.

func IsDirectoryEvent

func IsDirectoryEvent(ev *event.E) bool

IsDirectoryEvent checks if an event is a directory consensus event.

func NormalizeRelayURL

func NormalizeRelayURL(url string) string

NormalizeRelayURL ensures a relay URL has the canonical format with trailing slash.

func ParseDirectoryEvent

func ParseDirectoryEvent(ev *event.E) (parsed interface{}, err error)

ParseDirectoryEvent parses any directory event based on its kind.

Types

type EventCollector

type EventCollector struct {
	// contains filtered or unexported fields
}

EventCollector provides utility methods for collecting specific types of directory events from a slice.

func NewEventCollector

func NewEventCollector(events []*event.E) *EventCollector

NewEventCollector creates a new event collector for the given events.

func (*EventCollector) GroupTagActs

func (ec *EventCollector) GroupTagActs() (acts []*directory.GroupTagAct)

GroupTagActs returns all group tag acts.

func (*EventCollector) PublicKeyAdvertisements

func (ec *EventCollector) PublicKeyAdvertisements() (ads []*directory.PublicKeyAdvertisement)

PublicKeyAdvertisements returns all public key advertisements.

func (*EventCollector) RelayIdentities

func (ec *EventCollector) RelayIdentities() (identities []*directory.RelayIdentityAnnouncement)

RelayIdentities returns all relay identity declarations.

func (*EventCollector) ReplicationRequests

func (ec *EventCollector) ReplicationRequests() (requests []*directory.DirectoryEventReplicationRequest)

ReplicationRequests returns all replication requests.

func (*EventCollector) ReplicationResponses

func (ec *EventCollector) ReplicationResponses() (responses []*directory.DirectoryEventReplicationResponse)

ReplicationResponses returns all replication responses.

func (*EventCollector) TrustActs

func (ec *EventCollector) TrustActs() (acts []*directory.TrustAct)

TrustActs returns all trust acts.

type IdentityResolver

type IdentityResolver struct {
	// contains filtered or unexported fields
}

IdentityResolver manages identity resolution and key delegation tracking.

It maintains mappings between delegate keys and their primary identities, enabling clients to resolve the actual identity behind any signing key.

func NewIdentityResolver

func NewIdentityResolver() *IdentityResolver

NewIdentityResolver creates a new identity resolver instance.

func (*IdentityResolver) ClearCache

func (r *IdentityResolver) ClearCache()

ClearCache clears all cached identity mappings.

func (*IdentityResolver) FilterEventsByIdentity

func (r *IdentityResolver) FilterEventsByIdentity(events []*event.E, identity string) (filtered []*event.E)

FilterEventsByIdentity filters events to only those signed by a specific identity or its delegates.

func (*IdentityResolver) GetDelegatesForIdentity

func (r *IdentityResolver) GetDelegatesForIdentity(identity string) (delegates []string)

GetDelegatesForIdentity returns all delegate keys for a given identity.

func (*IdentityResolver) GetIdentityTag

func (r *IdentityResolver) GetIdentityTag(delegate string) (*directory.IdentityTag, error)

GetIdentityTag returns the identity tag for a delegate key.

func (*IdentityResolver) GetPublicKeyAdvertisementByID

func (r *IdentityResolver) GetPublicKeyAdvertisementByID(keyID string) (*directory.PublicKeyAdvertisement, error)

GetPublicKeyAdvertisementByID returns a public key advertisement by key ID.

func (*IdentityResolver) GetPublicKeyAdvertisements

func (r *IdentityResolver) GetPublicKeyAdvertisements(identity string) (ads []*directory.PublicKeyAdvertisement)

GetPublicKeyAdvertisements returns all public key advertisements for an identity.

func (*IdentityResolver) GetStats

func (r *IdentityResolver) GetStats() Stats

GetStats returns statistics about the resolver's state.

func (*IdentityResolver) IsDelegateKey

func (r *IdentityResolver) IsDelegateKey(pubkey string) bool

IsDelegateKey checks if a public key is a known delegate.

func (*IdentityResolver) IsIdentityKey

func (r *IdentityResolver) IsIdentityKey(pubkey string) bool

IsIdentityKey checks if a public key is a known identity (has delegates).

func (*IdentityResolver) ProcessEvent

func (r *IdentityResolver) ProcessEvent(ev *event.E)

ProcessEvent processes an event to extract and cache identity information.

This should be called for all directory events to keep the resolver's internal state up to date.

func (*IdentityResolver) ResolveEventIdentity

func (r *IdentityResolver) ResolveEventIdentity(ev *event.E) string

ResolveEventIdentity resolves the actual identity behind an event's pubkey.

func (*IdentityResolver) ResolveIdentity

func (r *IdentityResolver) ResolveIdentity(pubkey string) string

ResolveIdentity resolves the actual identity behind a public key.

If the public key is a delegate, it returns the primary identity. If the public key is already an identity, it returns the input unchanged.

type ReplicationFilter

type ReplicationFilter struct {
	// contains filtered or unexported fields
}

ReplicationFilter manages replication decisions based on trust scores.

It uses a TrustCalculator to compute trust scores and determines which relays are trusted enough for replication based on a minimum threshold.

func NewReplicationFilter

func NewReplicationFilter(minTrustScore float64) *ReplicationFilter

NewReplicationFilter creates a new replication filter with a minimum trust score threshold.

func (*ReplicationFilter) AddTrustAct

func (rf *ReplicationFilter) AddTrustAct(act *directory.TrustAct)

AddTrustAct adds a trust act and updates the trusted relays set.

func (*ReplicationFilter) FilterEvents

func (rf *ReplicationFilter) FilterEvents(events []*event.E) []*event.E

FilterEvents filters events to only those from trusted relays.

func (*ReplicationFilter) GetMinTrustScore

func (rf *ReplicationFilter) GetMinTrustScore() float64

GetMinTrustScore returns the current minimum trust score threshold.

func (*ReplicationFilter) GetTrustScore

func (rf *ReplicationFilter) GetTrustScore(pubkey string) float64

GetTrustScore returns the trust score for a relay.

func (*ReplicationFilter) GetTrustedRelays

func (rf *ReplicationFilter) GetTrustedRelays() []string

GetTrustedRelays returns all trusted relay public keys.

func (*ReplicationFilter) SetMinTrustScore

func (rf *ReplicationFilter) SetMinTrustScore(minScore float64)

SetMinTrustScore updates the minimum trust score threshold and recalculates trusted relays.

func (*ReplicationFilter) ShouldReplicate

func (rf *ReplicationFilter) ShouldReplicate(pubkey string) bool

ShouldReplicate checks if a relay is trusted enough for replication.

type Stats

type Stats struct {
	Identities   int // Number of primary identities
	Delegates    int // Number of delegate keys
	PublicKeyAds int // Number of public key advertisements
}

Stats returns statistics about tracked identities and delegates.

type TrustCalculator

type TrustCalculator struct {
	// contains filtered or unexported fields
}

TrustCalculator computes aggregate trust scores from multiple trust acts.

It maintains a collection of trust acts and provides methods to calculate weighted trust scores for relay public keys.

func NewTrustCalculator

func NewTrustCalculator() *TrustCalculator

NewTrustCalculator creates a new trust calculator instance.

func (*TrustCalculator) AddAct

func (tc *TrustCalculator) AddAct(act *directory.TrustAct)

AddAct adds a trust act to the calculator.

func (*TrustCalculator) CalculateTrust

func (tc *TrustCalculator) CalculateTrust(pubkey string) float64

CalculateTrust calculates an aggregate trust score for a public key.

The score is computed as a weighted average where:

  • high trust = 100
  • medium trust = 50
  • low trust = 25

Expired trust acts are excluded from the calculation. Returns a score between 0 and 100.

func (*TrustCalculator) Clear

func (tc *TrustCalculator) Clear()

Clear removes all trust acts from the calculator.

func (*TrustCalculator) GetActiveTrustActs

func (tc *TrustCalculator) GetActiveTrustActs(pubkey string) []*directory.TrustAct

GetActiveTrustActs returns only non-expired trust acts for a public key.

func (*TrustCalculator) GetActs

func (tc *TrustCalculator) GetActs(pubkey string) []*directory.TrustAct

GetActs returns all trust acts for a specific public key.

func (*TrustCalculator) GetAllPubkeys

func (tc *TrustCalculator) GetAllPubkeys() []string

GetAllPubkeys returns all public keys that have trust acts.

type TrustGraph

type TrustGraph struct {
	// contains filtered or unexported fields
}

TrustGraph represents a directed graph of trust relationships.

func BuildTrustGraph

func BuildTrustGraph(events []*event.E) *TrustGraph

BuildTrustGraph builds a trust graph from a collection of events.

func NewTrustGraph

func NewTrustGraph() *TrustGraph

NewTrustGraph creates a new trust graph instance.

func (*TrustGraph) AddTrustAct

func (tg *TrustGraph) AddTrustAct(act *directory.TrustAct)

AddTrustAct adds a trust act to the graph.

func (*TrustGraph) GetTrustActs

func (tg *TrustGraph) GetTrustActs(source string) []*directory.TrustAct

GetTrustActs returns all trust acts from a source pubkey.

func (*TrustGraph) GetTrustTargets

func (tg *TrustGraph) GetTrustTargets(source string) []string

GetTrustTargets returns all pubkeys trusted by the given source.

func (*TrustGraph) GetTrustedBy

func (tg *TrustGraph) GetTrustedBy(target string) []string

GetTrustedBy returns all pubkeys that trust the given target.

Source Files

  • client.go
  • doc.go
  • helpers.go
  • identity_resolver.go
  • trust.go

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL