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