libp2p package
Subpackages
- Bitswap
- libp2p.crypto package
- Subpackages
- Submodules
- libp2p.crypto.authenticated_encryption module
- libp2p.crypto.ecc module
- libp2p.crypto.ed25519 module
- libp2p.crypto.exceptions module
- libp2p.crypto.key_exchange module
- libp2p.crypto.keys module
- libp2p.crypto.rsa module
- libp2p.crypto.secp256k1 module
- libp2p.crypto.serialization module
- Module contents
- Subpackages
- libp2p.discovery package
- Subpackages
- libp2p.discovery.bootstrap package
- libp2p.discovery.events package
- libp2p.discovery.mdns package
- libp2p.discovery.random_walk package
- libp2p.discovery.rendezvous module
InternalErrorInvalidCookieErrorInvalidNamespaceErrorInvalidPeerInfoErrorInvalidTTLErrorNotAuthorizedErrorRendezvousClientRendezvousDiscoveryRendezvousErrorRendezvousServiceUnavailableError- Submodules
- libp2p.discovery.rendezvous.client module
- libp2p.discovery.rendezvous.service module
- libp2p.discovery.rendezvous.discovery module
- libp2p.discovery.rendezvous.config module
- libp2p.discovery.rendezvous.messages module
- Subpackages
- libp2p.discovery.upnp package
- Submodules
- Module contents
- Subpackages
- libp2p.filecoin package
- Submodules
- libp2p.filecoin.constants module
- libp2p.filecoin.networks module
- libp2p.filecoin.bootstrap module
- libp2p.filecoin.pubsub module
- libp2p.filecoin.cli module
- Module contents
FilecoinAddressFilecoinNetworkPresetaddress_protocol()blocks_topic()build_filecoin_gossipsub()build_filecoin_pubsub()build_filecoin_score_params()dht_protocol_name()filecoin_message_id()filter_bootstrap_for_transport()get_bootstrap_addresses()get_network_preset()get_runtime_bootstrap_addresses()is_valid_address()make_delegated_address()make_id_address()messages_topic()parse_address()resolve_dns_bootstrap_to_ip4_tcp()
- libp2p.host package
- Subpackages
- Submodules
- libp2p.host.basic_host module
BasicHostBasicHost.bootstrapBasicHost.close()BasicHost.conn_managerBasicHost.connect()BasicHost.disconnect()BasicHost.export_health_metrics()BasicHost.get_addrs()BasicHost.get_connected_peers()BasicHost.get_connection_health()BasicHost.get_health_monitor_status()BasicHost.get_id()BasicHost.get_live_peers()BasicHost.get_metrics_recv_channel()BasicHost.get_mux()BasicHost.get_nat_type()BasicHost.get_network()BasicHost.get_network_health_summary()BasicHost.get_peer_connection_info()BasicHost.get_peerstore()BasicHost.get_private_key()BasicHost.get_public_key()BasicHost.get_transport_addrs()BasicHost.initiate_autotls_procedure()BasicHost.is_peer_connected()BasicHost.mDNSBasicHost.multiselectBasicHost.multiselect_clientBasicHost.new_stream()BasicHost.peerstoreBasicHost.remove_stream_handler()BasicHost.run()BasicHost.send_command()BasicHost.set_stream_handler()BasicHost.upgrade_inbound_connection()BasicHost.upgrade_outbound_connection()BasicHost.upnp
- libp2p.host.defaults module
- libp2p.host.exceptions module
- libp2p.host.observed_addr_manager module
- libp2p.host.ping module
- libp2p.host.routed_host module
- Module contents
- libp2p.identity package
- libp2p.io package
- Submodules
- libp2p.io.abc module
- libp2p.io.exceptions module
- libp2p.io.msgio module
- libp2p.io.trio module
- libp2p.io.utils module
- Module contents
- libp2p.kad_dht package
- Subpackages
- Submodules
- libp2p.kad_dht.kad_dht module
DHTModeKadDHTKadDHT.add_peer()KadDHT.apply_fallbacks()KadDHT.find_peer()KadDHT.find_providers()KadDHT.get_diagnostics()KadDHT.get_routing_table_size()KadDHT.get_value()KadDHT.get_value_store_size()KadDHT.handle_stream()KadDHT.is_random_walk_enabled()KadDHT.provide()KadDHT.put_value()KadDHT.refresh_routing_table()KadDHT.register_validator()KadDHT.run()KadDHT.set_namespace_validator()KadDHT.set_validator()KadDHT.stop()KadDHT.strict_validationKadDHT.switch_mode()KadDHT.validate_config()
KadDhtEventget_connection_type()
- libp2p.kad_dht.peer_routing module
- libp2p.kad_dht.provider_store module
- libp2p.kad_dht.routing_table module
KBucketRoutingTableRoutingTable.add_peer()RoutingTable.cleanup_routing_table()RoutingTable.find_bucket()RoutingTable.find_local_closest_peers()RoutingTable.get_diagnostics()RoutingTable.get_peer_ids()RoutingTable.get_peer_info()RoutingTable.get_peer_infos()RoutingTable.get_stale_peers()RoutingTable.get_target_keys_for_refresh()RoutingTable.peer_in_table()RoutingTable.remove_peer()RoutingTable.size()RoutingTable.start_periodic_refresh()
gen_random_key_in_bucket()key_to_int()peer_id_to_key()
- libp2p.kad_dht.utils module
- libp2p.kad_dht.value_store module
- libp2p.kad_dht.pb
- Module contents
BucketStatCoverageGapDHTModeFreshnessDistributionKadDHTKadDHT.add_peer()KadDHT.apply_fallbacks()KadDHT.find_peer()KadDHT.find_providers()KadDHT.get_diagnostics()KadDHT.get_routing_table_size()KadDHT.get_value()KadDHT.get_value_store_size()KadDHT.handle_stream()KadDHT.is_random_walk_enabled()KadDHT.provide()KadDHT.put_value()KadDHT.refresh_routing_table()KadDHT.register_validator()KadDHT.run()KadDHT.set_namespace_validator()KadDHT.set_validator()KadDHT.stop()KadDHT.strict_validationKadDHT.switch_mode()KadDHT.validate_config()
PeerRoutingRoutingTableRoutingTable.add_peer()RoutingTable.cleanup_routing_table()RoutingTable.find_bucket()RoutingTable.find_local_closest_peers()RoutingTable.get_diagnostics()RoutingTable.get_peer_ids()RoutingTable.get_peer_info()RoutingTable.get_peer_infos()RoutingTable.get_stale_peers()RoutingTable.get_target_keys_for_refresh()RoutingTable.peer_in_table()RoutingTable.remove_peer()RoutingTable.size()RoutingTable.start_periodic_refresh()
RoutingTableDiagnosticsRoutingTableReportRoutingTableReport.bucket_statsRoutingTableReport.coverage_gapsRoutingTableReport.extraRoutingTableReport.freshnessRoutingTableReport.health_scoreRoutingTableReport.keyspace_coverageRoutingTableReport.local_peer_id_hexRoutingTableReport.populated_bucketsRoutingTableReport.summary()RoutingTableReport.timestampRoutingTableReport.total_bucketsRoutingTableReport.total_peersRoutingTableReport.verdict
ValueStorecreate_key_from_binary()
- libp2p.network package
- Subpackages
- Submodules
- libp2p.network.exceptions module
- libp2p.network.swarm module
SwarmSwarm.add_conn()Swarm.auto_connectorSwarm.background_nurserySwarm.cleanup_connection_health()Swarm.close()Swarm.close_peer()Swarm.common_stream_handlerSwarm.connection_configSwarm.connection_gateSwarm.connection_prunerSwarm.connectionsSwarm.connections_legacySwarm.dial_addr()Swarm.dial_peer()Swarm.dial_peer_replacement()Swarm.dns_resolverSwarm.event_background_nursery_createdSwarm.export_health_metrics()Swarm.get_conn_mgr_info()Swarm.get_connection()Swarm.get_connections()Swarm.get_connections_map()Swarm.get_global_health_summary()Swarm.get_health_monitor_status()Swarm.get_metrics()Swarm.get_peer_health_summary()Swarm.get_peer_id()Swarm.get_tag_info()Swarm.get_total_connections()Swarm.health_dataSwarm.initialize_connection_health()Swarm.is_protected()Swarm.listen()Swarm.listenersSwarm.new_stream()Swarm.notifeesSwarm.notify_closed_stream()Swarm.notify_connected()Swarm.notify_disconnected()Swarm.notify_listen()Swarm.notify_listen_close()Swarm.notify_opened_stream()Swarm.peerstoreSwarm.protect()Swarm.record_connection_error()Swarm.record_connection_event()Swarm.register_notifee()Swarm.remove_conn()Swarm.remove_notifee()Swarm.retry_configSwarm.run()Swarm.self_idSwarm.set_resource_manager()Swarm.set_stream_handler()Swarm.tag_peer()Swarm.tag_storeSwarm.transport_managerSwarm.unblock_peer()Swarm.unprotect()Swarm.untag_peer()Swarm.upgrade_inbound_raw_conn()Swarm.upgrade_outbound_raw_conn()Swarm.upgrader
create_default_stream_handler()
- Module contents
AutoConnectorAutoConnector.clear_all_cooldowns()AutoConnector.clear_cooldown()AutoConnector.maybe_connect()AutoConnector.record_disconnect()AutoConnector.record_failed_connection()AutoConnector.record_successful_connection()AutoConnector.run_background_task()AutoConnector.set_discovery_callback()AutoConnector.start()AutoConnector.stop()
CommonTagsConnectionPrunerTagInfoTagStoreTagStore.clear_peer()TagStore.get_all_peers()TagStore.get_protected_peers()TagStore.get_tag()TagStore.get_tag_info()TagStore.get_tag_value()TagStore.is_protected()TagStore.protect()TagStore.record_connection()TagStore.remove_connection()TagStore.tag_peer()TagStore.unprotect()TagStore.untag_peer()TagStore.upsert_tag()
upsert_add()upsert_bounded()upsert_set()
- libp2p.observability package
- Subpackages
- libp2p.observability.oso package
- Submodules
- libp2p.observability.oso.cli module
- libp2p.observability.oso.dependency_graph module
- libp2p.observability.oso.generators module
- libp2p.observability.oso.metrics module
- libp2p.observability.oso.models module
- libp2p.observability.oso.providers module
- libp2p.observability.oso.report module
- libp2p.observability.oso.service module
- libp2p.observability.oso.transitive_graph module
- Module contents
- libp2p.observability.oso package
- Module contents
- Subpackages
- libp2p.peer package
- Submodules
- libp2p.peer.envelope module
- libp2p.peer.id module
- libp2p.peer.peer_record module
- libp2p.peer.peerdata module
PeerDataPeerData.add_addrs()PeerData.add_privkey()PeerData.add_protocols()PeerData.add_pubkey()PeerData.addrsPeerData.clear_addrs()PeerData.clear_keydata()PeerData.clear_metadata()PeerData.clear_metrics()PeerData.clear_protocol_data()PeerData.first_supported_protocol()PeerData.get_addrs()PeerData.get_last_identified()PeerData.get_metadata()PeerData.get_privkey()PeerData.get_protocols()PeerData.get_pubkey()PeerData.get_ttl()PeerData.is_expired()PeerData.last_identifiedPeerData.latency_EWMA()PeerData.latmapPeerData.metadataPeerData.privkeyPeerData.protocolsPeerData.pubkeyPeerData.put_metadata()PeerData.record_latency()PeerData.remove_protocols()PeerData.set_protocols()PeerData.set_ttl()PeerData.supports_protocols()PeerData.ttlPeerData.update_last_identified()
PeerDataError
- libp2p.peer.peerinfo module
- libp2p.peer.peerstore module
PeerRecordStatePeerStorePeerStore.add_addr()PeerStore.add_addrs()PeerStore.add_key_pair()PeerStore.add_privkey()PeerStore.add_protocols()PeerStore.add_pubkey()PeerStore.addr_stream()PeerStore.addrs()PeerStore.clear_addrs()PeerStore.clear_keydata()PeerStore.clear_metadata()PeerStore.clear_metrics()PeerStore.clear_peerdata()PeerStore.clear_protocol_data()PeerStore.consume_peer_record()PeerStore.consume_peer_records()PeerStore.first_supported_protocol()PeerStore.get()PeerStore.get_local_record()PeerStore.get_peer_record()PeerStore.get_protocols()PeerStore.has_peer()PeerStore.latency_EWMA()PeerStore.maybe_delete_peer_record()PeerStore.peer_data_mapPeerStore.peer_ids()PeerStore.peer_info()PeerStore.peer_with_keys()PeerStore.peers_with_addrs()PeerStore.privkey()PeerStore.pubkey()PeerStore.put()PeerStore.record_latency()PeerStore.remove_protocols()PeerStore.set_local_record()PeerStore.set_protocols()PeerStore.start_cleanup_task()PeerStore.supports_protocols()PeerStore.valid_peer_ids()
PeerStoreErrorcreate_signed_peer_record()env_to_send_in_RPC()issue_and_cache_local_record()
- Module contents
- libp2p.perf package
- libp2p.protocol_muxer package
- libp2p.pubsub package
- Subpackages
- Submodules
- libp2p.pubsub.exceptions module
- libp2p.pubsub.floodsub module
- libp2p.pubsub.gossipsub module
GossipSubGossipSub.adaptive_degree_highGossipSub.adaptive_degree_lowGossipSub.adaptive_gossip_enabledGossipSub.add_peer()GossipSub.attach()GossipSub.back_offGossipSub.degreeGossipSub.degree_highGossipSub.degree_lowGossipSub.direct_connect_heartbeat()GossipSub.direct_connect_initial_delayGossipSub.direct_connect_intervalGossipSub.direct_peersGossipSub.do_pxGossipSub.dont_send_message_idsGossipSub.eclipse_protection_enabledGossipSub.emit_control_message()GossipSub.emit_extension()GossipSub.emit_graft()GossipSub.emit_idontwant()GossipSub.emit_ihave()GossipSub.emit_iwant()GossipSub.emit_observe()GossipSub.emit_prune()GossipSub.emit_unobserve()GossipSub.equivocation_detectionGossipSub.extensions_stateGossipSub.fanoutGossipSub.fanout_heartbeat()GossipSub.flush_pending_messages()GossipSub.get_protocols()GossipSub.gossip_factorGossipSub.gossip_heartbeat()GossipSub.handle_graft()GossipSub.handle_idontwant()GossipSub.handle_ihave()GossipSub.handle_iwant()GossipSub.handle_observe()GossipSub.handle_prune()GossipSub.handle_rpc()GossipSub.handle_unobserve()GossipSub.heartbeat()GossipSub.heartbeat_initial_delayGossipSub.heartbeat_intervalGossipSub.join()GossipSub.last_health_updateGossipSub.leave()GossipSub.max_idontwant_messagesGossipSub.max_messages_per_topic_per_secondGossipSub.mcacheGossipSub.meshGossipSub.mesh_heartbeat()GossipSub.message_rate_limitsGossipSub.min_mesh_diversity_ipsGossipSub.network_health_scoreGossipSub.on_peer_subscribed()GossipSub.pack_control_msgs()GossipSub.peer_protocolGossipSub.protocolsGossipSub.prune_back_offGossipSub.publish()GossipSub.pubsubGossipSub.px_peers_countGossipSub.register_extension_handler()GossipSub.remove_peer()GossipSub.run()GossipSub.scorerGossipSub.select_from_minus()GossipSub.send_recent_messages()GossipSub.send_rpc()GossipSub.spam_protection_enabledGossipSub.start_observing_topic()GossipSub.stop_observing_topic()GossipSub.supports_protocol_feature()GossipSub.supports_scoring()GossipSub.supports_v13_features()GossipSub.supports_v20_features()GossipSub.time_since_last_publishGossipSub.time_to_liveGossipSub.topic_observationGossipSub.unregister_extension_handler()GossipSub.unsubscribe_back_offGossipSub.wait_for_mesh()
- libp2p.pubsub.mcache module
- libp2p.pubsub.pubsub module
ContentAddressedMessageIDGeneratorCustomMessageIDGeneratorGossipsubEventMessageIDGeneratorPeerAndSeqnoMessageIDGeneratorPubsubPubsub.add_to_blacklist()Pubsub.allowed_topicsPubsub.blacklisted_peersPubsub.clear_blacklist()Pubsub.continuously_read_stream()Pubsub.counterPubsub.dead_peer_receive_channelPubsub.ensure_peer_stream()Pubsub.event_handle_dead_peer_queue_startedPubsub.event_handle_peer_queue_startedPubsub.get_blacklisted_peers()Pubsub.get_hello_packet()Pubsub.get_message_id()Pubsub.get_msg_validators()Pubsub.handle_dead_peer_queue()Pubsub.handle_peer_queue()Pubsub.handle_sending_messages()Pubsub.handle_subscription()Pubsub.hostPubsub.is_peer_blacklisted()Pubsub.max_inbound_rpc_sizePubsub.max_subscriptions_per_peerPubsub.max_subscriptions_per_rpcPubsub.message_all_peers()Pubsub.my_idPubsub.notify_subscriptions()Pubsub.peer_queuesPubsub.peer_receive_channelPubsub.peer_topicsPubsub.peersPubsub.protocolsPubsub.publish()Pubsub.push_msg()Pubsub.remove_from_blacklist()Pubsub.remove_topic_validator()Pubsub.routerPubsub.run()Pubsub.seen_messagesPubsub.set_topic_validator()Pubsub.sign_keyPubsub.stream_handler()Pubsub.strict_signingPubsub.subscribe()Pubsub.subscribed_topics_receivePubsub.subscribed_topics_sendPubsub.topic_idsPubsub.topic_validatorsPubsub.unsubscribe()Pubsub.validate_msg()Pubsub.validation_cachePubsub.validation_timeoutPubsub.wait_for_mesh()Pubsub.wait_for_peer()Pubsub.wait_for_subscription()Pubsub.wait_until_ready()Pubsub.write_msg()
TopicValidatorValidationCacheValidationResultget_content_addressed_msg_id()get_peer_and_seqno_msg_id()get_secure_msg_id()get_timestamp_msg_id()get_topic_aware_msg_id()
- libp2p.pubsub.pubsub_notifee module
- libp2p.pubsub.subscription module
- libp2p.pubsub.validators module
- Module contents
- libp2p.request_response package
- Submodules
- libp2p.request_response.api module
- libp2p.request_response.codec module
- libp2p.request_response.exceptions module
- Module contents
- libp2p.rcmgr package
- Submodules
- libp2p.rcmgr.allowlist module
AllowlistAllowlist.add_multiaddr()Allowlist.add_peer()Allowlist.add_peer_multiaddr()Allowlist.allowed()Allowlist.allowed_multiaddr()Allowlist.allowed_peer()Allowlist.allowed_peer_and_multiaddr()Allowlist.clear()Allowlist.get_allowed_multiaddrs()Allowlist.get_allowed_peers()Allowlist.is_empty()Allowlist.remove_multiaddr()Allowlist.remove_peer()Allowlist.remove_peer_multiaddr()
AllowlistConfignew_allowlist()new_allowlist_with_config()
- libp2p.rcmgr.exceptions module
- libp2p.rcmgr.limits module
- libp2p.rcmgr.manager module
ConnectionScopeResourceLimitsResourceManagerResourceManager.acquire_connection()ResourceManager.acquire_memory()ResourceManager.acquire_scoped_stream()ResourceManager.acquire_stream()ResourceManager.close()ResourceManager.get_stats()ResourceManager.is_resource_available()ResourceManager.open_connection()ResourceManager.release_connection()ResourceManager.release_memory()ResourceManager.release_scoped_stream()ResourceManager.release_stream()ResourceManager.set_protocol_peer_stream_limit()ResourceManager.set_protocol_stream_limit()ResourceManager.set_service_peer_stream_limit()ResourceManager.set_service_stream_limit()
loggernew_resource_manager()
- libp2p.rcmgr.metrics module
DirectionMetricTypeMetricsMetrics.allow_conn()Metrics.allow_memory()Metrics.allow_stream()Metrics.block_conn()Metrics.block_memory()Metrics.block_stream()Metrics.get_counter()Metrics.get_gauge()Metrics.get_summary()Metrics.increment()Metrics.record_block()Metrics.record_connection()Metrics.record_memory()Metrics.record_stream()Metrics.release_memory()Metrics.remove_conn()Metrics.remove_stream()Metrics.reset()Metrics.set_gauge()
ResourceMetrics
- Module contents
DirectionResourceLimitsResourceManagerResourceManager.acquire_connection()ResourceManager.acquire_memory()ResourceManager.acquire_scoped_stream()ResourceManager.acquire_stream()ResourceManager.close()ResourceManager.get_stats()ResourceManager.is_resource_available()ResourceManager.open_connection()ResourceManager.release_connection()ResourceManager.release_memory()ResourceManager.release_scoped_stream()ResourceManager.release_stream()ResourceManager.set_protocol_peer_stream_limit()ResourceManager.set_protocol_stream_limit()ResourceManager.set_service_peer_stream_limit()ResourceManager.set_service_stream_limit()
ResourceScopeClosednew_resource_manager()
- libp2p.records package
- libp2p.relay package
- Subpackages
- libp2p.relay.circuit_v2 package
- Subpackages
- Submodules
- libp2p.relay.circuit_v2.protocol module
- libp2p.relay.circuit_v2.transport module
- libp2p.relay.circuit_v2.discovery module
- libp2p.relay.circuit_v2.resources module
- libp2p.relay.circuit_v2.config module
- libp2p.relay.circuit_v2.protocol_buffer module
- libp2p.relay.circuit_v2.performance_tracker module
- Module contents
- libp2p.relay.circuit_v2 package
- Module contents
- Subpackages
- libp2p.security package
- Subpackages
- Submodules
- libp2p.security.base_session module
- libp2p.security.base_transport module
- libp2p.security.exceptions module
- libp2p.security.secure_session module
- libp2p.security.security_multistream module
SecurityMultistreamSecurityMultistream.add_transport()SecurityMultistream.multiselectSecurityMultistream.multiselect_clientSecurityMultistream.secure_inbound()SecurityMultistream.secure_outbound()SecurityMultistream.select_transport()SecurityMultistream.select_transport_and_protocol()SecurityMultistream.transports
logger
- Module contents
- libp2p.stream_muxer package
- libp2p.tools package
- Subpackages
- libp2p.tools.anyio_service package
- Submodules
- libp2p.tools.anyio_service.api module
- libp2p.tools.anyio_service.context module
- libp2p.tools.anyio_service.exceptions module
- libp2p.tools.anyio_service.manager module
- libp2p.tools.anyio_service.stats module
- libp2p.tools.anyio_service.tasks module
- libp2p.tools.anyio_service.utils module
- Module contents
- libp2p.tools.timed_cache package
- libp2p.tools.anyio_service package
- Submodules
- libp2p.tools.constants module
GossipsubParamsGossipsubParams.degreeGossipsubParams.degree_highGossipsubParams.degree_lowGossipsubParams.direct_connect_initial_delayGossipsubParams.direct_connect_intervalGossipsubParams.direct_peersGossipsubParams.do_pxGossipsubParams.gossip_historyGossipsubParams.gossip_windowGossipsubParams.heartbeat_initial_delayGossipsubParams.heartbeat_intervalGossipsubParams.max_pending_messages_per_peerGossipsubParams.pending_messages_ttlGossipsubParams.prune_back_offGossipsubParams.px_peers_countGossipsubParams.time_to_liveGossipsubParams.unsubscribe_back_off
- libp2p.tools.utils module
- Module contents
- Subpackages
- libp2p.transport package
- Subpackages
- libp2p.transport.tcp package
- libp2p.transport.quic package
- Connection ID Management
- Submodules
- libp2p.transport.quic.config module
- libp2p.transport.quic.connection module
- libp2p.transport.quic.exceptions module
- libp2p.transport.quic.listener module
- libp2p.transport.quic.security module
- libp2p.transport.quic.stream module
- libp2p.transport.quic.transport module
- libp2p.transport.quic.utils module
- Module contents
- libp2p.transport.websocket package
- Submodules
- libp2p.transport.websocket.connection module
- libp2p.transport.websocket.listener module
- libp2p.transport.websocket.manager module
- libp2p.transport.websocket.multiaddr_utils module
- libp2p.transport.websocket.proxy module
- libp2p.transport.websocket.proxy_env module
- libp2p.transport.websocket.transport module
- Module contents
- libp2p.transport.webrtc package
- Subpackages
- Submodules
- libp2p.transport.webrtc.certificate module
- libp2p.transport.webrtc.config module
- libp2p.transport.webrtc.connection module
- libp2p.transport.webrtc.constants module
- libp2p.transport.webrtc.exceptions module
- libp2p.transport.webrtc.listener module
- libp2p.transport.webrtc.multiaddr_utils module
- libp2p.transport.webrtc.noise_handshake module
- libp2p.transport.webrtc.private_listener module
- libp2p.transport.webrtc.private_transport module
- libp2p.transport.webrtc.sdp module
- libp2p.transport.webrtc.signaling module
- libp2p.transport.webrtc.stream module
- libp2p.transport.webrtc.transport module
- Module contents
- libp2p.transport.webtransport package
WebTransportCertManagerWebTransportCertificateWebTransportCertificateErrorWebTransportConfigWebTransportConnectionErrorWebTransportErrorWebTransportHandshakeErrorWebTransportMultiaddrErrorWebTransportStreamErrorWebTransportTransportbuild_webtransport_multiaddr()extract_certhashes()fingerprint_from_multibase()is_webtransport_multiaddr()multihash_from_der()multihash_from_multibase()parse_webtransport_multiaddr()- Submodules
- libp2p.transport.webtransport.config module
- libp2p.transport.webtransport.transport module
- libp2p.transport.webtransport.listener module
- libp2p.transport.webtransport.connection module
- Submodules
- libp2p.transport.exceptions module
- libp2p.transport.upgrader module
- Module contents
DemultiplexedConnTypeDemultiplexedListenerPortDemultiplexerTCPTransportManagerTransportManager.add_listen_addr()TransportManager.add_transport()TransportManager.add_transports()TransportManager.close_all()TransportManager.get_transports()TransportManager.has_transport_for()TransportManager.listen_on()TransportManager.set_background_nursery()TransportManager.set_swarm()TransportManager.transport_for_dialing()TransportManager.transport_for_listening()
WebsocketTransportWebsocketTransport.can_dial()WebsocketTransport.can_listen()WebsocketTransport.create_listener()WebsocketTransport.dial()WebsocketTransport.get_connections()WebsocketTransport.get_listeners()WebsocketTransport.get_stats()WebsocketTransport.protocols()WebsocketTransport.resolve()WebsocketTransport.set_background_nursery()WebsocketTransport.set_peer_id()
identify_conn_type()
- Subpackages
- libp2p.utils package
- Submodules
- libp2p.utils.logging module
- libp2p.utils.multiaddr_utils module
- libp2p.utils.varint module
decode_uvarint()decode_uvarint_from_stream()decode_varint_from_bytes()decode_varint_with_size()encode_delim()encode_uvarint()encode_varint_prefixed()read_delim()read_length_prefixed_protobuf()read_varint_prefixed_bytes()read_varint_prefixed_bytes_limited()read_varint_prefixed_bytes_sync()
- libp2p.utils.version module
- libp2p.utils.paths module
- libp2p.utils.address_validation module
- libp2p.utils.dns_utils module
- libp2p.metrics package
Submodules
libp2p.abc module
- class libp2p.abc.AbstractSecureConn
Bases:
ABCAbstract interface for secure connections.
Represents a secured connection object, including details about the security involved in the connection.
- abstract get_local_private_key() PrivateKey
Retrieve the local peer’s private key.
- Returns:
The private key of the local peer.
- class libp2p.abc.CMInfo(low_watermark: int, high_watermark: int, connected_count: int, grace_period: float, last_trim: float | None)
Bases:
objectUnified snapshot of connection manager state.
Equivalent to go-libp2p’s connmgr.CMInfo snapshot returned by BasicConnMgr.GetInfo() — providing a single call-site for all watermark / live-count / grace / last-trim data needed by operators and metrics exporters.
Attributes
- low_watermarkint
Target connection count after pruning.
- high_watermarkint
Connection count that triggers pruning.
- connected_countint
Current number of live connections.
- grace_periodfloat
Seconds a new connection is exempt from pruning.
- last_trimfloat | None
Unix timestamp of the most recent prune cycle, or None if the connection count has never exceeded the high watermark.
- class libp2p.abc.IAddrBook
Bases:
ABCInterface for an address book.
Provides methods for managing peer addresses.
- abstract add_addr(peer_id: ID, addr: Multiaddr, ttl: int) None
Add a single address for a given peer.
This method calls
add_addrs(peer_id, [addr], ttl).Parameters
- peer_idID
The peer identifier for which to add the address.
- addrMultiaddr
The multiaddress of the peer.
- ttlint
The time-to-live for the address, after which it is no longer valid.
- abstract add_addrs(peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) None
Add multiple addresses for a given peer, all with the same TTL.
If an address already exists with a longer TTL, no action should be taken. If an address exists with a shorter TTL, its TTL should be extended to match the provided TTL.
Parameters
- peer_idID
The peer identifier for which to add addresses.
- addrsSequence[Multiaddr]
A sequence of multiaddresses to add.
- ttlint
The time-to-live for the addresses, after which they become invalid.
- abstract addrs(peer_id: ID) list[Multiaddr]
Retrieve all known and valid addresses for the specified peer.
Parameters
- peer_idID
The peer identifier whose addresses are requested.
Returns
- list[Multiaddr]
A list of valid multiaddresses for the given peer.
- class libp2p.abc.ICertifiedAddrBook
Bases:
ABCInterface for a certified address book.
Provides methods for managing signed peer records
- abstract consume_peer_record(envelope: Envelope, ttl: int) bool
Accept and store a signed PeerRecord, unless it’s older than the one already stored.
This function: - Extracts the peer ID and sequence number from the envelope - Rejects the record if it’s older (lower seq) - Updates the stored peer record and replaces associated addresses if accepted
Parameters
- envelope:
Signed envelope containing a PeerRecord.
- ttl:
Time-to-live for the included multiaddrs (in seconds).
- abstract get_peer_record(peer_id: ID) Envelope | None
Retrieve the most recent signed PeerRecord Envelope for a peer, if it exists and is still relevant.
First, it runs cleanup via maybe_delete_peer_record to purge stale data. Then it checks whether the peer has valid, unexpired addresses before returning the associated envelope.
Parameters
- peer_idID
The peer to look up.
- abstract maybe_delete_peer_record(peer_id: ID) None
Delete the signed peer record for a peer if it has no know (non-expired) addresses.
This is a garbage collection mechanism: if all addresses for a peer have expired or been cleared, there’s no point holding onto its signed Envelope
Parameters
- peer_idID
The peer whose record we may delete.
- class libp2p.abc.IContentRouting
Bases:
ABCInterface for content routing.
Provides methods to advertise and search for content providers.
- abstract find_provider_iter(cid: bytes, count: int) Iterable[PeerInfo]
Search for peers that can provide the content identified by the given CID.
Parameters
- cidbytes
The content identifier.
- countint
The maximum number of providers to return.
Returns
- Iterable[PeerInfo]
An iterator of PeerInfo objects for peers that provide the content.
- abstract provide(cid: bytes, announce: bool = True) None
Advertise that the host can provide content identified by the given CID.
If
announceis True, the content is announced; otherwise, it is only recorded locally.Parameters
- cidbytes
The content identifier.
- announcebool, optional
Whether to announce the provided content (default is True).
- class libp2p.abc.IEnvelope
Bases:
ABC- abstract equal(other: Any) bool
Compare this Envelope with another for structural equality.
Two envelopes are considered equal if: - They have the same public key - The payload type and payload bytes match - Their signatures are identical
- Parameters:
other – Another object to compare.
- Returns:
True if equal, False otherwise.
- abstract marshal_envelope() bytes
Serialize this Envelope into its protobuf wire format.
Converts all envelope fields into a pb.Envelope protobuf message and returns the serialized bytes.
- Returns:
Serialized envelope as bytes.
- abstract record() PeerRecord
Lazily decode and return the embedded PeerRecord.
This method unmarshals the payload bytes into a PeerRecord instance, using the registered codec to identify the type. The decoded result is cached for future use.
- Returns:
Decoded PeerRecord object.
- Raises:
Exception – If decoding fails or payload type is unsupported.
- abstract validate(domain: str) None
Verify the envelope’s signature within the given domain scope.
This ensures that the envelope has not been tampered with and was signed under the correct usage context.
- Parameters:
domain – Domain string that contextualizes the signature.
- Raises:
ValueError – If the signature is invalid.
- class libp2p.abc.IHost
Bases:
ABCInterface for the host.
Provides methods for retrieving host information, managing connections and streams, and running the host.
- abstract property conn_manager: TagStore
Return the connection manager (TagStore) for this host.
Provides access to tag_peer, untag_peer, upsert_tag, protect, unprotect, and is_protected without going through the network layer — matching go-libp2p’s h.ConnManager().
Returns
- TagStore
The tag store managing peer priorities and protections.
- abstract async connect(peer_info: PeerInfo) None
Establish a connection to the specified peer.
This method ensures there is a connection between the host and the peer represented by the provided peer information. It also absorbs the addresses from
peer_infointo the host’s internal peerstore. If no active connection exists, the host will dial the peer and block until a connection is established or an error occurs.Parameters
- peer_infoPeerInfo
The peer information of the peer to connect to.
- abstract async disconnect(peer_id: ID) None
Disconnect from the specified peer.
Parameters
- peer_idID
The identifier of the peer to disconnect from.
- abstract export_health_metrics(format: str = 'json') str
Export health metrics in specified format.
Parameters
- formatstr
The format to export metrics in. Supported: “json”, “prometheus”
Returns
- str
The health metrics in the requested format. Returns empty string or object if health monitoring is disabled.
Note
This method is marked as abstract to ensure all host implementations provide health monitoring support. However, implementations may return empty strings when health monitoring is disabled, effectively providing “optional” health monitoring with a consistent API.
- abstract get_addrs() list[Multiaddr]
Return the addresses this host advertises to other peers.
These may differ from the actual listen addresses when
announce_addrsis configured. Each address includes a/p2p/{peer_id}suffix.Returns
- list[Multiaddr]
A list of advertised multiaddresses, each with a
/p2p/{peer_id}suffix.
- abstract get_connected_peers() list[ID]
Retrieve the identifiers of peers currently connected to the host.
Returns
- list[ID]
A list of peer identifiers.
- abstract get_connection_health(peer_id: ID) dict[str, Any]
Get health summary for peer connections.
Parameters
- peer_idID
The identifier of the peer to get health information for.
Returns
- dict[str, Any]
A dictionary containing health metrics for the peer’s connections. Returns empty dict if health monitoring is disabled or peer not found.
Note
This method is marked as abstract to ensure all host implementations provide health monitoring support. However, implementations may return empty dictionaries when health monitoring is disabled, effectively providing “optional” health monitoring with a consistent API.
- abstract async get_health_monitor_status() dict[str, Any]
Get status information about the health monitoring service.
Returns
- dict[str, Any]
A dictionary containing health monitor status information including: - enabled: Whether health monitoring is active - monitoring_task_started: Whether the monitoring task is running - check_interval_seconds: Health check interval - total_connections: Total number of connections - monitored_connections: Number of monitored connections - total_peers: Total number of peers - monitored_peers: Number of peers being monitored Returns {“enabled”: False} if health monitoring is disabled.
- abstract get_metrics_recv_channel() MemoryReceiveChannel[Any] | None
Returns the recving end of the channel, used for metric events
- abstract get_mux() Multiselect
Retrieve the muxer instance for the host.
Returns
- Any
The muxer instance of the host.
- abstract get_network() INetworkService
Retrieve the network service instance associated with the host.
Returns
- INetworkService
The network instance of the host.
- abstract get_network_health_summary() dict[str, Any]
Get overall network health summary.
- Returns:
- dict[str, Any]
A dictionary containing global health metrics across all connections. Returns empty dict if health monitoring is disabled.
- Note:
This method is marked as abstract to ensure all host implementations provide health monitoring support. However, implementations may return empty dictionaries when health monitoring is disabled, effectively providing “optional” health monitoring with a consistent API.
- abstract get_peerstore() IPeerStore
- Returns:
the peerstore of the host
- abstract get_private_key() PrivateKey
Retrieve the private key of the host.
Returns
- PrivateKey
The private key belonging to the host.
- abstract get_public_key() PublicKey
Retrieve the public key of the host.
Returns
- PublicKey
The public key belonging to the host.
- abstract get_transport_addrs() list[Multiaddr]
Retrieve the raw multiaddr addresses this host is listening to, without the /p2p/{peer_id} suffix.
Returns
- list[Multiaddr]
A list of raw multiaddresses.
- abstract async initiate_autotls_procedure(public_ip: str | None = None) None
Initiate the ACME-AUTO-TLS-BROKER negotiation for TLS certificate
- abstract async new_stream(peer_id: ID, protocol_ids: Sequence[TProtocol]) INetStream
Create a new stream to the specified peer.
Parameters
- peer_idID
The identifier of the peer to connect.
- protocol_idsSequence[TProtocol]
A sequence of available protocol identifiers to use for the stream.
Returns
- INetStream
The newly created network stream.
- abstract remove_stream_handler(protocol_id: TProtocol) None
Remove the stream handler for the specified protocol.
Parameters
- protocol_idTProtocol
The protocol identifier to remove the handler for.
- abstract run(listen_addrs: Sequence[Multiaddr], *, task_status: Any = TASK_STATUS_IGNORED) AbstractAsyncContextManager[None]
Run the host and start listening on the specified multiaddresses.
Parameters
- listen_addrsSequence[Multiaddr]
A sequence of multiaddresses on which the host should listen.
- task_statusAny
Task status for trio nursery compatibility (ignored).
- abstract set_stream_handler(protocol_id: TProtocol, stream_handler: Callable[[object], Awaitable[None]]) None
Set the stream handler for the specified protocol.
Parameters
- protocol_idTProtocol
The protocol identifier used on the stream.
- stream_handlerStreamHandlerFn
The stream handler function to be set.
- abstract async upgrade_inbound_connection(raw_conn: IRawConnection, maddr: Multiaddr) IMuxedConn
Upgrade a raw inbound connection to a fully secure and multiplexed network connection for the given multiaddress.
Parameters
- raw_connIRawConnection
The inbound raw connection to upgrade.
- maddrMultiaddr
The multiaddress this connection arrived on.
Returns
- IMuxedConn
The upgraded and authenticated inbound muxed connection.
Raises
- SwarmException
If the upgrade process (security handshake or multiplexer negotiation) fails
- abstract async upgrade_outbound_connection(raw_conn: IRawConnection, peer_id: ID) INetConn
Upgrade a raw outbound connection to a fully secure and multiplexed network connection for the specified peer.
Parameters
- raw_connIRawConnection
The raw (unencrypted/unmultiplexed) connection to upgrade.
- peer_idID
The ID of the peer this connection is being established to.
Returns
- INetConn
The upgraded and authenticated network connection with security and multiplexing.
Raises
- SwarmException
If the upgrade process (security handshake or multiplexer negotiation) fails
- class libp2p.abc.IKeyBook
Bases:
ABCInterface for an key book.
Provides methods for managing cryptographic keys.
- abstract add_key_pair(peer_id: ID, key_pair: KeyPair) None
Adds the key pair for a specified peer
Parameters
- peer_idID
The peer identifier whose key pair is to be added
- key_pair: KeyPair
The key pair of the peer
- abstract add_privkey(peer_id: ID, privkey: PrivateKey) None
Adds the private key for a specified peer
Parameters
- peer_idID
The peer identifier whose private key is to be added
- privkey: PrivateKey
The private key of the peer
- abstract add_pubkey(peer_id: ID, pubkey: PublicKey) None
Adds the public key for a specified peer
Parameters
- peer_idID
The peer identifier whose public key is to be added
- pubkey: PublicKey
The public key of the peer
- abstract clear_keydata(peer_id: ID) None
Remove all stored keydata for the specified peer.
Parameters
- peer_idID
The peer identifier whose keys are to be removed.
- abstract privkey(peer_id: ID) PrivateKey
Returns the private key of the specified peer
Parameters
- peer_idID
The peer identifier whose private key is to be returned.
- class libp2p.abc.IListener
Bases:
ABCInterface for a network listener.
Provides methods for starting a listener, retrieving its addresses, and closing it.
- abstract get_addrs() tuple[Multiaddr, ...]
Retrieve the list of addresses on which the listener is active.
Returns
- tuple[Multiaddr, …]
A tuple of multiaddresses.
- abstract async listen(maddr: Multiaddr) None
Start listening on the specified multiaddress.
The listener manages its own background tasks internally and keeps them alive until
close()is called. Callers do not need to supply a nursery.Parameters
- maddrMultiaddr
The multiaddress on which to listen.
Raises
- Exception
Transport-specific listener exception, such as
OpenConnectionError(TCP/WebSocket) orQUICListenError(QUIC), if listening fails (e.g. missing/invalid port or failed start).
- class libp2p.abc.IMetrics
Bases:
ABCInterface for metrics of peer interaction.
Provides methods for managing the metrics.
- abstract clear_metrics(peer_id: ID) None
Clears the stored latency metrics for the specified peer.
Parameters
- peer_idID
The identifier of the peer whose latency metrics are to be cleared.
- abstract latency_EWMA(peer_id: ID) float
Returns the current latency value for the specified peer using Exponentially Weighted Moving Average (EWMA).
Parameters
- peer_idID
The identifier of the peer whose latency EWMA is to be returned.
- abstract record_latency(peer_id: ID, RTT: float) None
Records a new round-trip time (RTT) latency value for the specified peer using Exponentially Weighted Moving Average (EWMA).
Parameters
- peer_idID
The identifier of the peer for which latency is being recorded.
- RTTfloat
The round-trip time latency value to record.
- class libp2p.abc.IMultiselectClient
Bases:
ABCClient for multiselect negotiation.
Communicates with the receiver’s multiselect module to select a protocol for communication.
- abstract async handshake(communicator: IMultiselectCommunicator) None
Ensure that the client and multiselect module are using the same multiselect protocol.
Parameters
- communicatorIMultiselectCommunicator
The communicator used for negotiating the multiselect protocol.
Raises
- Exception
If there is a multiselect protocol ID mismatch.
- abstract async select_one_of(protocols: Sequence[TProtocol], communicator: IMultiselectCommunicator) TProtocol
Select one protocol from a sequence by communicating with the multiselect module.
For each protocol in the provided sequence, the client sends a selection message and expects the multiselect module to confirm the protocol. The first confirmed protocol is returned.
Parameters
- protocolsSequence[TProtocol]
The protocols to attempt selection.
- communicatorIMultiselectCommunicator
The communicator used for negotiating the protocol.
Returns
- TProtocol
The protocol selected by the multiselect module.
- abstract async try_select(communicator: IMultiselectCommunicator, protocol: TProtocol) TProtocol
Attempt to select the given protocol.
Parameters
- communicatorIMultiselectCommunicator
The communicator used to interact with the counterparty.
- protocolTProtocol
The protocol to select.
Returns
- TProtocol
The protocol if successfully selected.
Raises
- Exception
If protocol selection fails.
- class libp2p.abc.IMultiselectCommunicator
Bases:
ABCCommunicator helper for multiselect.
Ensures that both the client and multistream module follow the same multistream protocol.
- class libp2p.abc.IMultiselectMuxer
Bases:
ABCMultiselect module for protocol negotiation.
Responsible for responding to a multiselect client by selecting a protocol and its corresponding handler for communication.
- abstract add_handler(protocol: TProtocol, handler: Callable[[object], Awaitable[None]]) None
Store a handler for the specified protocol.
Parameters
- protocolTProtocol
The protocol name.
- handlerStreamHandlerFn
The handler function associated with the protocol.
- abstract get_protocols() tuple[TProtocol | None, ...]
Retrieve the protocols for which handlers have been registered.
Returns
- tuple[TProtocol, …]
A tuple of registered protocol names.
- abstract async negotiate(communicator: IMultiselectCommunicator) tuple[TProtocol | None, Callable[[object], Awaitable[None]] | None]
Negotiate a protocol selection with a multiselect client.
Parameters
- communicatorIMultiselectCommunicator
The communicator used to negotiate the protocol.
Returns
- tuple[TProtocol, StreamHandlerFn]
A tuple containing the selected protocol and its handler.
Raises
- Exception
If negotiation fails.
- class libp2p.abc.IMuxedConn(conn: ISecureConn, peer_id: ID)
Bases:
ABCInterface for a multiplexed connection.
References
https://github.com/libp2p/go-stream-muxer/blob/master/muxer.go
Attributes
- peer_id (ID):
The identifier of the connected peer.
- event_started (trio.Event):
An event that signals when the multiplexer has started.
- abstract async accept_stream() IMuxedStream
Accept a new multiplexed stream initiated by the remote peer.
- Returns:
A new instance of IMuxedStream.
- event_started: Event
- abstract get_connection_type() ConnectionType
Get connection type by delegating to secured_conn.
- abstract get_transport_addresses() list[Multiaddr]
Get transport addresses by delegating to secured_conn.
- abstract property is_closed: bool
Check if the connection is fully closed.
- Returns:
True if the connection is closed, otherwise False.
- abstract property is_established: bool
Check if the connection is fully established and ready for streams.
- Returns:
True if the connection is established, otherwise False.
- abstract property is_initiator: bool
Determine if this connection is the initiator.
- Returns:
True if this connection initiated the connection, otherwise False.
- abstract async open_stream() IMuxedStream
Create and open a new multiplexed stream.
- Returns:
A new instance of IMuxedStream.
- class libp2p.abc.IMuxedStream
Bases:
ReadWriteCloser,AsyncContextManager[IMuxedStream]Interface for a multiplexed stream.
Represents a stream multiplexed over a single connection.
Attributes
- muxed_conn (IMuxedConn):
The underlying multiplexed connection.
- muxed_conn: IMuxedConn
- abstract async reset() None
Reset the stream.
This method closes both ends of the stream, instructing the remote side to hang up.
- abstract set_deadline(ttl: int) None
Set a deadline for the stream.
- Parameters:
ttl – Time-to-live for the stream in seconds.
- Raises:
ValueError – if ttl is invalid (e.g. negative).
- class libp2p.abc.INetConn
Bases:
CloserInterface for a network connection.
Defines a network connection capable of creating and managing streams.
Attributes
- muxed_conn (IMuxedConn):
The underlying multiplexed connection.
- event_started (trio.Event):
Event signaling when the connection has started.
- event_started: Event
- abstract get_connection_type() ConnectionType
Get the type of connection (direct, relayed, etc.)
- abstract get_streams() tuple[INetStream, ...]
Retrieve all active streams associated with this connection.
- Returns:
A tuple containing instances of INetStream.
- abstract get_transport_addresses() list[Multiaddr]
Retrieve the actual transport addresses used by this connection.
Returns the real IP/port addresses, not peerstore addresses. For relayed connections, should include /p2p-circuit in the path.
- Returns:
A list of multiaddresses used by the transport.
- abstract property is_closed: bool
Check if the connection is fully closed.
- Returns:
True if the connection is closed, otherwise False.
- muxed_conn: IMuxedConn
- abstract async new_stream() INetStream
Create a new network stream over the connection.
- Returns:
A new instance of INetStream.
- class libp2p.abc.INetStream
Bases:
ReadWriteCloserInterface for a network stream.
Represents a network stream operating over a multiplexed connection.
Attributes
- muxed_conn (IMuxedConn):
The multiplexed connection that this stream belongs to.
- abstract get_protocol() TProtocol | None
Retrieve the protocol identifier for the stream.
- Returns:
The protocol ID associated with the stream.
- muxed_conn: IMuxedConn
- class libp2p.abc.INetwork
Bases:
ABCInterface for the network.
Provides methods for managing connections, streams, and listeners.
Attributes
- peerstoreIPeerStore
The peer store for managing peer information.
- connectionsdict[ID, list[INetConn]]
A mapping of peer IDs to lists of network connections (multiple connections per peer).
- listenersdict[str, IListener]
A mapping of listener identifiers to listener instances.
- abstract async close_peer(peer_id: ID) None
Close the connection to the specified peer.
Parameters
- peer_idID
The identifier of the peer whose connection should be closed.
- abstract async dial_peer(peer_id: ID) list[INetConn]
Create connections to the specified peer with load balancing.
Parameters
- peer_idID
The identifier of the peer to dial.
Returns
- list[INetConn]
List of established connections to the peer.
Raises
- SwarmException
If an error occurs during dialing.
- abstract export_health_metrics(format: str = 'json') str
Export health metrics in specified format.
Parameters
- formatstr
The format to export metrics in. Supported: “json”, “prometheus”
Returns
- str
The health metrics in the requested format. Returns empty string or object if health monitoring is disabled.
- abstract get_connection(peer_id: ID) INetConn | None
Get single connection for backward compatibility.
Parameters
- peer_idID
The peer ID to get a connection for.
Returns
- INetConn | None
The first available connection, or None if no connections exist.
- abstract get_connections(peer_id: ID | None = None) list[INetConn]
Get connections for peer (like JS getConnections, Go ConnsToPeer).
Parameters
- peer_idID | None
The peer ID to get connections for. If None, returns all connections.
Returns
- list[INetConn]
List of connections to the specified peer, or all connections if peer_id is None.
- abstract get_connections_map() dict[ID, list[INetConn]]
Get all connections map (like JS getConnectionsMap).
Returns
- dict[ID, list[INetConn]]
The complete mapping of peer IDs to their connection lists.
- abstract get_global_health_summary() dict[str, Any]
Get global health summary across all peers.
- Returns:
- dict[str, Any]
A dictionary containing global health metrics across all connections. Returns empty dict if health monitoring is disabled.
- Note:
This method is marked as abstract to ensure all network implementations provide health monitoring support. However, implementations may return empty dictionaries when health monitoring is disabled, effectively providing “optional” health monitoring with a consistent API.
- abstract async get_health_monitor_status() dict[str, Any]
Get status information about the health monitoring service.
Returns
- dict[str, Any]
A dictionary containing health monitor status information including: - enabled: Whether health monitoring is active - monitoring_task_started: Whether the monitoring task is running - check_interval_seconds: Health check interval - total_connections: Total number of connections - monitored_connections: Number of monitored connections - total_peers: Total number of peers - monitored_peers: Number of peers being monitored Returns {“enabled”: False} if health monitoring is disabled.
- abstract get_peer_health_summary(peer_id: ID) dict[str, Any]
Get health summary for a specific peer.
Parameters
- peer_idID
The identifier of the peer to get health information for.
Returns
- dict[str, Any]
A dictionary containing health metrics for the peer’s connections. Returns empty dict if health monitoring is disabled or peer not found.
Note
This method is marked as abstract to ensure all network implementations provide health monitoring support. However, implementations may return empty dictionaries when health monitoring is disabled, effectively providing “optional” health monitoring with a consistent API.
- abstract get_peer_id() ID
Retrieve the peer identifier for this network.
Returns
- ID
The identifier of this peer.
- abstract async listen(*multiaddrs: Multiaddr) bool
Start listening on one or more multiaddresses.
Parameters
- multiaddrsSequence[Multiaddr]
One or more multiaddresses on which to start listening.
Returns
- bool
True if at least one listener started successfully, otherwise False.
- abstract async new_stream(peer_id: ID) INetStream
Create a new network stream to the specified peer.
Parameters
- peer_idID
The identifier of the destination peer.
Returns
- INetStream
The newly created network stream.
- peerstore: IPeerStore
- abstract register_notifee(notifee: INotifee) None
Register a notifee instance to receive network events.
Parameters
- notifeeINotifee
An object implementing the INotifee interface.
- abstract remove_notifee(notifee: INotifee) None
Unregister a notifee instance so it stops receiving network events.
Parameters
- notifeeINotifee
The notifee previously passed to
register_notifee.
- abstract set_stream_handler(stream_handler: Callable[[object], Awaitable[None]]) None
Set the stream handler for incoming streams.
Parameters
- stream_handlerStreamHandlerFn
The handler function to process incoming streams.
- abstract async upgrade_inbound_raw_conn(raw_conn: IRawConnection, maddr: Multiaddr) IMuxedConn
Secure and upgrade a raw inbound connection to a multiplexed network connection
Parameters
- raw_connIRawConnection
The incoming raw connection to upgrade.
- maddrMultiaddr
The multiaddress on which the connection was received.
Returns
- IMuxedConn
The upgraded, secure, and multiplexed network connection.
Raises
- SwarmException
If upgrading security or multiplexing the connection fails.
- abstract async upgrade_outbound_raw_conn(raw_conn: IRawConnection, peer_id: ID) INetConn
Secure and upgrade a raw outbound connection to a multiplexed network connection
Parameters
- raw_connIRawConnection
The raw connection to upgrade.
- peer_idID
The peer to which this connection is established.
Returns
- INetConn
The upgraded, secure, and multiplexed network connection.
Raises
- SwarmException
If upgrading security or multiplexing the connection fails.
- class libp2p.abc.INetworkService
Bases:
INetwork,ServiceAPIInterface for a network service with connection management capabilities.
Extends INetwork with go-libp2p style connection manager methods.
- abstract get_conn_mgr_info() CMInfo
Return a unified snapshot of connection manager state.
Provides a single call-site for watermarks, live connection count, grace period, and the timestamp of the last prune — matching go-libp2p’s BasicConnMgr.GetInfo().
Returns
- CMInfo
Snapshot of current connection manager state.
- abstract get_metrics() dict[str, int]
Get connection metrics (go-libp2p style).
Returns
- dict[str, int]
Connection metrics including total, inbound, and outbound counts.
- abstract get_tag_info(peer_id: ID) Any
Get the metadata associated with a peer.
Parameters
- peer_idID
The peer to get info for.
Returns
- Any
The tag info for the peer, or None if no tags recorded.
- abstract get_total_connections() int
Get total number of connections (inbound + outbound).
Returns
- int
Total number of active connections.
- abstract is_protected(peer_id: ID, tag: str = '') bool
Check if a peer is protected.
Parameters
- peer_idID
The peer to check.
- tagstr
If provided, check if protected by this specific tag.
Returns
- bool
True if the peer is protected.
- abstract protect(peer_id: ID, tag: str) None
Protect a peer from having its connection(s) pruned.
Parameters
- peer_idID
The peer to protect.
- tagstr
Protection tag.
- abstract tag_peer(peer_id: ID, tag: str, value: int) None
Tag a peer with a string, associating a weight with the tag.
Parameters
- peer_idID
The peer to tag.
- tagstr
The tag name.
- valueint
The weight/value associated with the tag.
- class libp2p.abc.INotifee
Bases:
ABCInterface for a network service.
Extends the INetwork interface with additional service management capabilities.
- abstract async closed_stream(network: INetwork, stream: INetStream) None
Called when a stream is closed.
Parameters
- networkINetwork
The network instance on which the stream was closed.
- streamINetStream
The stream that was closed.
- abstract async connected(network: INetwork, conn: INetConn) None
Called when a new connection is established.
Parameters
- networkINetwork
The network instance where the connection was established.
- connINetConn
The connection that was opened.
- abstract async disconnected(network: INetwork, conn: INetConn) None
Called when a connection is closed.
Parameters
- networkINetwork
The network instance where the connection was closed.
- connINetConn
The connection that was closed.
- abstract async listen(network: INetwork, multiaddr: Multiaddr) None
Called when a listener starts on a multiaddress.
Parameters
- networkINetwork
The network instance where the listener is active.
- multiaddrMultiaddr
The multiaddress on which the listener is listening.
- abstract async listen_close(network: INetwork, multiaddr: Multiaddr) None
Called when a listener stops listening on a multiaddress.
Parameters
- networkINetwork
The network instance where the listener was active.
- multiaddrMultiaddr
The multiaddress that is no longer being listened on.
- abstract async opened_stream(network: INetwork, stream: INetStream) None
Called when a new stream is opened.
Parameters
- networkINetwork
The network instance on which the stream was opened.
- streamINetStream
The stream that was opened.
- class libp2p.abc.IPeerData
Bases:
ABCInterface for managing peer data.
Provides methods for handling protocols, addresses, metadata, and keys associated with a peer.
- abstract add_addrs(addrs: Sequence[Multiaddr]) None
Add multiple multiaddresses to the peer’s data.
Parameters
- addrsSequence[Multiaddr]
A sequence of multiaddresses to add.
- ttl: inr
Time to live for the peer record
- abstract add_privkey(privkey: PrivateKey) None
Add a private key to the peer’s data.
Parameters
- privkeyPrivateKey
The private key to add.
- abstract add_protocols(protocols: Sequence[str]) None
Add one or more protocols to the peer’s data.
Parameters
- protocolsSequence[str]
A sequence of protocols to add.
- abstract add_pubkey(pubkey: PublicKey) None
Add a public key to the peer’s data.
Parameters
- pubkeyPublicKey
The public key to add.
- abstract clear_keydata() None
Clears all cryptographic key data associated with this peer, including both public and private keys.
- abstract first_supported_protocol(protocols: Sequence[str]) str
Returns the first protocol from the input list that this peer supports.
Parameters
- protocolsSequence[str]
A sequence of protocol strings to check for support.
Returns
- str
The first matching protocol, or an empty string if none are supported.
- abstract get_addrs() list[Multiaddr]
Retrieve all multiaddresses associated with the peer.
Returns
- list[Multiaddr]
A list of multiaddresses.
- abstract get_last_identified() int
Fetch the last identified timestamp
Returns
- last_identified_timestamp
The lastIdentified time of peer.
- abstract get_metadata(key: str) str | int | float | bool | None
Retrieve metadata for a given key.
Parameters
- keystr
The metadata key.
Returns
- MetadataValue
The metadata value for the given key.
Raises
- PeerDataError
If the key is not found.
- abstract get_privkey() PrivateKey
Retrieve the private key for the peer.
Returns
- PrivateKey
The private key of the peer.
Raises
- PeerDataError
If the private key is not found.
- abstract get_protocols() list[str]
Retrieve all protocols associated with the peer.
Returns
- list[str]
A list of protocols associated with the peer.
- abstract get_pubkey() PublicKey
Retrieve the public key for the peer.
Returns
- PublicKey
The public key of the peer.
Raises
- PeerDataError
If the public key is not found.
- abstract get_ttl() int
Get ttl value for the peer for validity check
Returns
- int
The ttl of the peer.
- abstract is_expired() bool
Check if the peer is expired based on last_identified and ttl
Returns
- bool
True, if last_identified + ttl > current_time
- abstract latency_EWMA() float
Returns the current EWMA value of the recorded latency.
Returns
- float
The current latency estimate based on EWMA.
- abstract put_metadata(key: str, val: str | int | float | bool | None) None
Store a metadata key-value pair for the peer.
Parameters
- keystr
The metadata key.
- valMetadataValue
The value to associate with the key.
- abstract record_latency(new_latency: float) None
Records a new latency measurement using Exponentially Weighted Moving Average (EWMA).
Parameters
- new_latencyfloat
The new round-trip time (RTT) latency value to incorporate into the EWMA calculation.
- abstract remove_protocols(protocols: Sequence[str]) None
Removes the specified protocols from this peer’s list of supported protocols.
Parameters
- protocolsSequence[str]
A sequence of protocol strings to be removed.
- abstract set_protocols(protocols: Sequence[str]) None
Set the protocols for the peer.
Parameters
- protocolsSequence[str]
A sequence of protocols to set.
- abstract set_ttl(ttl: int) None
Set ttl value for the peer for validity check
Parameters
- ttlint
The ttl for the peer.
- abstract supports_protocols(protocols: Sequence[str]) list[str]
Returns the list of protocols from the input sequence that are supported by this peer.
Parameters
- protocolsSequence[str]
A sequence of protocol strings to check against this peer’s supported protocols.
Returns
- list[str]
A list of protocol strings that are supported.
- class libp2p.abc.IPeerMetadata
Bases:
ABCInterface for managing peer metadata.
Provides methods for storing and retrieving metadata associated with peers.
- abstract clear_metadata(peer_id: ID) None
Remove all stored metadata for the specified peer.
Parameters
- peer_idID
The peer identifier whose metadata are to be removed.
- class libp2p.abc.IPeerRecord
Bases:
ABCInterface for a libp2p PeerRecord object.
A PeerRecord contains metadata about a peer such as its ID, public addresses, and a strictly increasing sequence number for versioning.
PeerRecords are used in signed routing Envelopes for secure peer data propagation.
- abstract codec() bytes
Return a binary codec prefix that identifies the PeerRecord type.
This is prepended in signed envelopes to allow type-safe decoding.
- abstract domain() str
Return the domain string for this record type.
Used in envelope validation to distinguish different record types.
- abstract equal(other: object) bool
Compare this PeerRecord with another for equality.
Two PeerRecords are considered equal if: - They have the same peer_id - Their seq numbers match - Their address lists are identical and ordered
- Parameters:
other – Object to compare with.
- Returns:
True if equal, False otherwise.
- abstract marshal_record() bytes
Serialize this PeerRecord into a byte string.
Used when signing or sealing the record in an envelope.
- Raises:
ValueError – if protobuf serialization fails.
- Returns:
Byte-encoded PeerRecord.
- abstract to_protobuf() PeerRecord
Convert this PeerRecord into its Protobuf representation.
- Raises:
ValueError – if serialization fails (e.g., invalid peer ID).
- Returns:
A populated protobuf PeerRecord message.
- class libp2p.abc.IPeerRouting
Bases:
ABCInterface for peer routing.
Provides methods to search for a specific peer.
- class libp2p.abc.IPeerStore
Bases:
IPeerMetadata,IAddrBook,ICertifiedAddrBook,IKeyBook,IMetrics,IProtoBookInterface for a peer store.
Provides methods for managing peer information including address management, protocol handling, and key storage.
- abstract add_addr(peer_id: ID, addr: Multiaddr, ttl: int) None
Add an address for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
- addrMultiaddr
The multiaddress to add.
- ttlint
The time-to-live for the record.
- abstract add_addrs(peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) None
Add multiple addresses for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
- addrsSequence[Multiaddr]
A sequence of multiaddresses to add.
- ttlint
The time-to-live for the record.
- abstract add_key_pair(peer_id: ID, key_pair: KeyPair) None
Add a key pair for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
- key_pairKeyPair
The key pair to add.
Raises
- PeerStoreError
If the peer already has a public or private key set.
- abstract add_privkey(peer_id: ID, privkey: PrivateKey) None
Add a private key for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
- privkeyPrivateKey
The private key to add.
Raises
- PeerStoreError
If the peer already has a private key set.
- abstract add_protocols(peer_id: ID, protocols: Sequence[str]) None
Add additional protocols for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
- protocolsSequence[str]
The protocols to add.
- abstract add_pubkey(peer_id: ID, pubkey: PublicKey) None
Add a public key for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
- pubkeyPublicKey
The public key to add.
Raises
- PeerStoreError
If the peer already has a public key set.
- abstract addrs(peer_id: ID) list[Multiaddr]
Retrieve the addresses for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
Returns
- list[Multiaddr]
A list of multiaddresses.
- abstract clear_addrs(peer_id: ID) None
Clear all addresses for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
- abstract clear_keydata(peer_id: ID) None
Remove all stored keydata for the specified peer.
Parameters
- peer_idID
The peer identifier whose keys are to be removed.
- abstract clear_metadata(peer_id: ID) None
Clears the stored latency metrics for the specified peer.
Parameters
- peer_idID
The identifier of the peer whose latency metrics are to be cleared.
- abstract clear_metrics(peer_id: ID) None
Clears the stored latency metrics for the specified peer.
Parameters
- peer_idID
The identifier of the peer whose latency metrics are to be cleared.
- abstract clear_protocol_data(peer_id: ID) None
Clears all protocol data associated with the specified peer.
Parameters
- peer_idID
The identifier of the peer whose protocol data will be cleared.
- abstract consume_peer_record(envelope: Envelope, ttl: int) bool
Accept and store a signed PeerRecord, unless it’s older than the one already stored.
This function: - Extracts the peer ID and sequence number from the envelope - Rejects the record if it’s older (lower seq) - Updates the stored peer record and replaces associated addresses if accepted
Parameters
- envelope:
Signed envelope containing a PeerRecord.
- ttl:
Time-to-live for the included multiaddrs (in seconds).
- abstract first_supported_protocol(peer_id: ID, protocols: Sequence[str]) str
Returns the first protocol from the input list that the peer supports.
Parameters
- peer_idID
The identifier of the peer to check for supported protocols.
- protocolsSequence[str]
A sequence of protocol strings to check.
Returns
- str
The first matching protocol string, or an empty string if none are supported.
- abstract get(peer_id: ID, key: str) str | int | float | bool | None
Retrieve the value associated with a key for a specified peer.
Parameters
- peer_idID
The identifier of the peer.
- keystr
The key to look up.
Returns
- MetadataValue
The value corresponding to the specified key.
Raises
- PeerStoreError
If the peer ID or value is not found.
- abstract get_peer_record(peer_id: ID) Envelope | None
Retrieve the most recent signed PeerRecord Envelope for a peer, if it exists and is still relevant.
First, it runs cleanup via maybe_delete_peer_record to purge stale data. Then it checks whether the peer has valid, unexpired addresses before returning the associated envelope.
Parameters
- peer_idID
The peer to look up.
- abstract get_protocols(peer_id: ID) list[str]
Retrieve the protocols associated with the specified peer.
Parameters
- peer_idID
The identifier of the peer.
Returns
- list[str]
A list of protocol identifiers.
Raises
- PeerStoreError
If the peer ID is not found.
- abstract has_peer(peer_id: ID) bool
Return True if
peer_idis known to this store.This MUST be O(1)-ish (in-memory map / single key lookup) and MUST NOT materialize the full peer list:
peer_ids()on persistent stores reconstructs and hashes every peer, which is far too expensive for hot paths (e.g. per-connection checks).Parameters
- peer_idID
The peer ID to check.
Returns
- bool
True if the peer is known to the store.
- abstract latency_EWMA(peer_id: ID) float
Returns the current latency value for the specified peer using Exponentially Weighted Moving Average (EWMA).
Parameters
- peer_idID
The identifier of the peer whose latency EWMA is to be returned.
- abstract maybe_delete_peer_record(peer_id: ID) None
Delete the signed peer record for a peer if it has no know (non-expired) addresses.
This is a garbage collection mechanism: if all addresses for a peer have expired or been cleared, there’s no point holding onto its signed Envelope
Parameters
- peer_idID
The peer whose record we may delete.
- abstract peer_ids() list[ID]
Retrieve all peer identifiers stored in the peer store.
Returns
- list[ID]
A list of all peer IDs in the store.
- abstract peer_info(peer_id: ID) PeerInfo
Retrieve the peer information for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
Returns
- PeerInfo
The peer information object for the given peer.
- abstract peers_with_addrs() list[ID]
Retrieve all peer identifiers with stored addresses.
Returns
- list[ID]
A list of peer IDs.
- abstract privkey(peer_id: ID) PrivateKey
Retrieve the private key for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
Returns
- PrivateKey
The private key of the peer.
Raises
- PeerStoreError
If the peer ID is not found.
- abstract pubkey(peer_id: ID) PublicKey
Retrieve the public key for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
Returns
- PublicKey
The public key of the peer.
Raises
- PeerStoreError
If the peer ID is not found.
- abstract put(peer_id: ID, key: str, val: str | int | float | bool | None) None
Store a key-value pair for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
- keystr
The key for the data.
- valMetadataValue
The value to store.
- abstract record_latency(peer_id: ID, RTT: float) None
Records a new round-trip time (RTT) latency value for the specified peer using Exponentially Weighted Moving Average (EWMA).
Parameters
- peer_idID
The identifier of the peer for which latency is being recorded.
- RTTfloat
The round-trip time latency value to record.
- abstract remove_protocols(peer_id: ID, protocols: Sequence[str]) None
Removes the specified protocols from the peer’s protocol list.
Parameters
- peer_idID
The identifier of the peer from which protocols will be removed.
- protocolsSequence[str]
A sequence of protocol strings to remove.
- abstract set_protocols(peer_id: ID, protocols: Sequence[str]) None
Set the protocols for the specified peer.
Parameters
- peer_idID
The identifier of the peer.
- protocolsSequence[str]
The protocols to set.
- abstract async start_cleanup_task(cleanup_interval: int = 3600) None
Start periodic cleanup of expired peer records and addresses.
- abstract supports_protocols(peer_id: ID, protocols: Sequence[str]) list[str]
Returns the list of protocols from the input sequence that the peer supports.
Parameters
- peer_idID
The identifier of the peer to check for protocol support.
- protocolsSequence[str]
A sequence of protocol strings to check against the peer’s supported protocols.
- class libp2p.abc.IPerf
Bases:
ABCInterface for the perf protocol service.
Spec: https://github.com/libp2p/specs/blob/master/perf/perf.md
- abstract measure_performance(multiaddr: Multiaddr, send_bytes: int, recv_bytes: int) AsyncIterator[Any]
Measure transfer performance to a remote peer.
Parameters
- multiaddrMultiaddr
The address of the remote peer to test against.
- send_bytesint
Number of bytes to upload to the remote peer.
- recv_bytesint
Number of bytes to request the remote peer to send back.
Yields
- PerfOutput
Progress reports during the transfer, with a final summary at the end.
- class libp2p.abc.IProtoBook
Bases:
ABCInterface for a protocol book.
Provides methods for managing the list of supported protocols.
- abstract add_protocols(peer_id: ID, protocols: Sequence[str]) None
Adds the given protocols to the specified peer’s protocol list.
Parameters
- peer_idID
The identifier of the peer to which protocols will be added.
- protocolsSequence[str]
A sequence of protocol strings to add.
- abstract clear_protocol_data(peer_id: ID) None
Clears all protocol data associated with the specified peer.
Parameters
- peer_idID
The identifier of the peer whose protocol data will be cleared.
- abstract first_supported_protocol(peer_id: ID, protocols: Sequence[str]) str
Returns the first protocol from the input list that the peer supports.
Parameters
- peer_idID
The identifier of the peer to check for supported protocols.
- protocolsSequence[str]
A sequence of protocol strings to check.
Returns
- str
The first matching protocol string, or an empty string if none are supported.
- abstract get_protocols(peer_id: ID) list[str]
Returns the list of protocols associated with the specified peer.
Parameters
- peer_idID
The identifier of the peer whose supported protocols are to be returned.
- abstract remove_protocols(peer_id: ID, protocols: Sequence[str]) None
Removes the specified protocols from the peer’s protocol list.
Parameters
- peer_idID
The identifier of the peer from which protocols will be removed.
- protocolsSequence[str]
A sequence of protocol strings to remove.
- abstract set_protocols(peer_id: ID, protocols: Sequence[str]) None
Replaces the existing protocols of the specified peer with the given list.
Parameters
- peer_idID
The identifier of the peer whose protocols are to be set.
- protocolsSequence[str]
A sequence of protocol strings to assign.
- abstract supports_protocols(peer_id: ID, protocols: Sequence[str]) list[str]
Returns the list of protocols from the input sequence that the peer supports.
Parameters
- peer_idID
The identifier of the peer to check for protocol support.
- protocolsSequence[str]
A sequence of protocol strings to check against the peer’s supported protocols.
- class libp2p.abc.IPubsub
Bases:
ServiceAPIInterface for the pubsub system.
Provides properties and methods to manage topics, subscriptions, and message publishing.
- abstract property my_id: ID
Retrieve the identifier for this pubsub instance.
Returns
- ID
The pubsub identifier.
- abstract property protocols: tuple[TProtocol, ...]
Retrieve the protocols used by the pubsub system.
Returns
- tuple[TProtocol, …]
A tuple of protocol identifiers.
- abstract async publish(topic_id: str | list[str], data: bytes) None
Publish a message to a topic or multiple topics.
Parameters
- topic_idstr | list[str]
The identifier of the topic (str) or topics (list[str]).
- databytes
The data to publish.
- abstract remove_topic_validator(topic: str) None
Remove the validator for a specific topic.
Parameters
- topicstr
The topic whose validator should be removed.
- abstract set_topic_validator(topic: str, validator: Callable[[ID, Message], bool] | Callable[[ID, Message], Awaitable[bool]], is_async_validator: bool) None
Set a validator for a specific topic.
Parameters
- topicstr
The topic for which to set the validator.
- validatorValidatorFn
The validator function.
- is_async_validatorbool
Whether the validator is asynchronous.
- abstract async subscribe(topic_id: str) ISubscriptionAPI
Subscribe to a topic.
Parameters
- topic_idstr
The identifier of the topic to subscribe to.
Returns
- ISubscriptionAPI
An object representing the subscription.
- abstract property topic_ids: KeysView[str]
Retrieve the set of topic identifiers.
Returns
- KeysView[str]
A view of the topic identifiers.
- abstract async unsubscribe(topic_id: str) None
Unsubscribe from a topic.
Parameters
- topic_idstr
The identifier of the topic to unsubscribe from.
- abstract async wait_for_peer(peer_id: ID, timeout: float = 5.0) None
Wait until a pubsub stream with the given peer has been established.
This method blocks until the given peer has been added to the pubsub peers map, indicating that a pubsub protocol stream exists. Use this instead of arbitrary trio.sleep() calls to avoid race conditions.
The implementation uses an event-based approach with
trio.Eventso the task consumes zero CPU while waiting.Parameters
- peer_idID
The identifier of the peer to wait for.
- timeoutfloat
Maximum time to wait in seconds. Defaults to 5.0.
Raises
- trio.TooSlowError
If the peer stream is not established within the timeout period.
Example:
await connect(host1, host2) await pubsub1.wait_for_peer(host2.get_id()) # Now safe to publish or check peer_topics
- abstract async wait_for_subscription(peer_id: ID, topic_id: str, timeout: float = 5.0) None
Wait until a specific peer has subscribed to a topic.
This method blocks until the given peer appears in the peer_topics map for the specified topic, indicating that they have sent a subscription message. Use this instead of arbitrary trio.sleep() calls to avoid race conditions.
The implementation uses an event-based approach with
trio.Eventso the task consumes zero CPU while waiting.Parameters
- peer_idID
The identifier of the peer to wait for.
- topic_idstr
The topic to check subscription for.
- timeoutfloat
Maximum time to wait in seconds. Defaults to 5.0.
Raises
- trio.TooSlowError
If the peer does not subscribe within the timeout period.
Example:
await connect(host1, host2) await pubsub1.wait_for_subscription(host2.get_id(), "my-topic") # Now safe to assert subscription state
- class libp2p.abc.IPubsubRouter
Bases:
ABCInterface for a pubsub router.
Provides methods to manage protocol support, peer attachments, and message handling for pubsub.
- abstract add_peer(peer_id: ID, protocol_id: TProtocol | None) None
Notify the router that a new peer has connected.
Parameters
- peer_idID
The identifier of the peer.
- protocol_idTProtocol
The protocol the peer supports (e.g., floodsub, gossipsub).
- abstract attach(pubsub: Pubsub) None
Attach the router to a newly initialized PubSub instance.
Parameters
- pubsubPubsub
The PubSub instance to attach to.
- async flush_pending_messages(peer_id: ID) None
Send messages the router queued while the peer was still connecting.
Optional hook, invoked once the outbound stream for the peer is registered and again when the peer announces a new subscription. Routers that do not queue during connection setup keep the no-op.
Parameters
- peer_idID
The peer whose queued messages should be sent.
- abstract get_protocols() list[TProtocol]
Retrieve the list of protocols supported by the router.
Returns
- list[TProtocol]
A list of supported protocol identifiers.
- abstract async handle_rpc(rpc: RPC, sender_peer_id: ID) None
Process an RPC message received from a peer.
Parameters
- rpcrpc_pb2.RPC
The RPC message to process.
- sender_peer_idID
The identifier of the peer that sent the message.
- abstract async join(topic: str) None
Join a topic to receive and forward messages.
Parameters
- topicstr
The topic to join.
- abstract async leave(topic: str) None
Leave a topic, stopping message forwarding for that topic.
Parameters
- topicstr
The topic to leave.
- async on_peer_subscribed(peer_id: ID, topic: str) None
React to a newly observed peer subscription for a topic.
Optional hook, invoked when a peer announces a subscription we had not previously recorded. GossipSub uses this for event-driven mesh first-fill (GRAFT) so publish does not wait on the next heartbeat. Heartbeat still owns ongoing mesh maintenance. Routers that do not use a mesh keep the no-op.
Parameters
- peer_idID
The peer that subscribed.
- topicstr
The topic they subscribed to.
- abstract async publish(msg_forwarder: ID, pubsub_msg: Message) None
Forward a validated pubsub message.
Parameters
- msg_forwarderID
The identifier of the message sender.
- pubsub_msgrpc_pb2.Message
The pubsub message to forward.
- abstract remove_peer(peer_id: ID) None
Notify the router that a peer has disconnected.
Parameters
- peer_idID
The identifier of the peer to remove.
- async send_recent_messages(peer_id: ID, topic: str) None
Replay recently seen messages for a topic to a peer.
Optional hook, invoked when a peer that is subscribed to the topic becomes writable. Routers without a message cache keep the no-op.
Parameters
- peer_idID
The peer to replay messages to.
- topicstr
The topic to replay messages for.
- class libp2p.abc.IRawConnection
Bases:
ReadWriteCloserInterface for a raw connection.
This interface provides a basic reader/writer connection abstraction.
Attributes
- is_initiator (bool):
True if the local endpoint initiated the connection.
- abstract get_connection_type() ConnectionType
Get the type of connection (direct, relayed, etc.)
- class libp2p.abc.ISecureConn
Bases:
AbstractSecureConn,IRawConnectionInterface for a secure connection.
Combines secure connection functionalities with raw I/O operations.
- class libp2p.abc.ISecureTransport
Bases:
ABCInterface for a security transport.
Used to secure connections by performing handshakes and negotiating secure channels between peers.
References
https://github.com/libp2p/go-conn-security/blob/master/interface.go
- abstract async secure_inbound(conn: IRawConnection) ISecureConn
Secure an inbound connection (when we are not the initiator).
This method secures the connection by either performing local operations or communicating with the opposing node.
Parameters
- connIRawConnection
The raw connection to secure.
Returns
- ISecureConn
The secured connection instance.
- abstract async secure_outbound(conn: IRawConnection, peer_id: ID) ISecureConn
Secure an outbound connection (when we are the initiator).
This method secures the connection by either performing local operations or communicating with the opposing node.
Parameters
- connIRawConnection
The raw connection to secure.
- peer_idID
The identifier of the remote peer.
Returns
- ISecureConn
The secured connection instance.
- class libp2p.abc.ISubscriptionAPI
Bases:
AsyncContextManager[ISubscriptionAPI],AsyncIterable[Message]Interface for a subscription in pubsub.
Combines asynchronous context management and iteration over messages.
- class libp2p.abc.ITransport
Bases:
ABCInterface for a transport.
Provides methods for dialing peers and creating listeners on a transport.
- abstract can_dial(maddr: Multiaddr) bool
Return True if this transport can dial the given multiaddr.
The TransportManager calls this method before attempting a dial to route the connection to the correct transport.
Parameters
- maddrMultiaddr
The multiaddress to check.
Returns
- bool
True if this transport can dial maddr, False otherwise.
Examples
TCP returns True for
/ip4/127.0.0.1/tcp/4001WebSocket returns True for
/ip4/127.0.0.1/tcp/8080/wsQUIC returns True for
/ip4/127.0.0.1/udp/4001/quic-v1
- abstract can_listen(maddr: Multiaddr) bool
Return True if this transport can listen on the given multiaddr.
Often identical to
can_dial()but may differ — e.g. a relay transport can dial outbound but cannot accept inbound connections.Parameters
- maddrMultiaddr
The multiaddress to check.
Returns
- bool
True if this transport can listen on maddr, False otherwise.
- abstract create_listener(handler_function: Callable[[ReadWriteCloser], Awaitable[None]]) IListener
Create a listener on the transport.
Parameters
- handler_functionTHandler
A function that is called when a new connection is received. The function should accept a connection (that implements the connection interface) as its argument.
Returns
- IListener
A listener instance.
- abstract async dial(maddr: Multiaddr) IRawConnection
Dial a peer on the specified multiaddress.
Parameters
- maddrMultiaddr
The multiaddress of the peer to dial.
Returns
- IRawConnection
The raw connection established to the peer.
- abstract protocols() list[str]
Return the list of multiaddr protocol names this transport handles.
Used by
TransportManageras a fast pre-filter: if the multiaddr contains none of the listed protocol names,can_dial/can_listenare not called.Returns
- list[str]
Protocol name strings, e.g.
["tcp"],["ws", "wss"], or["quic", "quic-v1"].
libp2p.exceptions module
- exception libp2p.exceptions.MultiError(errors: Sequence[Exception])
Bases:
BaseLibp2pErrorA combined error that wraps multiple exceptions into a single error object. This error is raised when multiple exceptions need to be reported together, typically in scenarios where parallel operations or multiple validations fail.
Example:
>>> from libp2p.exceptions import MultiError >>> errors = [ ... ValueError("Invalid input"), ... TypeError("Wrong type"), ... RuntimeError("Operation failed") ... ] >>> multi_error = MultiError(errors) >>> print(multi_error) Error 1: Invalid input Error 2: Wrong type Error 3: Operation failed
Note:
The string representation of this error will number and list all contained errors sequentially, making it easier to identify individual issues in complex error scenarios.
- exception libp2p.exceptions.ParseError
Bases:
BaseLibp2pError
- exception libp2p.exceptions.ValidationError
Bases:
BaseLibp2pErrorRaised when something does not pass a validation check.
libp2p.custom_types module
Module contents
Libp2p Python implementation.
- libp2p.create_mplex_muxer_option() Mapping[TProtocol, type[object]]
Returns muxer options with Mplex as the primary choice.
- Returns:
Muxer options with Mplex first
- libp2p.create_yamux_muxer_option() Mapping[TProtocol, type[object]]
Returns muxer options with Yamux as the primary choice.
- Returns:
Muxer options with Yamux first
- libp2p.generate_new_ed25519_identity() KeyPair
Generate a new Ed25519 identity key pair.
Ed25519 is preferred for better interoperability with other libp2p implementations (e.g., Rust, Go) which often disable RSA support.
- libp2p.generate_peer_id_from(key_pair: KeyPair) ID
Generate a deterministic peer ID from a keypair.
The peer ID is derived from the public key, so the same keypair will always produce the same peer ID. This enables identity persistence: if you save and reuse the same keypair, you’ll get the same peer ID.
- Parameters:
key_pair – The keypair to generate a peer ID from
- Returns:
A deterministic peer ID
- libp2p.get_default_muxer() str
Returns the currently selected default muxer.
- Returns:
Either “YAMUX” or “MPLEX”
- libp2p.get_default_muxer_options() Mapping[TProtocol, type[object]]
Returns the default muxer options based on the current default muxer setting.
- Returns:
Muxer options with the preferred muxer first
- libp2p.load_keypair(type: str = 'ed25519') KeyPair | None
Load a private key from disk and reconstruct its KeyPair (legacy helper).
Currently supports only Ed25519 keys from the fixed PEM path used by
save_keypair. Preferload_identityorFileSystemKeyStore.getfor protobuf-based persistence at arbitrary paths.- Parameters:
type – Type of key to load (default: “ed25519”).
- Returns:
KeyPair object if found, or None.
- Raises:
ValueError – if an unsupported key type is provided.
- libp2p.new_host(key_pair: KeyPair | None = None, key_pair_provider: Callable[[], KeyPair] | None = None, keystore: FileSystemKeyStore | None = None, identity_name: str = 'default', auto_persist: bool | None = None, muxer_opt: TMuxerOptions | None = None, sec_opt: TSecurityOptions | None = None, peerstore_opt: IPeerStore | None = None, disc_opt: IPeerRouting | None = None, muxer_preference: Literal['YAMUX', 'MPLEX'] | None = None, listen_addrs: Sequence[multiaddr.Multiaddr] | None = None, enable_mDNS: bool = False, enable_upnp: bool = False, enable_autotls: bool = False, enable_metrics: bool = False, bootstrap: list[str] | None = None, negotiate_timeout: int = 30, enable_quic: bool = False, enable_webrtc: bool = False, enable_webtransport: bool = False, quic_transport_opt: QUICTransportConfig | None = None, tls_client_config: ssl.SSLContext | None = None, tls_server_config: ssl.SSLContext | None = None, resource_manager: ResourceManager | None = None, psk: str | None = None, bootstrap_allow_ipv6: bool = False, bootstrap_dns_timeout: float = 10.0, bootstrap_dns_max_retries: int = 3, connection_config: ConnectionConfig | None = None, announce_addrs: Sequence[multiaddr.Multiaddr] | None = None, addrs_factory: AddrsFactory | None = None, disable_identify_address_discovery: bool = False, transports: Sequence[ITransport] | None = None, enable_tcp: bool = True, enable_websocket: bool = False) IHost
Create a new libp2p host based on the given parameters.
The host can listen on and dial over multiple transports simultaneously (TCP, WebSocket, QUIC), mirroring go-libp2p’s architecture.
Transport selection priority (highest to lowest):
transports— explicit list, used as-is.listen_addrsinspection — all addresses are inspected.enable_*flags.Default: TCP only.
- Parameters:
key_pair – optional explicit
KeyPair(mutually exclusive withkey_pair_providerandkeystore)key_pair_provider – optional
Callable[[], KeyPair]used to obtain the host identity (issue #312)keystore – optional
FileSystemKeyStorefor named identity load/saveidentity_name – key name within
keystore(default"default")auto_persist – when using
keystore, persist newly generated keys (defaults toTrueifkeystoreis set)muxer_opt – optional choice of stream muxer
sec_opt – optional choice of security upgrade
peerstore_opt – optional peerstore
disc_opt – optional discovery
muxer_preference – optional explicit muxer preference
listen_addrs – optional list of multiaddrs to listen on. All addresses are inspected to determine which transports to create.
enable_mDNS – whether to enable mDNS discovery
bootstrap – optional list of bootstrap peer addresses as strings
enable_quic – optional choice to use QUIC for transport
enable_autotls – optional choice to use AutoTLS for security
quic_transport_opt – optional configuration for quic transport
tls_client_config – optional TLS client configuration for WebSocket transport
tls_server_config – optional TLS server configuration for WebSocket transport
resource_manager (
libp2p.rcmgr.ResourceManageror None) – optional resource manager for connection/stream limitspsk – optional pre-shared key (PSK)
bootstrap_allow_ipv6 – if True, bootstrap accepts IPv6+TCP addresses
bootstrap_dns_timeout – DNS resolution timeout in seconds per attempt
bootstrap_dns_max_retries – max DNS resolution retries with backoff
connection_config – optional connection configuration for connection manager and health monitoring. When both connection_config and quic_transport_opt are provided, all ConnectionConfig attributes are merged into the QUIC config.
announce_addrs – if set, these replace listen addrs in get_addrs() (mutually exclusive with
addrs_factory)addrs_factory – optional callable matching go-libp2p
AddrsFactory; receives the live candidate address list and returns addresses to advertise (mutually exclusive withannounce_addrs)disable_identify_address_discovery – if True, do not record Identify observed addresses for local discovery (go
DisableIdentifyAddressDiscovery). Identify itself still runs for peer metadata; only observed-address discovery is skipped.transports – explicit list of transport instances to register. When provided, all
enable_*flags andlisten_addrs-based detection are bypassed.enable_tcp – include a TCP transport when auto-building (default True).
enable_websocket – include a WebSocket transport when auto-building.
- Returns:
return a host instance
- libp2p.new_swarm(key_pair: KeyPair | None = None, key_pair_provider: Callable[[], KeyPair] | None = None, keystore: FileSystemKeyStore | None = None, identity_name: str = 'default', auto_persist: bool | None = None, muxer_opt: TMuxerOptions | None = None, sec_opt: TSecurityOptions | None = None, peerstore_opt: IPeerStore | None = None, muxer_preference: Literal['YAMUX', 'MPLEX'] | None = None, listen_addrs: Sequence[multiaddr.Multiaddr] | None = None, transports: Sequence[ITransport] | None = None, enable_quic: bool = False, enable_webrtc: bool = False, enable_webtransport: bool = False, enable_autotls: bool = False, enable_tcp: bool = True, enable_websocket: bool = False, retry_config: RetryConfig | None = None, connection_config: ConnectionConfig | QUICTransportConfig | None = None, tls_client_config: ssl.SSLContext | None = None, tls_server_config: ssl.SSLContext | None = None, resource_manager: ResourceManager | None = None, psk: str | None = None, metric_send_channel: trio.MemorySendChannel[Any] | None = None) INetworkService
Create a swarm instance with multi-transport support.
The swarm can listen on and dial over multiple transports simultaneously (TCP, WebSocket, QUIC), mirroring go-libp2p’s architecture.
Transport selection priority (highest to lowest):
Explicit ``transports`` list — used as-is; all other transport parameters are ignored.
``listen_addrs`` inspection — each address is inspected to determine which transports are needed (TCP, WebSocket, QUIC). All detected transport types are created and registered.
``enable_*`` flags — coarse-grained control when no addresses are provided (
enable_quic,enable_websocket,enable_tcp).Default fallback — TCP only.
- Parameters:
key_pair – optional explicit
KeyPair(mutually exclusive withkey_pair_providerandkeystore)key_pair_provider – optional
Callable[[], KeyPair]used to obtain the host identity (issue #312)keystore – optional
FileSystemKeyStorefor named identity load/saveidentity_name – key name within
keystore(default"default")auto_persist – when using
keystore, persist newly generated keys (defaults toTrueifkeystoreis set)muxer_opt – optional choice of stream muxer
sec_opt – optional choice of security upgrade
peerstore_opt – optional peerstore
muxer_preference – optional explicit muxer preference (
"YAMUX"or"MPLEX")listen_addrs – optional list of multiaddrs to listen on. All addresses are inspected to determine which transports to create.
transports – explicit list of transport instances to register. When provided, all
enable_*flags andlisten_addrs-based detection are bypassed.enable_quic – include a QUIC transport when auto-building (deprecated; prefer passing
listen_addrswith QUIC addresses ortransports).enable_autotls – enable AutoTLS for QUIC / WebSocket transports.
enable_tcp – include a TCP transport when auto-building (default True).
enable_websocket – include a WebSocket transport when auto-building.
retry_config – optional connection retry configuration.
connection_config – optional connection configuration.
tls_client_config – TLS client context for WebSocket transport.
tls_server_config – TLS server context for WebSocket transport.
resource_manager – optional resource manager for connection/stream limits.
psk – optional pre-shared key for PSK encryption.
- Returns:
a Swarm instance implementing INetworkService.
Examples:
# TCP only (default) swarm = new_swarm() # TCP + WebSocket + QUIC auto-detected from listen_addrs swarm = new_swarm(listen_addrs=[ Multiaddr("/ip4/0.0.0.0/tcp/4001"), Multiaddr("/ip4/0.0.0.0/tcp/4002/ws"), Multiaddr("/ip4/0.0.0.0/udp/4003/quic-v1"), ]) # Explicit transport list swarm = new_swarm(transports=[TCP(), QUICTransport(kp.private_key)])
- Note: Yamux (/yamux/1.0.0) is the preferred stream multiplexer
due to its improved performance and features. Mplex (/mplex/6.7.0) is retained for backward compatibility but may be deprecated in the future.
- Note: Ed25519 keys are used by default for better interoperability with
other libp2p implementations (Rust, Go) which often disable RSA support.
- libp2p.save_keypair(key_pair: KeyPair, type: str = 'ed25519') None
Persist a private key to disk in PEM format (legacy helper).
Currently supports only Ed25519 keys and writes to a fixed path (
libp2p.utils.paths.ED25519_PATH). For general identity persistence prefersave_identity/load_identityorFileSystemKeyStore, which use the libp2p protobuf private-key format and caller-chosen paths.- Parameters:
key_pair – KeyPair object containing private and public keys.
type – Type of key to save (default: “ed25519”).
- Raises:
ValueError – if an unsupported key type is provided.
- libp2p.set_default_muxer(muxer_name: Literal['YAMUX', 'MPLEX']) None
Set the default multiplexer protocol to use.
- Parameters:
muxer_name – Either “YAMUX” or “MPLEX”
- Raises:
ValueError – If an unsupported muxer name is provided