libp2p/switch

    Dark Mode
Search:
Group by:
  Source   Edit

The switch is the core of libp2p, which brings together the transports, the connection manager, the upgrader and other parts to allow programs to use libp2p

Types

Service = ref object of RootObj
  inUse: bool
  Source   Edit
Switch {.public.} = ref object of Dial
  peerInfo*: PeerInfo
  connManager*: ConnManager
  transports*: seq[Transport]
  ms*: MultistreamSelect
  acceptFuts: seq[Future[void]]
  dialer*: Dial
  peerStore*: PeerStore
  nameResolver*: NameResolver
  started: bool
  services*: seq[Service]
  Source   Edit

Procs

proc addConnEventHandler(s: Switch; handler: ConnEventHandler;
                         kind: ConnEventKind) {.public, ...raises: [],
    tags: [RootEffect].}

Adds a ConnEventHandler, which will be triggered when a connection to a peer is created or dropped. There may be multiple connections per peer.

The handler should not raise.

  Source   Edit
proc addPeerEventHandler(s: Switch; handler: PeerEventHandler;
                         kind: PeerEventKind) {.public, ...raises: [],
    tags: [RootEffect].}

Adds a PeerEventHandler, which will be triggered when a peer connects or disconnects from us.

The handler should not raise.

  Source   Edit
proc connectedPeers(s: Switch; dir: Direction): seq[PeerId] {....raises: [],
    tags: [RootEffect].}
  Source   Edit
proc dial(s: Switch; peerId: PeerId; addrs: seq[MultiAddress]; proto: string): Future[
    Connection] {.public, ...raises: [], tags: [RootEffect].}
Connected to a peer and open a stream with the specified proto   Source   Edit
proc dial(s: Switch; peerId: PeerId; proto: string): Future[Connection] {.
    public, ...raises: [], tags: [RootEffect].}
Open a stream to a connected peer with the specified proto   Source   Edit
proc disconnect(s: Switch; peerId: PeerId): Future[void] {....gcsafe, public,
    ...raises: [], tags: [RootEffect].}
Disconnect from a peer, waiting for the connection(s) to be dropped   Source   Edit
proc isConnected(s: Switch; peerId: PeerId): bool {.public, ...raises: [], tags: [].}
returns true if the peer has one or more associated connections   Source   Edit
proc mount[T: LPProtocol](s: Switch; proto: T; matcher: Matcher = nil) {....gcsafe,
    raises: [LPError], public, ...raises: [].}
mount a protocol to the switch   Source   Edit
proc newSwitch(peerInfo: PeerInfo; transports: seq[Transport];
               secureManagers: openArray[Secure] = []; connManager: ConnManager;
               ms: MultistreamSelect; peerStore: PeerStore;
               nameResolver: NameResolver = nil; services = newSeq()): Switch {.
    ...raises: [LPError], raises: [], tags: [].}
  Source   Edit
proc removeConnEventHandler(s: Switch; handler: ConnEventHandler;
                            kind: ConnEventKind) {.public, ...raises: [],
    tags: [RootEffect].}
  Source   Edit
proc removePeerEventHandler(s: Switch; handler: PeerEventHandler;
                            kind: PeerEventKind) {.public, ...raises: [],
    tags: [RootEffect].}
  Source   Edit
proc start(s: Switch): Future[void] {.public(), stackTrace: false, ...raises: [],
                                      gcsafe, raises: [], raises: [],
                                      tags: [RootEffect].}
Start listening on every transport   Source   Edit
proc stop(s: Switch): Future[void] {.public(), stackTrace: false, ...raises: [],
                                     gcsafe, raises: [], raises: [],
                                     tags: [RootEffect].}
Stop listening on every transport, and close every active connections   Source   Edit

Methods

method addTransport(s: Switch; t: Transport) {....raises: [], tags: [].}
  Source   Edit
method connect(s: Switch; address: MultiAddress; allowUnknownPeerId = false): Future[
    PeerId] {....raises: [], tags: [RootEffect].}

Connects to a peer and retrieve its PeerId

If the P2P part is missing from the MA and allowUnknownPeerId is set to true, this will discover the PeerId while connecting. This exposes you to MiTM attacks, so it shouldn't be used without care!

  Source   Edit
method connect(s: Switch; peerId: PeerId; addrs: seq[MultiAddress];
               forceDial = false; reuseConnection = true; dir = Direction.Out): Future[
    void] {.public, ...raises: [], tags: [RootEffect].}
Connects to a peer without opening a stream to it   Source   Edit
method dial(s: Switch; peerId: PeerId; addrs: seq[MultiAddress];
            protos: seq[string]; forceDial = false): Future[Connection] {.
    public, ...raises: [], tags: [RootEffect].}
Connected to a peer and open a stream with the specified protos   Source   Edit
method dial(s: Switch; peerId: PeerId; protos: seq[string]): Future[Connection] {.
    public, ...raises: [], tags: [RootEffect].}
Open a stream to a connected peer with the specified protos   Source   Edit
method run(self: Service; switch: Switch): Future[void] {.base,
    stackTrace: false, ...raises: [], gcsafe, raises: [], raises: [],
    tags: [RootEffect].}
  Source   Edit
method setup(self: Service; switch: Switch): Future[bool] {.base,
    stackTrace: false, ...raises: [], gcsafe, raises: [], raises: [],
    tags: [RootEffect].}
  Source   Edit
method stop(self: Service; switch: Switch): Future[bool] {.base,
    stackTrace: false, ...raises: [], gcsafe, raises: [], raises: [],
    tags: [RootEffect].}
  Source   Edit

Exports

ConnManager, getStream, PeerEventKind, getStream, addPeerEventHandler, new, ConnEventKind, PeerEventHandler, selectMuxer, getConnections, contains, removePeerEventHandler, expectConnection, ConnEvent, connCount, ConnEventHandler, addConnEventHandler, triggerConnEvent, removeConnEventHandler, contains, triggerPeerEvents, AlreadyExpectingConnectionError, PeerEvent, TooManyConnectionsError, getStream, trackConnection, close, MaxConnectionsPerPeer, connectedPeers, selectMuxer, trackMuxer, getOutgoingSlot, slotsAvailable, dropPeer, getIncomingSlot, storeMuxer, release, MaxConnections, ConnectionSlot, DNS_OR_IP, LPStreamError, AlreadyExpectingConnectionError, shortLog, random, new, UDP_DNS, $, getProtoHeader, MaxConnectionsPerPeer, ephemeral, close, decode, MaPatternOp, ==, WS_DNS, initVBuffer, <=, decode, MaxSizeError, ==, ProtoFlags, handler=, getLen, handler, ECDHEScheme, shortLog, init, closed, addConnEventHandler, [], init, new, macOpenArray, random, init, new, Secret, peekVarint, random, handshake, MaxConnections, $, validate, mapOr, MaError, init, bytes, UpgradeFailedError, IdentityInvalidMsgError, maxInlineKeyLength, addHandler, TranscoderDNS, QUIC, ProtoVersion, [], init, withValue, getRequiredField, getField, mac, supported, removeConnEventHandler, WS_IP, write, public, MAKind, write, getField, checkFieldNumber, valueOr, codec, getRepeatedField, matchPartial, addObservation, IdentityNoMatchError, push, getBytes, WebSockets, trackConnection, &, data, readLp, HTTP, initVBuffer, start, atEof, PeerEventKind, getOutgoingSlot, peekSeq, toOpt, fullAddrs, payloadType, getProtoHeader, ProtoHeader, $, IP, protoAddress, newRng, withValue, IdentifyPushCodec, SecureConn, checkValid, getPublicKey, CircuitRelay, len, libp2p_failed_upgrades_incoming, exceptionToAssert, extractPublicKey, mapAnd, new, UDP_IP, new, newLPStreamEOFError, selectMuxer, connCount, write, DNSADDR, LPError, handler, AddressMapper, IdentifyPushHandler, write, ConnManager, WSS, getField, TCP_IP, selectMuxer, writePacked, handle, init, closeImpl, Identify, readSeq, toBytes, TCP_DNS, shortLog, encode, len, capLen, init, protoName, protoArgument, PeerEventHandler, LPProtoHandler, secure, ==, toRawBytes, IdentifyPush, getStream, TranscoderIP6Zone, $, initProtoBuffer, key, maxIncomingStreams, WSS_DNS, list, match, <, CryptoResult, WebSockets_DNS, readMessage, ProtoResult, WebRTCDirect, init, init, upgrade, UDP, PeerInfo, TranscoderOnion, StreamTracker, IdentifyNoPubKeyError, write, init, getConnections, LPStreamResetError, isEmpty, writeArray, new, toString, LPStreamIncompleteError, PeerId, LPStreamEOFError, readOnce, maxIncomingStreams=, IP6, shortLog, new, release, initVBuffer, PKScheme, init, new, payload, triggerConnEvent, triggerPeerEvents, init, Connection, write, init, TCP, PrivateKey, dropPeer, getBytes, start, write, init, close, &=, PeerInfoError, newLPStreamClosedError, random, compilesOr, handle, trackMuxer, init, initProtoBuffer, toException, DNS, init, finish, Upgrade, goffset, readVarint, HandlerHolder, getRawBytes, >, SecureConnTrackerName, KeyPair, init, init, high, readVarint, cmp, init, SupportedWireTypes, formatItIMPL, formatItIMPL, initStream, hash, formatItIMPL, Signature, contains, exclIfIt, formatItIMPL, getStream, IPFS, shortLog, readOnce, init, secure, isEmpty, ConnEventKind, MultiAddress, ProtoScalar, shortLog, contains, hex, expandItIMPL, protocols, codec=, DefaultMaxIncomingStreams, hash, HTTPS, UNIX, encode, TooManyConnectionsError, ConnectionSlot, getPtr, getBytes, TLS_WS, sign, addHandler, storeMuxer, TranscoderIP4, formatItIMPL, PeerEvent, ObservedAddrManager, MaResult, ProtoField, init, IdentifyCodec, getStream, writeSeq, DigestSheme, ConnEvent, init, $, DNS6, [], IpTransportProtocol, toOpenArray, init, IP4, TranscoderPort, isEnough, safeConvert, addPeerEventHandler, init, >=, expectConnection, init, ephemeral, payloadDomain, update, $, withValue, init, LPStreamLimitError, libp2p_pki_schemes, TranscoderOnion3, SignedPayload, closeImpl, toBytes, Secure, newLPStreamLimitError, write, MaPattern, keyOpenArray, match, parseFullAddress, $, closeImpl, isEmpty, writeLp, connectedPeers, new, getRequiredRepeatedField, init, newLPStreamIncompleteError, initProtoBuffer, MAProtocol, newLPStreamResetError, parseFullAddress, getPackedRepeatedField, initStream, init, getField, shortLog, DNS4, getWrapped, readArray, selectBest, write, P2PPattern, getWrapped, Envelope, hasPublicKey, toException, contains, init, isEnough, init, Reliable, init, addrs, hex, slotsAvailable, write, WS, AgentVersion, init, DNSANY, MultistreamSelect, encode, LPProtocol, TimeoutHandler, stretchKeys, init, getField, match, getField, writeLPVarint, iv, DefaultConnectionTimeout, new, readLine, Eof, CryptoError, getField, append, init, decode, WSS_IP, LPStreamConnDownError, PeerRecord, init, SupportedSchemes, getRepeatedField, getField, select, hash, Unreliable, SupportedSchemesInt, random, checkFutures, handler=, libp2p_failed_upgrades_outgoing, shuffle, validate, Matcher, mapEq, getField, init, removePeerEventHandler, Onion3, write, LPStreamTrackerName, identify, select, concat, TranscoderP2P, AddressInfo, ConnectionTrackerName, TranscoderIP6, write, EnvelopeError, verify, IdentifyInfo, IdentifyError, addHandler, encode, len, newLPStreamRemoteClosedError, MaPatResult, Direction, ProtoBuffer, init, InvalidVarintError, shortLog, ==, write, getBytes, write, UTP, toBytes, finish, peekArray, getMostObservedProtosAndPorts, init, PublicKey, ConnEventHandler, WebSockets_IP, decodeMsg, VBuffer, writeLp, writePBVarint, ProtoFieldKind, readExactly, protoArgument, getRepeatedField, ProtoError, newLPStreamConnDownError, init, initStream, ivOpenArray, closeWithEOF, TcpOnion3, orError, vsizeof, getField, LPStreamRemoteClosedError, guessDialableAddr, MultiStreamError, protoCode, stop, MaInvalidAddress, select, LPStream, LPStreamClosedError, RsaDefaultKeySize, writeVarint, getIncomingSlot, items, write, toBytes, getOrder, TranscoderUnix, SignedPeerRecord, init, stop, join, dial, dial, dial, connect, checkFutures, LPError, addTransport, addTransport, connect, toException, new, dial, Dialer, tryDial, DialFailedError, connect, Dial, connect, toException, tryDial, SPRBook, PeerBook, ProtoBook, AddressBook, ProtoVersionBook, SeqPeerBook, KeyBook, PeerBookChangeHandler, AgentBook, new, PeerStore