- Introduced a TypeScript client library for the Distributed Directory Consensus Protocol (NIP-XX), providing a high-level API for managing directory events, identity resolution, and trust calculations. - Implemented core functionalities including event parsing, trust score aggregation, and replication filtering, mirroring the Go implementation. - Added comprehensive documentation and development guides for ease of use and integration. - Updated the `.gitignore` to include additional dependencies and build artifacts for the TypeScript client. - Enhanced validation mechanisms for group tag names and trust levels, ensuring robust input handling and security. - Created a new `bun.lock` file to manage package dependencies effectively.
8.2 KiB
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 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 statistics
TrustCalculator
Computes 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 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 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 events
EventCollector
Utility 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 responses
Helper Functions
Event 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 event
Event 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 group
URL Utilities:
NormalizeRelayURL(url string) string- Ensure trailing slash
Trust 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 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
Related Documentation
License
See LICENSE file.