libp2p/switch

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
  
Source   Edit  
Switch {.public.} = ref object of Dial
  peerInfo*: PeerInfo
  connManager*: ConnManager
  transports*: seq[Transport]
  ms*: MultistreamSelect
  dialer*: Dial
  peerStore*: PeerStore
  nameResolver*: NameResolver
  services*: seq[Service]
Source   Edit  

Procs

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

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: [],
    forbids: [].}

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: [], forbids: [].}
Source   Edit  
proc dial(s: Switch; peerId: PeerId; addrs: seq[MultiAddress]; proto: string): Future[
    Connection] {.public, ...raises: [], tags: [], forbids: [].}
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: [], forbids: [].}
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: [], forbids: [].}
Disconnect from a peer, waiting for the connection(s) to be dropped Source   Edit  
proc isConnected(s: Switch; peerId: PeerId): bool {.public, ...raises: [],
    tags: [], forbids: [].}
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: [], forbids: [].}
Source   Edit  
proc removeConnEventHandler(s: Switch; handler: ConnEventHandler;
                            kind: ConnEventKind) {.public, ...raises: [], tags: [],
    forbids: [].}
Source   Edit  
proc removePeerEventHandler(s: Switch; handler: PeerEventHandler;
                            kind: PeerEventKind) {.public, ...raises: [], tags: [],
    forbids: [].}
Source   Edit  
proc start(s: Switch) {.async, ...gcsafe, public, ...raises: [],
                        tags: [TimeEffect, WriteIOEffect, RootEffect],
                        forbids: [].}
Start listening on every transport Source   Edit  
proc stop(s: Switch) {.async, public, ...raises: [],
                       tags: [TimeEffect, WriteIOEffect, RootEffect],
                       forbids: [].}
Stop listening on every transport, and close every active connections Source   Edit  

Methods

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

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;
               upgradeDir = Direction.Out): Future[void] {.public, ...raises: [],
    tags: [], forbids: [].}
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: [], forbids: [].}
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: [], forbids: [].}
Open a stream to a connected peer with the specified protos Source   Edit  
method run(self: Service; switch: Switch) {.base, async, ...gcsafe, raises: [],
    tags: [], forbids: [].}
Source   Edit  
method setup(self: Service; switch: Switch): Future[bool] {.base, async, ...gcsafe,
    raises: [], tags: [TimeEffect, WriteIOEffect], forbids: [].}
Source   Edit  
method stop(self: Service; switch: Switch): Future[bool] {.base, async, ...gcsafe,
    raises: [], tags: [TimeEffect, WriteIOEffect], forbids: [].}
Source   Edit  

Exports

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