Refactor: update examples to utilize new address paradigm with wildcard support

- Introduced `get_wildcard_address` function for explicit wildcard binding.
- Updated examples to use `get_available_interfaces` and `get_optimal_binding_address` for address selection.
- Ensured consistent usage of the new address paradigm across all example files.
- Added tests to verify the implementation of the new address paradigm and wildcard feature.
This commit is contained in:
yashksaini-coder
2025-09-09 12:10:28 +05:30
parent 80e22f7c4a
commit 7d364da950
15 changed files with 280 additions and 181 deletions

View File

@ -14,6 +14,7 @@ try:
expand_wildcard_address,
get_available_interfaces,
get_optimal_binding_address,
get_wildcard_address,
)
except ImportError:
# Fallbacks if utilities are missing
@ -29,6 +30,9 @@ except ImportError:
def get_optimal_binding_address(port: int, protocol: str = "tcp"):
return Multiaddr(f"/ip4/127.0.0.1/{protocol}/{port}")
def get_wildcard_address(port: int, protocol: str = "tcp"):
return Multiaddr(f"/ip4/0.0.0.0/{protocol}/{port}")
def main() -> None:
port = 8080
@ -37,7 +41,10 @@ def main() -> None:
for a in interfaces:
print(f" - {a}")
wildcard_v4 = Multiaddr(f"/ip4/0.0.0.0/tcp/{port}")
# Demonstrate wildcard address as a feature
wildcard_v4 = get_wildcard_address(port)
print(f"\nWildcard address (feature): {wildcard_v4}")
expanded_v4 = expand_wildcard_address(wildcard_v4)
print("\nExpanded IPv4 wildcard:")
for a in expanded_v4:

View File

@ -53,7 +53,11 @@ BOOTSTRAP_PEERS = [
async def run(port: int, bootstrap_addrs: list[str]) -> None:
"""Run the bootstrap discovery example."""
from libp2p.utils.address_validation import find_free_port, get_available_interfaces
from libp2p.utils.address_validation import (
find_free_port,
get_available_interfaces,
get_optimal_binding_address,
)
if port <= 0:
port = find_free_port()
@ -93,6 +97,12 @@ async def run(port: int, bootstrap_addrs: list[str]) -> None:
logger.info(f"{addr}")
print(f"{addr}")
# Display optimal address for reference
optimal_addr = get_optimal_binding_address(port)
optimal_addr_with_peer = f"{optimal_addr}/p2p/{host.get_id().to_string()}"
logger.info(f"Optimal address: {optimal_addr_with_peer}")
print(f"Optimal address: {optimal_addr_with_peer}")
# Keep running and log peer discovery events
await trio.sleep_forever()
except KeyboardInterrupt:

View File

@ -46,7 +46,11 @@ async def write_data(stream: INetStream) -> None:
async def run(port: int, destination: str) -> None:
from libp2p.utils.address_validation import find_free_port, get_available_interfaces
from libp2p.utils.address_validation import (
find_free_port,
get_available_interfaces,
get_optimal_binding_address,
)
if port <= 0:
port = find_free_port()
@ -72,11 +76,12 @@ async def run(port: int, destination: str) -> None:
for addr in all_addrs:
print(f"{addr}")
# Use the first address as the default for the client command
default_addr = all_addrs[0]
# Use optimal address for the client command
optimal_addr = get_optimal_binding_address(port)
optimal_addr_with_peer = f"{optimal_addr}/p2p/{host.get_id().to_string()}"
print(
f"\nRun this from the same folder in another console:\n\n"
f"chat-demo -d {default_addr}\n"
f"chat-demo -d {optimal_addr_with_peer}\n"
)
print("Waiting for incoming connection...")

View File

@ -1,6 +1,5 @@
import secrets
import multiaddr
import trio
from libp2p import (
@ -13,6 +12,10 @@ from libp2p.security.noise.transport import (
PROTOCOL_ID as NOISE_PROTOCOL_ID,
Transport as NoiseTransport,
)
from libp2p.utils.address_validation import (
get_available_interfaces,
get_optimal_binding_address,
)
async def main():
@ -39,14 +42,16 @@ async def main():
# Create a host with the key pair, Noise security, and mplex multiplexer
host = new_host(key_pair=key_pair, sec_opt=security_options)
# Configure the listening address
# Configure the listening address using the new paradigm
port = 8000
listen_addr = multiaddr.Multiaddr(f"/ip4/127.0.0.1/tcp/{port}")
listen_addrs = get_available_interfaces(port)
optimal_addr = get_optimal_binding_address(port)
# Start the host
async with host.run(listen_addrs=[listen_addr]):
async with host.run(listen_addrs=listen_addrs):
print("libp2p has started with Noise encryption and mplex multiplexing")
print("libp2p is listening on:", host.get_addrs())
print(f"Optimal address: {optimal_addr}")
# Keep the host running
await trio.sleep_forever()

View File

@ -38,6 +38,10 @@ from libp2p.network.stream.net_stream import (
from libp2p.peer.peerinfo import (
info_from_p2p_addr,
)
from libp2p.utils.address_validation import (
get_available_interfaces,
get_optimal_binding_address,
)
PROTOCOL_ID = TProtocol("/echo/1.0.0")
@ -173,7 +177,9 @@ async def run_enhanced_demo(
"""
Run enhanced echo demo with NetStream state management.
"""
listen_addr = multiaddr.Multiaddr(f"/ip4/127.0.0.1/tcp/{port}")
# Use the new address paradigm
listen_addrs = get_available_interfaces(port)
optimal_addr = get_optimal_binding_address(port)
# Generate or use provided key
if seed:
@ -185,7 +191,7 @@ async def run_enhanced_demo(
host = new_host(key_pair=create_new_key_pair(secret))
async with host.run(listen_addrs=[listen_addr]):
async with host.run(listen_addrs=listen_addrs):
print(f"Host ID: {host.get_id().to_string()}")
print("=" * 60)
@ -196,10 +202,12 @@ async def run_enhanced_demo(
# type: ignore: Stream is type of NetStream
host.set_stream_handler(PROTOCOL_ID, enhanced_echo_handler)
# Use optimal address for client command
optimal_addr_with_peer = f"{optimal_addr}/p2p/{host.get_id().to_string()}"
print(
"Run client from another console:\n"
f"python3 example_net_stream.py "
f"-d {host.get_addrs()[0]}\n"
f"-d {optimal_addr_with_peer}\n"
)
print("Waiting for connections...")
print("Press Ctrl+C to stop server")

View File

@ -1,6 +1,5 @@
import secrets
import multiaddr
import trio
from libp2p import (
@ -13,6 +12,10 @@ from libp2p.security.noise.transport import (
PROTOCOL_ID as NOISE_PROTOCOL_ID,
Transport as NoiseTransport,
)
from libp2p.utils.address_validation import (
get_available_interfaces,
get_optimal_binding_address,
)
async def main():
@ -39,14 +42,16 @@ async def main():
# Create a host with the key pair, Noise security, and mplex multiplexer
host = new_host(key_pair=key_pair, sec_opt=security_options)
# Configure the listening address
# Configure the listening address using the new paradigm
port = 8000
listen_addr = multiaddr.Multiaddr(f"/ip4/127.0.0.1/tcp/{port}")
listen_addrs = get_available_interfaces(port)
optimal_addr = get_optimal_binding_address(port)
# Start the host
async with host.run(listen_addrs=[listen_addr]):
async with host.run(listen_addrs=listen_addrs):
print("libp2p has started")
print("libp2p is listening on:", host.get_addrs())
print(f"Optimal address: {optimal_addr}")
# Keep the host running
await trio.sleep_forever()

View File

@ -1,6 +1,5 @@
import secrets
import multiaddr
import trio
from libp2p import (
@ -9,6 +8,10 @@ from libp2p import (
from libp2p.crypto.secp256k1 import (
create_new_key_pair,
)
from libp2p.utils.address_validation import (
get_available_interfaces,
get_optimal_binding_address,
)
async def main():
@ -19,14 +22,16 @@ async def main():
# Create a host with the key pair
host = new_host(key_pair=key_pair)
# Configure the listening address
# Configure the listening address using the new paradigm
port = 8000
listen_addr = multiaddr.Multiaddr(f"/ip4/127.0.0.1/tcp/{port}")
listen_addrs = get_available_interfaces(port)
optimal_addr = get_optimal_binding_address(port)
# Start the host
async with host.run(listen_addrs=[listen_addr]):
async with host.run(listen_addrs=listen_addrs):
print("libp2p has started with TCP transport")
print("libp2p is listening on:", host.get_addrs())
print(f"Optimal address: {optimal_addr}")
# Keep the host running
await trio.sleep_forever()

View File

@ -27,6 +27,7 @@ from libp2p.peer.peerinfo import (
from libp2p.utils.address_validation import (
find_free_port,
get_available_interfaces,
get_optimal_binding_address,
)
# Configure minimal logging
@ -82,9 +83,13 @@ async def run(port: int, destination: str, seed: int | None = None) -> None:
for addr in listen_addr:
print(f"{addr}/p2p/{peer_id}")
# Get optimal address for display
optimal_addr = get_optimal_binding_address(port)
optimal_addr_with_peer = f"{optimal_addr}/p2p/{peer_id}"
print(
"\nRun this from the same folder in another console:\n\n"
f"echo-demo -d {host.get_addrs()[0]}\n"
f"echo-demo -d {optimal_addr_with_peer}\n"
)
print("Waiting for incoming connections...")
await trio.sleep_forever()

View File

@ -63,7 +63,10 @@ def print_identify_response(identify_response: Identify):
async def run(port: int, destination: str, use_varint_format: bool = True) -> None:
from libp2p.utils.address_validation import get_available_interfaces
from libp2p.utils.address_validation import (
get_available_interfaces,
get_optimal_binding_address,
)
if not destination:
# Create first host (listener)
@ -100,11 +103,12 @@ async def run(port: int, destination: str, use_varint_format: bool = True) -> No
for addr in all_addrs:
print(f"{addr}")
# Use the first address as the default for the client command
default_addr = all_addrs[0]
# Use optimal address for the client command
optimal_addr = get_optimal_binding_address(port)
optimal_addr_with_peer = f"{optimal_addr}/p2p/{host_a.get_id().to_string()}"
print(
f"\nRun this from the same folder in another console:\n\n"
f"identify-demo {format_flag} -d {default_addr}\n"
f"identify-demo {format_flag} -d {optimal_addr_with_peer}\n"
)
print("Waiting for incoming identify request...")
@ -152,6 +156,7 @@ async def run(port: int, destination: str, use_varint_format: bool = True) -> No
from libp2p.utils.address_validation import (
find_free_port,
get_available_interfaces,
get_optimal_binding_address,
)
if port <= 0:

View File

@ -151,7 +151,10 @@ async def run_node(
key_pair = create_new_key_pair(secrets.token_bytes(32))
host = new_host(key_pair=key_pair)
from libp2p.utils.address_validation import get_available_interfaces
from libp2p.utils.address_validation import (
get_available_interfaces,
get_optimal_binding_address,
)
listen_addrs = get_available_interfaces(port)
@ -168,9 +171,10 @@ async def run_node(
for addr in all_addrs:
logger.info(f"{addr}")
# Use the first address as the default for the bootstrap command
default_addr = all_addrs[0]
bootstrap_cmd = f"--bootstrap {default_addr}"
# Use optimal address for the bootstrap command
optimal_addr = get_optimal_binding_address(port)
optimal_addr_with_peer = f"{optimal_addr}/p2p/{host.get_id().to_string()}"
bootstrap_cmd = f"--bootstrap {optimal_addr_with_peer}"
logger.info("To connect to this node, use: %s", bootstrap_cmd)
await connect_to_bootstrap_nodes(host, bootstrap_nodes)
@ -182,7 +186,7 @@ async def run_node(
# Save server address in server mode
if dht_mode == DHTMode.SERVER:
save_server_addr(str(default_addr))
save_server_addr(str(optimal_addr_with_peer))
# Start the DHT service
async with background_trio_service(dht):

View File

@ -61,7 +61,11 @@ async def send_ping(stream: INetStream) -> None:
async def run(port: int, destination: str) -> None:
from libp2p.utils.address_validation import find_free_port, get_available_interfaces
from libp2p.utils.address_validation import (
find_free_port,
get_available_interfaces,
get_optimal_binding_address,
)
if port <= 0:
port = find_free_port()
@ -83,11 +87,12 @@ async def run(port: int, destination: str) -> None:
for addr in all_addrs:
print(f"{addr}")
# Use the first address as the default for the client command
default_addr = all_addrs[0]
# Use optimal address for the client command
optimal_addr = get_optimal_binding_address(port)
optimal_addr_with_peer = f"{optimal_addr}/p2p/{host.get_id().to_string()}"
print(
f"\nRun this from the same folder in another console:\n\n"
f"ping-demo -d {default_addr}\n"
f"ping-demo -d {optimal_addr_with_peer}\n"
)
print("Waiting for incoming connection...")

View File

@ -102,7 +102,10 @@ async def monitor_peer_topics(pubsub, nursery, termination_event):
async def run(topic: str, destination: str | None, port: int | None) -> None:
from libp2p.utils.address_validation import get_available_interfaces
from libp2p.utils.address_validation import (
get_available_interfaces,
get_optimal_binding_address,
)
if port is None or port == 0:
port = find_free_port()
@ -162,11 +165,14 @@ async def run(topic: str, destination: str | None, port: int | None) -> None:
for addr in all_addrs:
logger.info(f"{addr}")
# Use the first address as the default for the client command
default_addr = all_addrs[0]
# Use optimal address for the client command
optimal_addr = get_optimal_binding_address(port)
optimal_addr_with_peer = (
f"{optimal_addr}/p2p/{host.get_id().to_string()}"
)
logger.info(
f"\nRun this from the same folder in another console:\n\n"
f"pubsub-demo -d {default_addr}\n"
f"pubsub-demo -d {optimal_addr_with_peer}\n"
)
logger.info("Waiting for peers...")