libp2p/peerstore

Search:
Group by:
Source   Edit  

Stores generic informations about peers.

Example:

import libp2p/peerstore
# Will keep info of all connected peers +
# last 50 disconnected peers.
# Passing `nil` for `identify` is only safe for simple peer-book usage like
# this example. APIs that rely on identify metadata require a real
# `Identify` instance when constructing the `PeerStore`.
import libp2p/[peerid, crypto/crypto]

let ps = PeerStore.new(nil, capacity = 50)

# Create a custom book type
type MoodBook = ref object of PeerBook[string]

let exampleRng = newRng()
var somePeerId = PeerId.random(exampleRng).expect("get random key")

ps[MoodBook][somePeerId] = "Happy"
doAssert ps[MoodBook][somePeerId] == "Happy"
##########################################################################################################################################

Types

AddressBook = ref object of PeerBook[seq[AddressEntry]]
  ttls*: AddressConfidenceTtls
Source   Edit  
AddressConfidence = enum
  Low, ## Self-reported by the peer via identify/identify-push, or manually
        ## provided by the user. Not yet verified by a direct connection.
        ## Medium TTL: reasonably trusted but not confirmed reachable.
  Medium, ## Verified: we successfully dialled this address at least once.
           ## Long TTL: high confidence that the address is reachable.
  High,                     ## Never expires regardless of how long since the last update.
  Infinite
Received from a discovery mechanism (DHT, rendezvous, mDNS, etc.). Not yet verified by a direct connection. Short TTL: quickly discarded if the address is never used. Source   Edit  
AddressConfidenceTtls = object
  low*: Duration = (value: 900000000000)
  medium*: Duration = (value: 3600000000000)
  high*: Duration = (value: 86400000000000)
Source   Edit  
AddressEntry = object
  address*: MultiAddress
  confidence*: AddressConfidence
  lastUpdated*: Moment
Source   Edit  
AgentBook = ref object of PeerBook[string]
Source   Edit  
KeyBook = ref object of PeerBook[PublicKey]
Source   Edit  
LastSeenBook = ref object of PeerBook[Opt[MultiAddress]]
Source   Edit  
LastSeenOutboundBook = ref object of PeerBook[Opt[MultiAddress]]
Source   Edit  
PeerBook[T] = ref object of BasePeerBook
  book*: Table[PeerId, T]
Source   Edit  
PeerBookChangeHandler = proc (peerId: PeerId) {....gcsafe, raises: [].}
Source   Edit  
PeerStore = ref object
  identify*: Identify
  capacity*: int
  toClean*: seq[PeerId]
  addressPolicy*: PeerAddressPolicy ## When set, inbound peer addresses are filtered through the shared
                                    ## policy before they are stored or redistributed.
  addressTtls*: AddressConfidenceTtls ## Per-confidence TTLs for address expiry.
  pruneHandle*: Future[void]
Source   Edit  
ProtoBook = ref object of SeqPeerBook[string]
Source   Edit  
ProtoVersionBook = ref object of PeerBook[string]
Source   Edit  
SeqPeerBook[T] = ref object of PeerBook[seq[T]]
Source   Edit  
SPRBook = ref object of PeerBook[Envelope]
Source   Edit  

Procs

proc `[]`(addressBook: AddressBook; peerId: PeerId): seq[MultiAddress] {.
    ...raises: [], tags: [], forbids: [].}
Return non-expired addresses for peerId. Connected peers keep their known addresses visible until disconnect. Source   Edit  
proc `[]`(p: PeerStore; _: type[AddressBook]): AddressBook {....raises: [].}
Get the AddressBook, initialising it with the store's configured TTLs. Source   Edit  
proc `[]`[T](p: PeerStore; typ: type[T]): T {....raises: [].}
Get a book from the PeerStore (ex: peerStoreAddressBook) Source   Edit  
proc `[]`[T](peerBook: PeerBook[T]; peerId: PeerId): T {....raises: [].}
Get all known metadata of a provided peer, or default(T) if missing Source   Edit  
proc `[]=`(addressBook: AddressBook; peerId: PeerId; addrs: seq[MultiAddress]) {.
    ...raises: [], tags: [RootEffect], forbids: [].}
Source   Edit  
proc `[]=`[T](peerBook: PeerBook[T]; peerId: PeerId; entry: T) {....raises: [].}
Set metadata for a given peerId. Source   Edit  
proc addHandler[T](peerBook: PeerBook[T]; handler: PeerBookChangeHandler) {.
    ...raises: [].}
Adds a callback that will be called everytime the book changes Source   Edit  
proc cleanup(peerStore: PeerStore; peerId: PeerId) {....raises: [],
    tags: [RootEffect], forbids: [].}
Source   Edit  
proc close(peerStore: PeerStore) {....raises: [], tags: [RootEffect], forbids: [].}
Cancel the background TTL-pruning loop, if running. Source   Edit  
proc contains(addressBook: AddressBook; peerId: PeerId): bool {....raises: [],
    tags: [], forbids: [].}
Source   Edit  
proc contains[T](peerBook: PeerBook[T]; peerId: PeerId): bool {....raises: [].}
Source   Edit  
proc del(peerStore: PeerStore; peerId: PeerId) {....raises: [], tags: [RootEffect],
    forbids: [].}
Delete the provided peer from every book. Source   Edit  
proc del[T](peerBook: PeerBook[T]; peerId: PeerId): bool {....raises: [].}
Delete the provided peer from the book. Returns whether the peer was in the book Source   Edit  
proc entries(addressBook: AddressBook; peerId: PeerId): seq[AddressEntry] {.
    ...raises: [], tags: [], forbids: [].}
Return the raw entry list for peerId, including expired entries. Source   Edit  
proc extend(addressBook: AddressBook; key: PeerId; addrs: seq[MultiAddress];
            confidence = AddressConfidence.Medium) {....raises: [],
    tags: [RootEffect], forbids: [].}
Add addresses for key without removing existing ones. For addresses already present the confidence is upgraded to max(existing, confidence) and lastUpdated is refreshed. New addresses are added with confidence. Source   Edit  
proc extend[T](self: SeqPeerBook[T]; key: PeerId; new: seq[T]) {....raises: [].}
Source   Edit  
proc getMostObservedProtosAndPorts(self: PeerStore): seq[MultiAddress] {.
    ...raises: [], tags: [], forbids: [].}
Source   Edit  
proc guessDialableAddr(self: PeerStore; ma: MultiAddress): MultiAddress {.
    ...raises: [], tags: [RootEffect], forbids: [].}
Source   Edit  
proc identify(peerStore: PeerStore; muxer: Muxer; dir: Direction): InternalRaisesFuture[
    void, (CancelledError, IdentityNoMatchError, IdentityInvalidMsgError,
           MultiStreamError, LPStreamError, MuxerError)] {....stackTrace: false,
    raises: [], gcsafe, raises: [], tags: [RootEffect], forbids: [].}
Source   Edit  
proc isExpired(entry: AddressEntry; ttls: AddressConfidenceTtls): bool {.
    ...raises: [], tags: [], forbids: [].}
Returns true only when the TTL is positive and the elapsed time exceeds it. Source   Edit  
proc len[T](peerBook: PeerBook[T]): int {....raises: [].}
Source   Edit  
proc markConnected(addressBook: AddressBook; peerId: PeerId; ma: MultiAddress) {.
    ...raises: [], tags: [RootEffect], forbids: [].}
Called after a successful outbound connection to ma. Upgrades the address to High confidence and refreshes its lastUpdated. If the address is not yet in the book it is added. Source   Edit  
proc markPeerConnected(peerStore: PeerStore; peerId: PeerId) {....raises: [],
    tags: [], forbids: [].}
Mark peerId as actively connected so known addresses do not TTL-expire. Source   Edit  
proc markPeerDisconnected(peerStore: PeerStore; peerId: PeerId) {....raises: [],
    tags: [], forbids: [].}
Drop active connection state after refreshing known addresses for redial. Source   Edit  
proc new(Self: type PeerStore; identify: Identify; capacity = 1000;
         addressTtls = AddressConfidenceTtls()): PeerStore {....raises: [].}
Source   Edit  
proc pruneExpired(addressBook: AddressBook) {....raises: [], tags: [RootEffect],
    forbids: [].}
Remove all per-address entries whose TTL has elapsed. Connected peers keep their entries fresh while they remain connected. Peers whose last address expires are removed from the AddressBook only; other peer metadata (keys, protocols, agent version, etc.) is left intact. Source   Edit  
proc set(addressBook: AddressBook; peerId: PeerId; addrs: seq[MultiAddress];
         confidence = AddressConfidence.Medium) {....raises: [],
    tags: [RootEffect], forbids: [].}
Replace the address list for peerId. For addresses that already exist the confidence is upgraded to max(existing, confidence) so that a high-confidence entry is never downgraded by a lower-confidence update. High/Infinite entries absent from the incoming list are preserved so that a verified dial address is never evicted by a later Identify update. Source   Edit  
proc startAddressPruning(peerStore: PeerStore) {....raises: [], tags: [RootEffect],
    forbids: [].}
Start the periodic per-address TTL pruning loop. No-op if already running. Uses the smallest positive TTL across all confidence levels as the interval. If all TTLs are zero (non-expiring), the loop is not started. Source   Edit  
proc updatePeerInfo(peerStore: PeerStore; info: IdentifyInfo;
                    observedAddr: Opt[MultiAddress] = Opt.none(MultiAddress);
                    direction: Opt[Direction] = Opt.none(Direction)) {.
    ...raises: [], tags: [RootEffect], forbids: [].}
Source   Edit