Libp2p.ConnectionV2 (libp2p_elixir v0.9.0)

Manages a secure, multiplexed Libp2p connection.

This module encapsulates the state machine for a single peer connection, handling the transition from a raw transport socket to a fully functional application session.

Connection Lifecycle

The connection process follows the standard Libp2p upgrade path:

  1. Transport Establishment: A raw TCP connection is established (either via Dial or Listen).
  2. Multistream-select (Security): The peers negotiate the security protocol. Only /noise is currently supported.
  3. Secure Handshake: The peers perform a Noise XX handshake to authenticate each other and establish shared encryption keys. See Libp2p.Noise for details.
  4. Multistream-select (Muxer): Over the now-encrypted channel, the peers negotiate a stream multiplexer. Only /yamux/1.0.0 is currently supported.
  5. Multiplexing (Yamux): The process enters the Yamux session mode. It acts as the controller for the session, parsing incoming frames and routing them to logical streams.

Stream Management

Once established, this process manages multiple concurrent logical streams (Libp2p.InboundStream or task-based handlers). It handles:

  • Opening new outbound streams.
  • Accepting inbound streams and negotiating protocols.
  • Flow control (Yamux window updates).
  • Connection teardown (GoAway frames).

Summary

Types

role()

@type role() :: :initiator | :responder

Functions

await_ready(conn, timeout \\ 20000)

@spec await_ready(pid(), timeout()) :: :ok | {:error, term()}

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

close_stream(conn, stream_id)

@spec close_stream(pid(), non_neg_integer()) :: :ok | {:error, term()}

open_stream(conn)

@spec open_stream(pid()) :: {:ok, non_neg_integer()} | {:error, term()}

open_stream(conn, initial_data)

@spec open_stream(pid(), binary()) :: {:ok, non_neg_integer()} | {:error, term()}

peer_store(conn)

@spec peer_store(pid()) :: pid() | atom()

remote_peer_id(conn)

@spec remote_peer_id(pid()) :: {:ok, binary()} | {:error, term()}

reset_stream(conn, stream_id)

@spec reset_stream(pid() | atom(), non_neg_integer()) :: :ok | {:error, term()}

Reset (RST) a yamux stream.

send_stream(conn, stream_id, data)

@spec send_stream(pid(), non_neg_integer(), binary()) :: :ok | {:error, term()}

set_stream_handler(conn, stream_id, pid)

@spec set_stream_handler(pid(), non_neg_integer(), pid()) :: :ok

Set the process that will receive stream events.

start_link(opts)

@spec start_link(keyword()) :: GenServer.on_start()