directory

package
v0.27.9 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2025 License: Unlicense Imports: 19 Imported by: 0

Documentation

Overview

Package directory implements the distributed directory consensus protocol as defined in NIP-XX for Nostr relay operators.

Overview

This package provides complete message encoding, validation, and helper functions for implementing the distributed directory consensus protocol. The protocol enables Nostr relay operators to form trusted consortiums that automatically synchronize essential identity-related events while maintaining decentralization and Byzantine fault tolerance.

Event Kinds

The protocol defines six new event kinds:

  • 39100: Relay Identity Announcement - Announces relay participation
  • 39101: Trust Act - Creates trust relationships between relays
  • 39102: Group Tag Act - Attests to arbitrary string values
  • 39103: Public Key Advertisement - Advertises HD-derived keys
  • 39104: Directory Event Replication Request - Requests event replication
  • 39105: Directory Event Replication Response - Responds to replication requests

Directory Events

The following existing event kinds are considered "directory events" and are automatically replicated among consortium members:

  • Kind 0: User Metadata
  • Kind 3: Follow Lists
  • Kind 5: Event Deletion Requests
  • Kind 1984: Reporting
  • Kind 10002: Relay List Metadata
  • Kind 10000: Mute Lists
  • Kind 10050: DM Relay Lists

Basic Usage

## Creating a Relay Identity Announcement

pubkey := []byte{...} // 32-byte relay identity key
announcement, err := directory.NewRelayIdentityAnnouncement(
	pubkey,
	"relay.example.com",           // name
	"A community relay",           // description
	"admin@example.com",           // contact
	"wss://relay.example.com",     // relay URL
	"abc123...",                   // signing key (hex)
	"def456...",                   // encryption key (hex)
	"1",                           // version
	"https://relay.example.com/.well-known/nostr.json", // NIP-11 URL
)
if err != nil {
	log.Fatal(err)
}

## Creating a Trust Act

act, err := directory.NewTrustAct(
	pubkey,
	"target_relay_pubkey_hex",     // target relay
	directory.TrustLevelHigh,      // trust level
	"wss://target.relay.com",      // target URL
	nil,                           // no expiry
	directory.TrustReasonManual,   // manual trust
	[]uint16{1, 6, 7},            // additional kinds to replicate
	nil,                           // no identity tag
)

## Creating a Public Key Advertisement

validFrom := time.Now()
validUntil := validFrom.Add(30 * 24 * time.Hour) // 30 days

keyAd, err := directory.NewPublicKeyAdvertisement(
	pubkey,
	"signing-key-001",                    // key ID
	"fedcba9876543210...",               // public key (hex)
	directory.KeyPurposeSigning,         // purpose
	validFrom,                           // valid from
	validUntil,                          // valid until
	"secp256k1",                         // algorithm
	"m/39103'/1237'/0'/0/1",            // derivation path
	1,                                   // key index
	nil,                                 // no identity tag
)

Identity Tags

Identity tags (I tags) provide npub-encoded identities with proof-of-control signatures. They bind an identity to a specific delegate key, preventing unauthorized use.

## Creating Identity Tags

// Create identity tag builder with private key
identityPrivkey := []byte{...} // 32-byte private key
builder, err := directory.NewIdentityTagBuilder(identityPrivkey)
if err != nil {
	log.Fatal(err)
}

// Create signed identity tag for delegate key
delegatePubkey := []byte{...} // 32-byte delegate public key
identityTag, err := builder.CreateIdentityTag(delegatePubkey)
if err != nil {
	log.Fatal(err)
}

// Use in trust act
act, err := directory.NewTrustAct(
	pubkey,
	"target_relay_pubkey_hex",
	directory.TrustLevelHigh,
	"wss://target.relay.com",
	nil,
	directory.TrustReasonManual,
	[]uint16{1, 6, 7},
	identityTag, // Include identity tag
)

Validation

All message types include comprehensive validation:

// Validate a parsed event
if err := announcement.Validate(); err != nil {
	log.Printf("Invalid announcement: %v", err)
	return
}

// Validate any consortium event
if err := directory.ValidateConsortiumEvent(event); err != nil {
	log.Printf("Invalid consortium event: %v", err)
	return
}

// Verify NIP-11 binding
valid, err := directory.ValidateRelayIdentityBinding(
	announcement,
	nip11Pubkey,
	nip11Nonce,
	nip11Sig,
	relayAddress,
)
if err != nil || !valid {
	log.Printf("Invalid relay identity binding")
	return
}

Trust Calculation

The package provides utilities for calculating trust relationships:

// Create trust calculator
calculator := directory.NewTrustCalculator()

// Add trust acts
calculator.AddAct(act1)
calculator.AddAct(act2)

// Get direct trust level
level := calculator.GetTrustLevel("relay_pubkey_hex")

// Calculate inherited trust
inheritedLevel := calculator.CalculateInheritedTrust(
	"from_relay_pubkey",
	"to_relay_pubkey",
)

Replication Filtering

Determine which events should be replicated to which relays:

// Create replication filter
filter := directory.NewReplicationFilter(calculator)
filter.AddTrustAct(act)

// Check if event should be replicated
shouldReplicate := filter.ShouldReplicate(event, "target_relay_pubkey")

// Get all replication targets for an event
targets := filter.GetReplicationTargets(event)

Event Batching

Batch events for efficient replication:

// Create event batcher
batcher := directory.NewEventBatcher(100) // max 100 events per batch

// Add events to batches
batcher.AddEvent("wss://relay1.com", event1)
batcher.AddEvent("wss://relay1.com", event2)
batcher.AddEvent("wss://relay2.com", event3)

// Check if batch is full
if batcher.IsBatchFull("wss://relay1.com") {
	batch := batcher.FlushBatch("wss://relay1.com")
	// Send batch for replication
}

Replication Requests and Responses

## Creating Replication Requests

requestID, err := directory.GenerateRequestID()
if err != nil {
	log.Fatal(err)
}

request, err := directory.NewDirectoryEventReplicationRequest(
	pubkey,
	requestID,
	"wss://target.relay.com",
	[]*event.E{event1, event2, event3},
)

## Creating Replication Responses

// Success response
results := []*directory.EventResult{
	directory.CreateEventResult("event_id_1", true, ""),
	directory.CreateEventResult("event_id_2", false, "duplicate event"),
}

response, err := directory.CreateSuccessResponse(
	pubkey,
	requestID,
	"wss://source.relay.com",
	results,
)

// Error response
errorResponse, err := directory.CreateErrorResponse(
	pubkey,
	requestID,
	"wss://source.relay.com",
	"relay temporarily unavailable",
)

Key Management

The protocol uses BIP32 HD key derivation for deterministic key generation:

// Create key pool manager
masterSeed := []byte{...} // BIP39 seed
manager := directory.NewKeyPoolManager(masterSeed, 0) // identity index 0

// Generate derivation paths
signingPath := manager.GenerateDerivationPath(directory.KeyPurposeSigning, 5)
// Returns: "m/39103'/1237'/0'/0/5"

encryptionPath := manager.GenerateDerivationPath(directory.KeyPurposeEncryption, 3)
// Returns: "m/39103'/1237'/0'/1/3"

// Track key usage
nextIndex := manager.GetNextKeyIndex(directory.KeyPurposeSigning)
manager.SetKeyIndex(directory.KeyPurposeSigning, 10) // Skip to index 10

Error Handling

All functions return detailed errors using the errorf package:

announcement, err := directory.ParseRelayIdentityAnnouncement(event)
if err != nil {
	// Handle specific error types
	switch {
	case strings.Contains(err.Error(), "invalid event kind"):
		log.Printf("Wrong event kind: %v", err)
	case strings.Contains(err.Error(), "missing"):
		log.Printf("Missing required field: %v", err)
	default:
		log.Printf("Parse error: %v", err)
	}
	return
}

Security Considerations

The package implements several security measures:

  • All events must have valid signatures
  • Identity tags prevent unauthorized identity use
  • NIP-11 binding prevents relay impersonation
  • Timestamp validation prevents replay attacks
  • Content size limits prevent DoS attacks
  • Nonce validation ensures cryptographic security

Protocol Constants

Important protocol constants:

  • MaxKeyDelegations: 512 unused key delegations per identity
  • KeyExpirationDays: 30 days for unused key delegations
  • MinNonceSize: 16 bytes minimum for nonces
  • MaxContentLength: 65536 bytes maximum for event content

Integration Example

Complete example of implementing consortium membership:

package main

import (
	"log"
	"time"

	"next.orly.dev/pkg/protocol/directory"
)

func main() {
	// Generate relay identity key
	relayPrivkey := []byte{...} // 32 bytes
	relayPubkey := schnorr.PubkeyFromSeckey(relayPrivkey)

	// Create relay identity announcement
	announcement, err := directory.NewRelayIdentityAnnouncement(
		relayPubkey,
		"my-relay.com",
		"My Community Relay",
		"admin@my-relay.com",
		"wss://my-relay.com",
		hex.EncodeToString(signingPubkey),
		hex.EncodeToString(encryptionPubkey),
		"1",
		"https://my-relay.com/.well-known/nostr.json",
	)
	if err != nil {
		log.Fatal(err)
	}

	// Sign and publish announcement
	if err := announcement.Event.Sign(relayPrivkey); err != nil {
		log.Fatal(err)
	}

	// Create trust act for another relay
	act, err := directory.NewTrustAct(
		relayPubkey,
		"trusted_relay_pubkey_hex",
		directory.TrustLevelHigh,
		"wss://trusted-relay.com",
		nil, // no expiry
		directory.TrustReasonManual,
		[]uint16{1, 6, 7}, // replicate text notes, reposts, reactions
		nil, // no identity tag
	)
	if err != nil {
		log.Fatal(err)
	}

	// Sign and publish act
	if err := act.Event.Sign(relayPrivkey); err != nil {
		log.Fatal(err)
	}

	// Set up replication filter
	calculator := directory.NewTrustCalculator()
	calculator.AddAct(act)

	filter := directory.NewReplicationFilter(calculator)
	filter.AddTrustAct(act)

	// When receiving events, check if they should be replicated
	for event := range eventChannel {
		targets := filter.GetReplicationTargets(event)
		for _, target := range targets {
			// Replicate event to target relay
			replicateEvent(event, target)
		}
	}
}

For more detailed examples and advanced usage patterns, see the test files and the reference implementation in the main relay codebase.

Package directory provides data structures and validation for the distributed directory consensus protocol as defined in NIP-XX.

This package implements message encoding and validation for the following event kinds:

  • 39100: Relay Identity Announcement - Announces relay participation in consortium
  • 39101: Trust Act - Establishes trust relationships with numeric levels (0-100%)
  • 39102: Group Tag Act - Creates/manages group tags with ownership specs
  • 39103: Public Key Advertisement - Advertises delegate keys with expiration
  • 39104: Directory Event Replication Request - Requests event synchronization
  • 39105: Directory Event Replication Response - Responds to sync requests
  • 39106: Group Tag Transfer - Transfers group tag ownership (planned)
  • 39107: Escrow Witness Completion Act - Completes escrow transfers (planned)

Numeric Trust Levels

Trust levels are represented as numeric values from 0-100, indicating the percentage probability that any given event will be replicated. This implements partial replication via cryptographic random selection (dice-throw mechanism):

  • 100: Full replication - ALL events replicated (100% probability)
  • 75: High partial replication - 75% of events replicated on average
  • 50: Medium partial replication - 50% of events replicated on average
  • 25: Low partial replication - 25% of events replicated on average
  • 10: Minimal sampling - 10% of events replicated on average
  • 0: No replication - effectively disables replication

For each event, a cryptographically secure random number (0-100) is generated and compared to the trust level threshold. If the random number ≤ trust level, the event is replicated; otherwise it is discarded. This provides:

  • Proportional bandwidth/storage reduction
  • Probabilistic network coverage (events propagate via multiple paths)
  • Network resilience (different relays replicate different random subsets)
  • Tunable trade-offs between resources and completeness

Group Tag Ownership

Group Tag Acts (Kind 39102) establish ownership and control over arbitrary string tags, functioning as a first-come-first-served registration system akin to domain name registration. Features include:

  • Single signature or multisig ownership (2-of-3, 3-of-5)
  • URL-safe character validation (RFC 3986 compliance)
  • Ownership transfer capability (via Kind 39106)
  • Escrow-based transfer protocol (via Kind 39107)
  • Foundation for permissioned structured groups across multiple relays

The term "act" in this protocol draws from legal terminology, where an act represents a formal declaration or testimony that has legal significance. Similar to legal instruments such as:

  • Deed Poll: A legal document binding one party to a particular course of action
  • Witness Testimony: A formal statement given under oath as evidence
  • Affidavit: A written statement confirmed by oath for use as evidence

In the context of this protocol, acts serve as cryptographically signed declarations that establish trust relationships, group memberships, or other formal statements within the relay consortium. Like their legal counterparts, these acts:

  • Are formally structured with specific required elements
  • Carry the authority and responsibility of the signing party
  • Create binding relationships or obligations within the consortium
  • Can be verified for authenticity through cryptographic signatures
  • May have expiration dates or other temporal constraints

This legal framework provides a conceptual foundation for understanding the formal nature and binding character of consortium declarations.

Index

Constants

View Source
const (
	MaxKeyDelegations = 512
	KeyExpirationDays = 30
	MinNonceSize      = 16    // bytes
	MaxContentLength  = 65536 // bytes
)

Validation constants

Variables

View Source
var (
	RelayIdentityAnnouncementKind         = kind.New(39100)
	TrustActKind                          = kind.New(39101)
	GroupTagActKind                       = kind.New(39102)
	PublicKeyAdvertisementKind            = kind.New(39103)
	DirectoryEventReplicationRequestKind  = kind.New(39104)
	DirectoryEventReplicationResponseKind = kind.New(39105)
	GroupTagTransferKind                  = kind.New(39106)
	EscrowWitnessCompletionActKind        = kind.New(39107)
)

Event kinds for the distributed directory consensus protocol

View Source
var (
	DTag                = []byte("d")                 // Unique identifier for replaceable events
	RelayTag            = []byte("relay")             // WebSocket URL of a relay
	SigningKeyTag       = []byte("signing_key")       // Public key for signature verification
	EncryptionKeyTag    = []byte("encryption_key")    // Public key for ECDH encryption
	VersionTag          = []byte("version")           // Protocol version number
	NIP11URLTag         = []byte("nip11_url")         // Deprecated: Use HTTP GET with Accept header instead
	PubkeyTag           = []byte("p")                 // Public key reference
	TrustLevelTag       = []byte("trust_level")       // Numeric trust level (0-100)
	ExpiryTag           = []byte("expiry")            // Unix timestamp for expiration
	ReasonTag           = []byte("reason")            // Reason for trust establishment
	KTag                = []byte("K")                 // Comma-separated event kinds for replication
	ITag                = []byte("I")                 // Identity tag with proof-of-control
	GroupTagTag         = []byte("group_tag")         // Group identifier and metadata
	ActorTag            = []byte("actor")             // Public key of the actor
	ConfidenceTag       = []byte("confidence")        // Confidence score (0-100)
	OwnersTag           = []byte("owners")            // Ownership specification (scheme + pubkeys)
	CreatedTag          = []byte("created")           // Creation/registration timestamp
	FromOwnersTag       = []byte("from_owners")       // Previous owners in transfer
	ToOwnersTag         = []byte("to_owners")         // New owners in transfer
	TransferDateTag     = []byte("transfer_date")     // Transfer effective date
	SignaturesTag       = []byte("signatures")        // Multisig signatures for transfers
	EscrowIDTag         = []byte("escrow_id")         // Unique escrow identifier
	SellerWitnessTag    = []byte("seller_witness")    // Seller's witness public key
	BuyerWitnessTag     = []byte("buyer_witness")     // Buyer's witness public key
	ConditionsTag       = []byte("conditions")        // Escrow conditions/requirements
	WitnessRoleTag      = []byte("witness_role")      // Role of witness (seller/buyer)
	CompletionStatusTag = []byte("completion_status") // Escrow completion status
	VerificationHashTag = []byte("verification_hash") // Hash for verification
	TimestampTag        = []byte("timestamp")         // General purpose timestamp
	PurposeTag          = []byte("purpose")           // Key purpose (signing/encryption/delegation)
	AlgorithmTag        = []byte("algorithm")         // Cryptographic algorithm identifier
	DerivationPathTag   = []byte("derivation_path")   // BIP32 derivation path
	KeyIndexTag         = []byte("key_index")         // Key index in derivation chain
	RequestIDTag        = []byte("request_id")        // Unique request identifier
	EventIDTag          = []byte("event_id")          // Event ID reference
	StatusTag           = []byte("status")            // Status code (success/error/pending)
	ErrorTag            = []byte("error")             // Error message
)

Common tag names used across directory protocol messages. These tags are used to structure and encode protocol messages within Nostr events.

Functions

func CreateBaseEvent

func CreateBaseEvent(pubkey []byte, k *kind.K) (ev *event.E)

CreateBaseEvent creates a basic event structure with common fields set. This is used as a starting point for constructing protocol messages. The event still needs tags, content, and signature to be complete.

func FormatKindsList

func FormatKindsList(kinds []uint16) string

FormatKindsList formats a list of event kinds as a comma-separated string.

func GenerateNonce

func GenerateNonce(size int) (nonce []byte, err error)

GenerateNonce creates a cryptographically secure random nonce for use in identity tags and other protocol messages.

func GenerateNonceHex

func GenerateNonceHex(size int) (nonceHex string, err error)

GenerateNonceHex creates a hex-encoded nonce of the specified byte size.

func GenerateRequestID

func GenerateRequestID() (requestID string, err error)

GenerateRequestID generates a unique request ID for replication requests.

func IsConsortiumEvent

func IsConsortiumEvent(ev *event.E) bool

IsConsortiumEvent returns true if the event is a consortium protocol event.

func IsDirectoryEventKind

func IsDirectoryEventKind(k uint16) (isDirectory bool)

IsDirectoryEventKind returns true if the given kind is a directory event that should always be replicated among consortium members, regardless of the trust level's partial replication setting.

Standard Nostr directory events (always replicated):

  • Kind 0: User Metadata (profiles)
  • Kind 3: Follow Lists (contact lists)
  • Kind 5: Event Deletion Requests
  • Kind 1984: Reporting (spam, abuse reports)
  • Kind 10002: Relay List Metadata
  • Kind 10000: Mute Lists
  • Kind 10050: DM Relay Lists

Protocol-specific directory events (always replicated):

  • Kind 39100: Relay Identity Announcements
  • Kind 39101: Trust Acts
  • Kind 39102: Group Tag Acts
  • Kind 39103: Public Key Advertisements
  • Kind 39104: Directory Event Replication Requests
  • Kind 39105: Directory Event Replication Responses
  • Kind 39106: Group Tag Transfers
  • Kind 39107: Escrow Witness Completion Acts

func ParseKindsList

func ParseKindsList(kindsStr string) (kinds []uint16, err error)

ParseKindsList parses a comma-separated list of event kinds.

func ValidateConsortiumEvent

func ValidateConsortiumEvent(ev *event.E) (err error)

ValidateConsortiumEvent performs comprehensive validation of any consortium protocol event, including signature verification and protocol-specific checks.

func ValidateDerivationPath

func ValidateDerivationPath(path string) (err error)

ValidateDerivationPath validates a BIP32 derivation path for this protocol.

func ValidateEventContent

func ValidateEventContent(content []byte) (err error)

ValidateEventContent validates that event content is within size limits.

func ValidateEventKindForReplication

func ValidateEventKindForReplication(kind uint16) (err error)

ValidateEventKindForReplication validates that an event kind is appropriate for replication in the directory consensus protocol.

func ValidateGroupTagName

func ValidateGroupTagName(name string) (err error)

ValidateGroupTagName validates that a group tag name is URL-safe (RFC 3986).

func ValidateHexKey

func ValidateHexKey(key string) (err error)

ValidateHexKey validates that a string is a valid 64-character hex key.

func ValidateKeyPurpose

func ValidateKeyPurpose(purpose string) (err error)

ValidateKeyPurpose checks if the provided key purpose is valid. Valid purposes are: signing, encryption, delegation.

func ValidateNPub

func ValidateNPub(npub string) (err error)

ValidateNPub validates that a string is a valid npub-encoded public key.

func ValidateNonce

func ValidateNonce(nonce string) (err error)

ValidateNonce validates that a nonce meets minimum security requirements.

func ValidateRelayIdentityBinding

func ValidateRelayIdentityBinding(
	announcement *RelayIdentityAnnouncement,
	nip11Pubkey, nip11Nonce, nip11Sig, relayAddress string,
) (valid bool, err error)

ValidateRelayIdentityBinding verifies that a relay identity announcement is properly bound to its network address through NIP-11 signature verification.

func ValidateReplicationStatus

func ValidateReplicationStatus(status string) (err error)

ValidateReplicationStatus checks if the provided replication status is valid. Valid statuses are: success, error, pending.

func ValidateSignature

func ValidateSignature(sig string) (err error)

ValidateSignature validates that a signature is properly formatted.

func ValidateSignatureScheme

func ValidateSignatureScheme(scheme SignatureScheme) error

ValidateSignatureScheme checks if a signature scheme is valid.

func ValidateTimestamp

func ValidateTimestamp(ts int64) (err error)

ValidateTimestamp validates that a timestamp is reasonable (not too far in past/future).

func ValidateTrustLevel

func ValidateTrustLevel(level TrustLevel) (err error)

ValidateTrustLevel checks if the provided trust level is valid (0-100). Returns an error if the level exceeds 100.

func ValidateWebSocketURL

func ValidateWebSocketURL(wsURL string) (err error)

ValidateWebSocketURL validates that a string is a valid WebSocket URL.

func VerifyIdentityTagSignature

func VerifyIdentityTagSignature(
	identityTag *IdentityTag,
	delegatePubkey []byte,
) (valid bool, err error)

VerifyIdentityTagSignature verifies the signature in an identity tag.

Types

type DirectoryEventReplicationRequest

type DirectoryEventReplicationRequest struct {
	Event       *event.E
	Content     *ReplicationRequestContent
	RequestID   string
	TargetRelay string
}

DirectoryEventReplicationRequest represents a complete Directory Event Replication Request event (Kind 39104) with typed access to its components.

func NewDirectoryEventReplicationRequest

func NewDirectoryEventReplicationRequest(
	pubkey []byte,
	requestID, targetRelay string,
	events []*event.E,
) (derr *DirectoryEventReplicationRequest, err error)

NewDirectoryEventReplicationRequest creates a new Directory Event Replication Request event.

func ParseDirectoryEventReplicationRequest

func ParseDirectoryEventReplicationRequest(ev *event.E) (derr *DirectoryEventReplicationRequest, err error)

ParseDirectoryEventReplicationRequest parses an event into a DirectoryEventReplicationRequest structure with validation.

func (*DirectoryEventReplicationRequest) ContainsEventKind

func (derr *DirectoryEventReplicationRequest) ContainsEventKind(kind uint16) bool

ContainsEventKind returns true if the request contains events of the specified kind.

func (*DirectoryEventReplicationRequest) GetDirectoryEvents

func (derr *DirectoryEventReplicationRequest) GetDirectoryEvents() []*event.E

GetDirectoryEvents returns only the directory events from the request.

func (*DirectoryEventReplicationRequest) GetEventByIndex

func (derr *DirectoryEventReplicationRequest) GetEventByIndex(index int) *event.E

GetEventByIndex returns the event at the specified index, or nil if out of bounds.

func (*DirectoryEventReplicationRequest) GetEventCount

func (derr *DirectoryEventReplicationRequest) GetEventCount() int

GetEventCount returns the number of events in the request.

func (*DirectoryEventReplicationRequest) GetEvents

func (derr *DirectoryEventReplicationRequest) GetEvents() []*event.E

GetEvents returns the list of events to replicate.

func (*DirectoryEventReplicationRequest) GetEventsByAuthor

func (derr *DirectoryEventReplicationRequest) GetEventsByAuthor(pubkey []byte) []*event.E

GetEventsByAuthor returns all events from the specified author.

func (*DirectoryEventReplicationRequest) GetEventsByKind

func (derr *DirectoryEventReplicationRequest) GetEventsByKind(kind uint16) []*event.E

GetEventsByKind returns all events of the specified kind.

func (*DirectoryEventReplicationRequest) GetNonDirectoryEvents

func (derr *DirectoryEventReplicationRequest) GetNonDirectoryEvents() []*event.E

GetNonDirectoryEvents returns only the non-directory events from the request.

func (*DirectoryEventReplicationRequest) GetRequestID

func (derr *DirectoryEventReplicationRequest) GetRequestID() string

GetRequestID returns the unique request identifier.

func (*DirectoryEventReplicationRequest) GetTargetRelay

func (derr *DirectoryEventReplicationRequest) GetTargetRelay() string

GetTargetRelay returns the target relay URL.

func (*DirectoryEventReplicationRequest) HasEvents

func (derr *DirectoryEventReplicationRequest) HasEvents() bool

HasEvents returns true if the request contains events.

func (*DirectoryEventReplicationRequest) Validate

func (derr *DirectoryEventReplicationRequest) Validate() (err error)

Validate performs comprehensive validation of a DirectoryEventReplicationRequest.

type DirectoryEventReplicationResponse

type DirectoryEventReplicationResponse struct {
	Event       *event.E
	Content     *ReplicationResponseContent
	RequestID   string
	Status      ReplicationStatus
	ErrorMsg    string
	SourceRelay string
}

DirectoryEventReplicationResponse represents a complete Directory Event Replication Response event (Kind 39105) with typed access to its components.

func CreateErrorResponse

func CreateErrorResponse(
	pubkey []byte,
	requestID, sourceRelay, errorMsg string,
) (response *DirectoryEventReplicationResponse, err error)

CreateErrorResponse creates an error replication response.

func CreateSuccessResponse

func CreateSuccessResponse(
	pubkey []byte,
	requestID, sourceRelay string,
	eventResults []*EventResult,
) (response *DirectoryEventReplicationResponse, err error)

CreateSuccessResponse creates a successful replication response.

func NewDirectoryEventReplicationResponse

func NewDirectoryEventReplicationResponse(
	pubkey []byte,
	requestID string,
	status ReplicationStatus,
	errorMsg, sourceRelay string,
	results []*EventResult,
) (derr *DirectoryEventReplicationResponse, err error)

NewDirectoryEventReplicationResponse creates a new Directory Event Replication Response event.

func ParseDirectoryEventReplicationResponse

func ParseDirectoryEventReplicationResponse(ev *event.E) (derr *DirectoryEventReplicationResponse, err error)

ParseDirectoryEventReplicationResponse parses an event into a DirectoryEventReplicationResponse structure with validation.

func (*DirectoryEventReplicationResponse) GetErrorMsg

func (derr *DirectoryEventReplicationResponse) GetErrorMsg() string

GetErrorMsg returns the error message, if any.

func (*DirectoryEventReplicationResponse) GetFailedResults

func (derr *DirectoryEventReplicationResponse) GetFailedResults() []*EventResult

GetFailedResults returns all results with error status.

func (*DirectoryEventReplicationResponse) GetFailureCount

func (derr *DirectoryEventReplicationResponse) GetFailureCount() int

GetFailureCount returns the number of failed event replications.

func (*DirectoryEventReplicationResponse) GetPendingCount

func (derr *DirectoryEventReplicationResponse) GetPendingCount() int

GetPendingCount returns the number of pending event replications.

func (*DirectoryEventReplicationResponse) GetPendingResults

func (derr *DirectoryEventReplicationResponse) GetPendingResults() []*EventResult

GetPendingResults returns all results with pending status.

func (*DirectoryEventReplicationResponse) GetRequestID

func (derr *DirectoryEventReplicationResponse) GetRequestID() string

GetRequestID returns the request ID this response corresponds to.

func (*DirectoryEventReplicationResponse) GetResultByEventID

func (derr *DirectoryEventReplicationResponse) GetResultByEventID(eventID string) *EventResult

GetResultByEventID returns the result for a specific event ID, or nil if not found.

func (*DirectoryEventReplicationResponse) GetResultCount

func (derr *DirectoryEventReplicationResponse) GetResultCount() int

GetResultCount returns the number of event results.

func (*DirectoryEventReplicationResponse) GetResults

func (derr *DirectoryEventReplicationResponse) GetResults() []*EventResult

GetResults returns the list of individual event results.

func (*DirectoryEventReplicationResponse) GetSourceRelay

func (derr *DirectoryEventReplicationResponse) GetSourceRelay() string

GetSourceRelay returns the relay that sent this response.

func (*DirectoryEventReplicationResponse) GetStatus

GetStatus returns the overall replication status.

func (*DirectoryEventReplicationResponse) GetSuccessCount

func (derr *DirectoryEventReplicationResponse) GetSuccessCount() int

GetSuccessCount returns the number of successfully replicated events.

func (*DirectoryEventReplicationResponse) GetSuccessRate

func (derr *DirectoryEventReplicationResponse) GetSuccessRate() float64

GetSuccessRate returns the success rate as a percentage (0-100).

func (*DirectoryEventReplicationResponse) GetSuccessfulResults

func (derr *DirectoryEventReplicationResponse) GetSuccessfulResults() []*EventResult

GetSuccessfulResults returns all results with success status.

func (*DirectoryEventReplicationResponse) HasResults

func (derr *DirectoryEventReplicationResponse) HasResults() bool

HasResults returns true if the response contains event results.

func (*DirectoryEventReplicationResponse) IsError

func (derr *DirectoryEventReplicationResponse) IsError() bool

IsError returns true if the overall replication failed.

func (*DirectoryEventReplicationResponse) IsPending

func (derr *DirectoryEventReplicationResponse) IsPending() bool

IsPending returns true if the replication is still pending.

func (*DirectoryEventReplicationResponse) IsSuccess

func (derr *DirectoryEventReplicationResponse) IsSuccess() bool

IsSuccess returns true if the overall replication was successful.

func (*DirectoryEventReplicationResponse) Validate

func (derr *DirectoryEventReplicationResponse) Validate() (err error)

Validate performs comprehensive validation of a DirectoryEventReplicationResponse.

type EventBatcher

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

EventBatcher helps batch events for efficient replication.

func NewEventBatcher

func NewEventBatcher(maxBatchSize int) *EventBatcher

NewEventBatcher creates a new event batcher.

func (*EventBatcher) AddEvent

func (eb *EventBatcher) AddEvent(targetRelay string, ev *event.E)

AddEvent adds an event to the batch for a target relay.

func (*EventBatcher) FlushAllBatches

func (eb *EventBatcher) FlushAllBatches() map[string][]*event.E

FlushAllBatches returns and clears all batches.

func (*EventBatcher) FlushBatch

func (eb *EventBatcher) FlushBatch(targetRelay string) []*event.E

FlushBatch returns and clears the batch for a target relay.

func (*EventBatcher) GetAllBatches

func (eb *EventBatcher) GetAllBatches() map[string][]*event.E

GetAllBatches returns all current batches.

func (*EventBatcher) GetBatch

func (eb *EventBatcher) GetBatch(targetRelay string) []*event.E

GetBatch returns the current batch for a target relay.

func (*EventBatcher) IsBatchFull

func (eb *EventBatcher) IsBatchFull(targetRelay string) bool

IsBatchFull returns true if the batch for a target relay is full.

type EventResult

type EventResult struct {
	EventID string            `json:"event_id"`
	Status  ReplicationStatus `json:"status"`
	Error   string            `json:"error,omitempty"`
}

EventResult represents the result of processing a single event in a replication request.

func CreateEventResult

func CreateEventResult(eventID string, success bool, errorMsg string) *EventResult

CreateEventResult creates an event result for a replication response.

func NewEventResult

func NewEventResult(eventID string, status ReplicationStatus, errorMsg string) *EventResult

NewEventResult creates a new EventResult.

func (*EventResult) HasError

func (er *EventResult) HasError() bool

HasError returns true if this event result has an error message.

func (*EventResult) IsError

func (er *EventResult) IsError() bool

IsError returns true if this event result failed.

func (*EventResult) IsPending

func (er *EventResult) IsPending() bool

IsPending returns true if this event result is pending.

func (*EventResult) IsSuccess

func (er *EventResult) IsSuccess() bool

IsSuccess returns true if this event result was successful.

type GroupTagAct

type GroupTagAct struct {
	Event       *event.E
	GroupID     string
	TagName     string
	TagValue    string
	Actor       string
	Confidence  int
	Owners      *OwnershipSpec
	Created     *time.Time
	Description string
	IdentityTag *IdentityTag
}

GroupTagAct represents a complete Group Tag Act event (Kind 39102) with typed access to its components.

func NewGroupTagAct

func NewGroupTagAct(
	pubkey []byte,
	groupID, tagName, tagValue, actor string,
	confidence int,
	owners *OwnershipSpec,
	description string,
	identityTag *IdentityTag,
) (gta *GroupTagAct, err error)

NewGroupTagAct creates a new Group Tag Act event.

func ParseGroupTagAct

func ParseGroupTagAct(ev *event.E) (gta *GroupTagAct, err error)

ParseGroupTagAct parses an event into a GroupTagAct structure with validation.

func (*GroupTagAct) GetActor

func (gta *GroupTagAct) GetActor() string

GetActor returns the public key of the relay making the act.

func (*GroupTagAct) GetConfidence

func (gta *GroupTagAct) GetConfidence() int

GetConfidence returns the confidence level (0-100) in this act.

func (*GroupTagAct) GetDescription

func (gta *GroupTagAct) GetDescription() string

GetDescription returns the optional description of the act.

func (*GroupTagAct) GetGroupID

func (gta *GroupTagAct) GetGroupID() string

GetGroupID returns the group identifier.

func (*GroupTagAct) GetTagName

func (gta *GroupTagAct) GetTagName() string

GetTagName returns the tag name being attested.

func (*GroupTagAct) GetTagValue

func (gta *GroupTagAct) GetTagValue() string

GetTagValue returns the tag value being attested.

func (*GroupTagAct) IsAttestedBy

func (gta *GroupTagAct) IsAttestedBy(actor string) bool

IsAttestedBy returns true if this act was made by the given actor.

func (*GroupTagAct) IsHighConfidence

func (gta *GroupTagAct) IsHighConfidence() bool

IsHighConfidence returns true if the confidence level is 80 or higher.

func (*GroupTagAct) IsLowConfidence

func (gta *GroupTagAct) IsLowConfidence() bool

IsLowConfidence returns true if the confidence level is below 50.

func (*GroupTagAct) IsMediumConfidence

func (gta *GroupTagAct) IsMediumConfidence() bool

IsMediumConfidence returns true if the confidence level is between 50 and 79.

func (*GroupTagAct) MatchesGroup

func (gta *GroupTagAct) MatchesGroup(groupID string) bool

MatchesGroup returns true if this act belongs to the given group.

func (*GroupTagAct) MatchesTag

func (gta *GroupTagAct) MatchesTag(name, value string) bool

MatchesTag returns true if this act matches the given tag name and value.

func (*GroupTagAct) Validate

func (gta *GroupTagAct) Validate() (err error)

Validate performs comprehensive validation of a GroupTagAct.

type IdentityTag

type IdentityTag struct {
	NPubIdentity string
	Nonce        string
	Signature    string
}

IdentityTag represents the I tag with npub identity and proof-of-control.

func ParseIdentityTag

func ParseIdentityTag(t *tag.T) (it *IdentityTag, err error)

ParseIdentityTag parses an I tag into an IdentityTag structure.

func (*IdentityTag) Validate

func (it *IdentityTag) Validate() (err error)

Validate performs validation of an IdentityTag.

type IdentityTagBuilder

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

IdentityTagBuilder helps construct identity tags with proper signatures.

func NewIdentityTagBuilder

func NewIdentityTagBuilder(identityPrivkey []byte) (builder *IdentityTagBuilder, err error)

NewIdentityTagBuilder creates a new identity tag builder with the given identity private key.

func (*IdentityTagBuilder) CreateIdentityTag

func (builder *IdentityTagBuilder) CreateIdentityTag(delegatePubkey []byte) (identityTag *IdentityTag, err error)

CreateIdentityTag creates a signed identity tag for the given delegate pubkey.

func (*IdentityTagBuilder) GetIdentityPubkey

func (builder *IdentityTagBuilder) GetIdentityPubkey() []byte

GetIdentityPubkey returns the raw identity public key.

func (*IdentityTagBuilder) GetNPubIdentity

func (builder *IdentityTagBuilder) GetNPubIdentity() string

GetNPubIdentity returns the npub-encoded identity.

type KeyPoolManager

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

KeyPoolManager helps manage HD key derivation and advertisement.

func NewKeyPoolManager

func NewKeyPoolManager(masterSeed []byte, identityIndex uint32) *KeyPoolManager

NewKeyPoolManager creates a new key pool manager with the given master seed.

func (*KeyPoolManager) GenerateDerivationPath

func (kpm *KeyPoolManager) GenerateDerivationPath(purpose KeyPurpose, index int) string

GenerateDerivationPath creates a BIP32 derivation path for the given purpose and index.

func (*KeyPoolManager) GetCurrentKeyIndex

func (kpm *KeyPoolManager) GetCurrentKeyIndex(purpose KeyPurpose) int

GetCurrentKeyIndex returns the current key index for the given purpose.

func (*KeyPoolManager) GetNextKeyIndex

func (kpm *KeyPoolManager) GetNextKeyIndex(purpose KeyPurpose) int

GetNextKeyIndex returns the next available key index for the given purpose.

func (*KeyPoolManager) SetKeyIndex

func (kpm *KeyPoolManager) SetKeyIndex(purpose KeyPurpose, index int)

SetKeyIndex sets the current key index for the given purpose.

type KeyPurpose

type KeyPurpose string

KeyPurpose indicates the intended use of an advertised public key. This allows proper key separation and reduces security risks.

const (
	KeyPurposeSigning    KeyPurpose = "signing"    // For signing events (BIP-340 Schnorr)
	KeyPurposeEncryption KeyPurpose = "encryption" // For ECDH encryption (NIP-04, NIP-44)
	KeyPurposeDelegation KeyPurpose = "delegation" // For delegated event signing (NIP-26)
)

type OwnershipSpec

type OwnershipSpec struct {
	Scheme SignatureScheme
	Owners []string // Public keys of owners
}

OwnershipSpec defines the ownership control for a group tag.

type PublicKeyAdvertisement

type PublicKeyAdvertisement struct {
	Event          *event.E
	KeyID          string
	PublicKey      string
	Purpose        KeyPurpose
	Expiry         *time.Time
	Algorithm      string
	DerivationPath string
	KeyIndex       int
	IdentityTag    *IdentityTag
}

PublicKeyAdvertisement represents a complete Public Key Advertisement event (Kind 39103) with typed access to its components.

func NewPublicKeyAdvertisement

func NewPublicKeyAdvertisement(
	pubkey []byte,
	keyID, publicKey string,
	purpose KeyPurpose,
	expiry *time.Time,
	algorithm, derivationPath string,
	keyIndex int,
	identityTag *IdentityTag,
) (pka *PublicKeyAdvertisement, err error)

NewPublicKeyAdvertisement creates a new Public Key Advertisement event.

func ParsePublicKeyAdvertisement

func ParsePublicKeyAdvertisement(ev *event.E) (pka *PublicKeyAdvertisement, err error)

ParsePublicKeyAdvertisement parses an event into a PublicKeyAdvertisement structure with validation.

func (*PublicKeyAdvertisement) GetAlgorithm

func (pka *PublicKeyAdvertisement) GetAlgorithm() string

GetAlgorithm returns the cryptographic algorithm.

func (*PublicKeyAdvertisement) GetDerivationPath

func (pka *PublicKeyAdvertisement) GetDerivationPath() string

GetDerivationPath returns the BIP32 derivation path.

func (*PublicKeyAdvertisement) GetIdentityTag

func (pka *PublicKeyAdvertisement) GetIdentityTag() *IdentityTag

GetIdentityTag returns the identity tag, or nil if not present.

func (*PublicKeyAdvertisement) GetKeyID

func (pka *PublicKeyAdvertisement) GetKeyID() string

GetKeyID returns the unique key identifier.

func (*PublicKeyAdvertisement) GetKeyIndex

func (pka *PublicKeyAdvertisement) GetKeyIndex() int

GetKeyIndex returns the key index from the derivation path.

func (*PublicKeyAdvertisement) GetPublicKey

func (pka *PublicKeyAdvertisement) GetPublicKey() string

GetPublicKey returns the hex-encoded public key.

func (*PublicKeyAdvertisement) GetPurpose

func (pka *PublicKeyAdvertisement) GetPurpose() KeyPurpose

GetPurpose returns the key purpose.

func (*PublicKeyAdvertisement) HasPurpose

func (pka *PublicKeyAdvertisement) HasPurpose(purpose KeyPurpose) bool

HasPurpose returns true if the key has the specified purpose.

func (*PublicKeyAdvertisement) IsDelegationKey

func (pka *PublicKeyAdvertisement) IsDelegationKey() bool

IsDelegationKey returns true if this is a delegation key.

func (*PublicKeyAdvertisement) IsEncryptionKey

func (pka *PublicKeyAdvertisement) IsEncryptionKey() bool

IsEncryptionKey returns true if this is an encryption key.

func (*PublicKeyAdvertisement) IsExpired

func (pka *PublicKeyAdvertisement) IsExpired() bool

IsExpired returns true if the key has expired.

func (*PublicKeyAdvertisement) IsNotYetValid

func (pka *PublicKeyAdvertisement) IsNotYetValid() bool

IsNotYetValid returns true if the key is not yet valid.

func (*PublicKeyAdvertisement) IsSigningKey

func (pka *PublicKeyAdvertisement) IsSigningKey() bool

IsSigningKey returns true if this is a signing key.

func (*PublicKeyAdvertisement) IsValid

func (pka *PublicKeyAdvertisement) IsValid() bool

IsValid returns true if the key is currently valid (within its validity period).

func (*PublicKeyAdvertisement) TimeUntilExpiry

func (pka *PublicKeyAdvertisement) TimeUntilExpiry() time.Duration

TimeUntilExpiry returns the duration until the key expires. Returns 0 if already expired.

func (*PublicKeyAdvertisement) TimeUntilValid

func (pka *PublicKeyAdvertisement) TimeUntilValid() time.Duration

TimeUntilValid returns the duration until the key becomes valid. Returns 0 if already valid or expired.

func (*PublicKeyAdvertisement) Validate

func (pka *PublicKeyAdvertisement) Validate() (err error)

Validate performs comprehensive validation of a PublicKeyAdvertisement.

type RelayIdentityAnnouncement

type RelayIdentityAnnouncement struct {
	Event         *event.E
	Content       *RelayIdentityContent
	RelayURL      string
	SigningKey    string
	EncryptionKey string
	Version       string
}

RelayIdentityAnnouncement represents a complete Relay Identity Announcement event with typed access to its components.

func NewRelayIdentityAnnouncement

func NewRelayIdentityAnnouncement(
	pubkey []byte,
	name, description, contact string,
	relayURL, signingKey, encryptionKey, version string,
) (ria *RelayIdentityAnnouncement, err error)

NewRelayIdentityAnnouncement creates a new Relay Identity Announcement event.

func ParseRelayIdentityAnnouncement

func ParseRelayIdentityAnnouncement(ev *event.E) (ria *RelayIdentityAnnouncement, err error)

ParseRelayIdentityAnnouncement parses an event into a RelayIdentityAnnouncement structure with validation.

func (*RelayIdentityAnnouncement) GetContact

func (ria *RelayIdentityAnnouncement) GetContact() string

GetContact returns the relay contact information from the content.

func (*RelayIdentityAnnouncement) GetDescription

func (ria *RelayIdentityAnnouncement) GetDescription() string

GetDescription returns the relay description from the content.

func (*RelayIdentityAnnouncement) GetEncryptionKey

func (ria *RelayIdentityAnnouncement) GetEncryptionKey() string

GetEncryptionKey returns the hex-encoded encryption public key.

func (*RelayIdentityAnnouncement) GetName

func (ria *RelayIdentityAnnouncement) GetName() string

GetName returns the relay name from the content.

func (*RelayIdentityAnnouncement) GetRelayURL

func (ria *RelayIdentityAnnouncement) GetRelayURL() string

GetRelayURL returns the relay WebSocket URL.

func (*RelayIdentityAnnouncement) GetSigningKey

func (ria *RelayIdentityAnnouncement) GetSigningKey() string

GetSigningKey returns the hex-encoded signing public key.

func (*RelayIdentityAnnouncement) GetVersion

func (ria *RelayIdentityAnnouncement) GetVersion() string

GetVersion returns the protocol version.

func (*RelayIdentityAnnouncement) Validate

func (ria *RelayIdentityAnnouncement) Validate() (err error)

Validate performs comprehensive validation of a RelayIdentityAnnouncement.

type RelayIdentityContent

type RelayIdentityContent struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Contact     string `json:"contact,omitempty"`
}

RelayIdentityContent represents the JSON content of a Relay Identity Announcement event (Kind 39100).

type ReplicationFilter

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

ReplicationFilter helps determine which events should be replicated.

func NewReplicationFilter

func NewReplicationFilter(trustCalculator *TrustCalculator) *ReplicationFilter

NewReplicationFilter creates a new replication filter.

func (*ReplicationFilter) AddTrustAct

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

AddTrustAct adds a trust act to the filter.

func (*ReplicationFilter) GetReplicationTargets

func (rf *ReplicationFilter) GetReplicationTargets(ev *event.E) []string

GetReplicationTargets returns all target relays that should receive an event.

func (*ReplicationFilter) ShouldReplicate

func (rf *ReplicationFilter) ShouldReplicate(ev *event.E, targetPubkey string) bool

ShouldReplicate determines if an event should be replicated to a target relay.

type ReplicationRequestContent

type ReplicationRequestContent struct {
	Events []*event.E `json:"events"`
}

ReplicationRequestContent represents the JSON content of a Directory Event Replication Request event (Kind 39104).

type ReplicationResponseContent

type ReplicationResponseContent struct {
	RequestID string         `json:"request_id"`
	Results   []*EventResult `json:"results"`
}

ReplicationResponseContent represents the JSON content of a Directory Event Replication Response event (Kind 39105).

type ReplicationStatus

type ReplicationStatus string

ReplicationStatus indicates the outcome of a replication request.

const (
	ReplicationStatusSuccess ReplicationStatus = "success" // Replication completed successfully
	ReplicationStatusError   ReplicationStatus = "error"   // Replication failed with error
	ReplicationStatusPending ReplicationStatus = "pending" // Replication in progress
)

type SignatureScheme

type SignatureScheme string

SignatureScheme defines the type of signature requirement.

const (
	SchemeSingle SignatureScheme = "single"
	Scheme2of3   SignatureScheme = "2-of-3"
	Scheme3of5   SignatureScheme = "3-of-5"
)

func (SignatureScheme) RequiredSignatures

func (s SignatureScheme) RequiredSignatures() int

RequiredSignatures returns the number of signatures required for the scheme.

type TrustAct

type TrustAct struct {
	Event            *event.E
	TargetPubkey     string
	TrustLevel       TrustLevel
	RelayURL         string
	Expiry           *time.Time
	Reason           TrustReason
	ReplicationKinds []uint16
	IdentityTag      *IdentityTag
}

TrustAct represents a complete Trust Act event (Kind 39101) with typed access to its components.

func NewTrustAct

func NewTrustAct(
	pubkey []byte,
	targetPubkey string,
	trustLevel TrustLevel,
	relayURL string,
	expiry *time.Time,
	reason TrustReason,
	replicationKinds []uint16,
	identityTag *IdentityTag,
) (ta *TrustAct, err error)

NewTrustAct creates a new Trust Act event.

func ParseTrustAct

func ParseTrustAct(ev *event.E) (ta *TrustAct, err error)

ParseTrustAct parses an event into a TrustAct structure with validation.

func (*TrustAct) GetExpiry

func (ta *TrustAct) GetExpiry() *time.Time

GetExpiry returns the expiry time, or nil if no expiry is set.

func (*TrustAct) GetIdentityTag

func (ta *TrustAct) GetIdentityTag() *IdentityTag

GetIdentityTag returns the identity tag, or nil if not present.

func (*TrustAct) GetReason

func (ta *TrustAct) GetReason() TrustReason

GetReason returns the reason for the trust relationship.

func (*TrustAct) GetRelayURL

func (ta *TrustAct) GetRelayURL() string

GetRelayURL returns the target relay's URL.

func (*TrustAct) GetReplicationKinds

func (ta *TrustAct) GetReplicationKinds() []uint16

GetReplicationKinds returns the list of event kinds to replicate.

func (*TrustAct) GetTargetPubkey

func (ta *TrustAct) GetTargetPubkey() string

GetTargetPubkey returns the target relay's public key.

func (*TrustAct) GetTrustLevel

func (ta *TrustAct) GetTrustLevel() TrustLevel

GetTrustLevel returns the trust level.

func (*TrustAct) HasReplicationKind

func (ta *TrustAct) HasReplicationKind(kind uint16) bool

HasReplicationKind returns true if the act includes the specified kind for replication.

func (*TrustAct) IsExpired

func (ta *TrustAct) IsExpired() bool

IsExpired returns true if the trust act has expired.

func (*TrustAct) ShouldReplicate

func (ta *TrustAct) ShouldReplicate(kind uint16) bool

ShouldReplicate returns true if an event of the given kind should be replicated based on this trust act.

func (*TrustAct) ShouldReplicateEvent

func (ta *TrustAct) ShouldReplicateEvent(kind uint16) (shouldReplicate bool, err error)

ShouldReplicateEvent determines whether a specific event should be replicated based on the trust level using partial replication (random dice-throw). This function uses crypto/rand for cryptographically secure randomness.

func (*TrustAct) Validate

func (ta *TrustAct) Validate() (err error)

Validate performs comprehensive validation of a TrustAct.

type TrustCalculator

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

TrustCalculator helps calculate trust scores and inheritance.

func NewTrustCalculator

func NewTrustCalculator() *TrustCalculator

NewTrustCalculator creates a new trust calculator.

func (*TrustCalculator) AddAct

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

AddAct adds a trust act to the calculator.

func (*TrustCalculator) CalculateInheritedTrust

func (tc *TrustCalculator) CalculateInheritedTrust(
	fromPubkey, toPubkey string,
) TrustLevel

CalculateInheritedTrust calculates inherited trust through the web of trust. With numeric trust levels, inherited trust is calculated by multiplying the trust percentages at each hop, reducing trust over distance.

func (*TrustCalculator) GetTrustLevel

func (tc *TrustCalculator) GetTrustLevel(pubkey string) TrustLevel

GetTrustLevel returns the trust level for a given pubkey.

type TrustLevel

type TrustLevel uint8

TrustLevel represents the replication percentage (0-100) indicating the probability that any given event will be replicated.

This implements partial replication via cryptographic random selection: For each event, a secure random number (0-100) is generated and compared to the trust level. If random ≤ trust_level, the event is replicated.

Benefits of numeric trust levels:

  • Precise resource control (bandwidth, storage, CPU)
  • Probabilistic network coverage via multiple propagation paths
  • Network resilience through random subset selection
  • Graceful degradation under resource constraints
  • Trust inheritance via percentage multiplication (e.g., 75% * 50% = 37.5%)
const (
	TrustLevelNone    TrustLevel = 0   // No replication (0%)
	TrustLevelMinimal TrustLevel = 10  // Minimal sampling (10%) - network discovery
	TrustLevelLow     TrustLevel = 25  // Low partial replication (25%) - exploratory
	TrustLevelMedium  TrustLevel = 50  // Medium partial replication (50%) - standard
	TrustLevelHigh    TrustLevel = 75  // High partial replication (75%) - important
	TrustLevelFull    TrustLevel = 100 // Full replication (100%) - critical partners
)

Suggested trust level constants for common use cases. These are guidelines; any value 0-100 is valid.

type TrustReason

type TrustReason string

TrustReason indicates how a trust relationship was established. This helps operators understand and audit their trust networks.

const (
	TrustReasonManual    TrustReason = "manual"    // Manually configured by operator
	TrustReasonAutomatic TrustReason = "automatic" // Automatically established by policy
	TrustReasonInherited TrustReason = "inherited" // Inherited through web of trust
)

Source Files

  • doc.go
  • group_tag_act.go
  • helpers.go
  • public_key_advertisement.go
  • relay_identity.go
  • replication_request.go
  • replication_response.go
  • trust_act.go
  • types.go
  • validation.go

Jump to

Keyboard shortcuts

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