High-level Go client library for the Distributed Directory Consensus Protocol (NIP-XX).
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.
import "next.orly.dev/pkg/protocol/directory-client"
// 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)
// 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)
// 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)
// 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")
// 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)
Manages identity resolution and key delegation tracking.
Methods:
NewIdentityResolver() *IdentityResolver - Create new instanceProcessEvent(ev *event.E) - Process event to extract identity infoResolveIdentity(pubkey string) string - Resolve delegate to identityResolveEventIdentity(ev *event.E) string - Resolve event's identityIsDelegateKey(pubkey string) bool - Check if key is a delegateIsIdentityKey(pubkey string) bool - Check if key has delegatesGetDelegatesForIdentity(identity string) []string - Get all delegatesGetIdentityTag(delegate string) (*IdentityTag, error) - Get identity tagGetPublicKeyAdvertisements(identity string) []*PublicKeyAdvertisement - Get key adsFilterEventsByIdentity(events []*event.E, identity string) []*event.E - Filter eventsClearCache() - Clear all cached mappingsGetStats() Stats - Get statisticsComputes aggregate trust scores from multiple trust acts.
Methods:
NewTrustCalculator() *TrustCalculator - Create new instanceAddAct(act *TrustAct) - Add a trust actCalculateTrust(pubkey string) float64 - Calculate trust score (0-100)GetActs(pubkey string) []*TrustAct - Get all acts for pubkeyGetActiveTrustActs(pubkey string) []*TrustAct - Get non-expired actsClear() - Remove all actsGetAllPubkeys() []string - Get all tracked pubkeysTrust Score Weights:
Manages replication decisions based on trust scores.
Methods:
NewReplicationFilter(minTrustScore float64) *ReplicationFilter - Create new instanceAddTrustAct(act *TrustAct) - Add trust act and update trusted relaysShouldReplicate(pubkey string) bool - Check if relay is trustedGetTrustedRelays() []string - Get all trusted relay pubkeysGetTrustScore(pubkey string) float64 - Get trust score for relaySetMinTrustScore(minScore float64) - Update thresholdGetMinTrustScore() float64 - Get current thresholdFilterEvents(events []*event.E) []*event.E - Filter to trusted eventsUtility for collecting specific types of directory events.
Methods:
NewEventCollector(events []*event.E) *EventCollector - Create new instanceRelayIdentities() []*RelayIdentity - Get all relay identitiesTrustActs() []*TrustAct - Get all trust actsGroupTagActs() []*GroupTagAct - Get all group tag actsPublicKeyAdvertisements() []*PublicKeyAdvertisement - Get all key adsReplicationRequests() []*ReplicationRequest - Get all requestsReplicationResponses() []*ReplicationResponse - Get all responsesEvent Filtering:
IsDirectoryEvent(ev *event.E) bool - Check if event is directory eventFilterDirectoryEvents(events []*event.E) []*event.E - Filter to directory eventsParseDirectoryEvent(ev *event.E) (interface{}, error) - Parse any directory eventEvent Finding:
FindRelayIdentity(events, relayURL) (*RelayIdentity, bool) - Find identity by URLFindTrustActsForRelay(events, targetPubkey) []*TrustAct - Find trust actsFindGroupTagActsForRelay(events, targetPubkey) []*GroupTagAct - Find group actsFindGroupTagActsByGroup(events, groupTag) []*GroupTagAct - Find by groupURL Utilities:
NormalizeRelayURL(url string) string - Ensure trailing slashTrust Graph:
NewTrustGraph() *TrustGraph - Create new graphBuildTrustGraph(events []*event.E) *TrustGraph - Build from eventsAddTrustAct(act *TrustAct) - Add trust act to graphGetTrustActs(source string) []*TrustAct - Get acts from sourceGetTrustedBy(target string) []string - Get who trusts targetGetTrustTargets(source string) []string - Get who source trustsAll components are thread-safe and can be used concurrently from multiple goroutines. Internal state is protected by read-write mutexes (sync.RWMutex).
ClearCache() if neededThis package works with:
The directory-client package includes comprehensive tests to ensure reliability and correctness:
# Run directory-client tests
go test ./pkg/protocol/directory-client
# Run all tests including directory-client
go test ./...
# Run with verbose output
go test -v ./pkg/protocol/directory-client
# Run with race detection
go test -race ./pkg/protocol/directory-client
# Run with coverage
go test -cover ./pkg/protocol/directory-client
The directory-client is tested as part of the project's integration test suite:
# Run the full test suite
./scripts/test.sh
# Run specific package tests
go test ./pkg/protocol/...
The test suite covers:
# Test identity resolution functionality
go test -v ./pkg/protocol/directory-client -run TestIdentityResolver
# Test trust calculation
go test -v ./pkg/protocol/directory-client -run TestTrustCalculator
# Test thread safety
go test -race -v ./pkg/protocol/directory-client
# Build the directory-client package
go build ./pkg/protocol/directory-client
# Run example usage
go run -tags=example ./pkg/protocol/directory-client
The directory-client follows Go best practices:
When adding new functionality:
See LICENSE file.