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