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.
Related Documentation ¶
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 ¶
- func FilterDirectoryEvents(events []*event.E) (filtered []*event.E)
- func FindGroupTagActsByGroup(events []*event.E, groupID string) (acts []*directory.GroupTagAct)
- func FindGroupTagActsForRelay(events []*event.E, targetPubkey string) (acts []*directory.GroupTagAct)
- func FindRelayIdentity(events []*event.E, relayURL string) (*directory.RelayIdentityAnnouncement, bool)
- func FindTrustActsForRelay(events []*event.E, targetPubkey string) (acts []*directory.TrustAct)
- func IsDirectoryEvent(ev *event.E) bool
- func NormalizeRelayURL(url string) string
- func ParseDirectoryEvent(ev *event.E) (parsed interface{}, err error)
- type EventCollector
- func (ec *EventCollector) GroupTagActs() (acts []*directory.GroupTagAct)
- func (ec *EventCollector) PublicKeyAdvertisements() (ads []*directory.PublicKeyAdvertisement)
- func (ec *EventCollector) RelayIdentities() (identities []*directory.RelayIdentityAnnouncement)
- func (ec *EventCollector) ReplicationRequests() (requests []*directory.DirectoryEventReplicationRequest)
- func (ec *EventCollector) ReplicationResponses() (responses []*directory.DirectoryEventReplicationResponse)
- func (ec *EventCollector) TrustActs() (acts []*directory.TrustAct)
- type IdentityResolver
- func (r *IdentityResolver) ClearCache()
- func (r *IdentityResolver) FilterEventsByIdentity(events []*event.E, identity string) (filtered []*event.E)
- func (r *IdentityResolver) GetDelegatesForIdentity(identity string) (delegates []string)
- func (r *IdentityResolver) GetIdentityTag(delegate string) (*directory.IdentityTag, error)
- func (r *IdentityResolver) GetPublicKeyAdvertisementByID(keyID string) (*directory.PublicKeyAdvertisement, error)
- func (r *IdentityResolver) GetPublicKeyAdvertisements(identity string) (ads []*directory.PublicKeyAdvertisement)
- func (r *IdentityResolver) GetStats() Stats
- func (r *IdentityResolver) IsDelegateKey(pubkey string) bool
- func (r *IdentityResolver) IsIdentityKey(pubkey string) bool
- func (r *IdentityResolver) ProcessEvent(ev *event.E)
- func (r *IdentityResolver) ResolveEventIdentity(ev *event.E) string
- func (r *IdentityResolver) ResolveIdentity(pubkey string) string
- type ReplicationFilter
- func (rf *ReplicationFilter) AddTrustAct(act *directory.TrustAct)
- func (rf *ReplicationFilter) FilterEvents(events []*event.E) []*event.E
- func (rf *ReplicationFilter) GetMinTrustScore() float64
- func (rf *ReplicationFilter) GetTrustScore(pubkey string) float64
- func (rf *ReplicationFilter) GetTrustedRelays() []string
- func (rf *ReplicationFilter) SetMinTrustScore(minScore float64)
- func (rf *ReplicationFilter) ShouldReplicate(pubkey string) bool
- type Stats
- type TrustCalculator
- func (tc *TrustCalculator) AddAct(act *directory.TrustAct)
- func (tc *TrustCalculator) CalculateTrust(pubkey string) float64
- func (tc *TrustCalculator) Clear()
- func (tc *TrustCalculator) GetActiveTrustActs(pubkey string) []*directory.TrustAct
- func (tc *TrustCalculator) GetActs(pubkey string) []*directory.TrustAct
- func (tc *TrustCalculator) GetAllPubkeys() []string
- type TrustGraph
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FilterDirectoryEvents ¶
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 ¶
FindTrustActsForRelay finds all trust acts targeting a specific relay.
func IsDirectoryEvent ¶
IsDirectoryEvent checks if an event is a directory consensus event.
func NormalizeRelayURL ¶
NormalizeRelayURL ensures a relay URL has the canonical format with trailing slash.
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