### Run the Multiplexing Example Source: https://github.com/libp2p/go-libp2p/blob/master/examples/multipro/README.md Execute the built binary to start the libp2p hosts and protocols. ```sh > ./multipro ``` -------------------------------- ### Build the Example Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-mdns/README.md Run these commands to get the necessary dependencies and build the chat application. ```bash go get -v -d ./... go build ``` -------------------------------- ### Clone and Navigate to Example Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/chat/README.md Clone the go-libp2p repository and navigate to the chat example directory to get started. ```shell git clone https://github.com/libp2p/go-libp2p cd go-libp2p/examples/pubsub/chat ``` -------------------------------- ### Build the Multiplexing Example Source: https://github.com/libp2p/go-libp2p/blob/master/examples/multipro/README.md Navigate to the example directory and build the Go executable. ```sh > cd multipro/ > go build ``` -------------------------------- ### Build the HTTP Proxy Example Source: https://github.com/libp2p/go-libp2p/blob/master/examples/http-proxy/README.md Navigate to the example directory and build the Go executable. ```bash > cd http-proxy/ > go build ``` -------------------------------- ### Run Metrics and Dashboards Example Source: https://github.com/libp2p/go-libp2p/blob/master/examples/metrics-and-dashboards/README.md Use this command to start the Prometheus and Grafana servers along with the go-libp2p application. ```bash docker compose -f ../../dashboards/docker-compose.base.yml -f ./compose.yml up ``` -------------------------------- ### Run the Basic Chat Example Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/basic-chat-with-rendezvous/README.md Execute the chat application using `go run` or by building and running the binary. This starts a pub/sub chat where peers can join and communicate. ```shell go run . # or, build and run separately go build . ./chat ``` -------------------------------- ### Build the Routed Echo Example Source: https://github.com/libp2p/go-libp2p/blob/master/examples/routed-echo/README.md Navigate to the example directory and build the application using `go build`. ```bash > cd routed-echo/ > go build ``` -------------------------------- ### Build Echo Example Source: https://github.com/libp2p/go-libp2p/blob/master/examples/echo/README.md Builds the echo client/server executable from the go-libp2p examples directory. ```bash > cd echo/ > go build ``` -------------------------------- ### Clone and Navigate go-libp2p Examples Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/basic-chat-with-rendezvous/README.md Clone the go-libp2p repository and navigate to the specific example directory for the basic chat with rendezvous. ```shell git clone https://github.com/libp2p/go-libp2p cd go-libp2p/examples/pubsub/basic-chat-with-rendezvous ``` -------------------------------- ### Run libp2p AutoTLS Example Source: https://github.com/libp2p/go-libp2p/blob/master/examples/autotls/README.md Navigate to the autotls directory and run the example using 'go run .'. Ensure your node is publicly reachable for AutoTLS to issue certificates. ```sh cd autotls/ go run . ``` -------------------------------- ### Example Allowlist Configuration Source: https://github.com/libp2p/go-libp2p/blob/master/p2p/host/resource-manager/docs/allowlist.md This shows an example of how an allowlist set can be configured, including IP addresses, IP addresses with PeerIDs, and IP ranges. ```plaintext /ip4/1.1.1.1 /ip6/2345:0425:2CA1::0567:5673:23b5 /ip4/192.168.1.1/p2p/qmFoo /ip4/192.168.1.1/p2p/qmBar /ip4/1.2.3.0/ipcidr/24 ``` -------------------------------- ### Build the Chat Application Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat/README.md Navigate to the chat example directory and build the executable using 'go build'. ```bash > cd chat/ > go build ``` -------------------------------- ### Enable Prometheus Metrics for Resource Manager Source: https://github.com/libp2p/go-libp2p/blob/master/p2p/host/resource-manager/README.md This example demonstrates how to enable Prometheus metrics for the resource manager. Refer to obs/stats_test.go for a complete example and DefaultViews in stats.go for recommended views. ```go import ( "context" "go.uber.org/fx" "go.uber.org/zap" "github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/core/metrics" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/p2p/config" "github.com/libp2p/go-libp2p/core/p2p/log" "github.com/libp2p/go-libp2p/core/p2p/nat" "github.com/libp2p/go-libp2p/core/p2p/net" "github.com/libp2p/go-libp2p/core/p2p/transport" "github.com/libp2p/go-libp2p/p2p/host/resourceuse/rcmgr" "github.com/libp2p/go-libp2p/p2p/host/resourceuse/rcmgr/testutils" "github.com/prometheus/client_golang/prometheus" ) func main() { var h host.Host var rcm *rcmgr.ResourceManager fx.New( fx.Provide( func() metrics.Reporter { return metrics.NewPrometheusReporter(prometheus.NewRegistry()) }, ), libp2p.ProvideResource secaraManager(), fx.Populate(&h, &rcm), ).Run() // ... use h and rcm ... } ``` -------------------------------- ### Run the Remote Peer Source: https://github.com/libp2p/go-libp2p/blob/master/examples/http-proxy/README.md Execute the compiled binary to start the remote libp2p peer. This peer will listen for incoming connections and print its libp2p address. ```bash > ./http-proxy Proxy server is ready libp2p-peer addresses: /ip4/127.0.0.1/tcp/12000/p2p/QmddTrQXhA9AkCpXPTkcY7e22NK73TwkUms3a44DhTKJTD ``` -------------------------------- ### Start Echo Listener Source: https://github.com/libp2p/go-libp2p/blob/master/examples/echo/README.md Launches the echo application in listen mode on port 10000. The node will print its Multiaddress for other nodes to connect to. ```bash > ./echo -l 10000 ``` -------------------------------- ### Import go-libp2p Package Source: https://github.com/libp2p/go-libp2p/blob/master/README.md To start using go-libp2p in your Go application, add the following import statement. ```go import "github.com/libp2p/go-libp2p" ``` -------------------------------- ### Run the Listener Node Source: https://github.com/libp2p/go-libp2p/blob/master/examples/routed-echo/README.md Start the listener node with a specified port. The output will display the host's multiaddress and Peer ID, which can be used to connect to it. ```bash > ./routed-echo -l 10000 2018/02/19 12:22:32 I can be reached at: 2018/02/19 12:22:32 /ip4/127.0.0.1/tcp/10000/p2p/QmfRY4vuKpU2tApACrbmYFn9xoeNzMQhLXg7nKnyvnzHeL 2018/02/19 12:22:32 /ip4/192.168.1.203/tcp/10000/p2p/QmfRY4vuKpU2tApACrbmYFn9xoeNzMQhLXg7nKnyvnzHeL 2018/02/19 12:22:32 Now run "./routed-echo -l 10001 -d QmfRY4vuKpU2tApACrbmYFn9xoeNzMQhLXg7nKnyvnzHeL" on a different terminal 2018/02/19 12:22:32 listening for connections ``` -------------------------------- ### Example Resource Manager Debug Log Source: https://github.com/libp2p/go-libp2p/blob/master/p2p/host/resource-manager/README.md This is an example log line emitted when debug logging is enabled and a resource limit is exceeded. It indicates which resource was blocked, the scope, current usage, and the limit that was hit. ```log 2022-08-12T15:49:35.459-0700 DEBUG rcmgr go-libp2p-resource-manager@v0.5.3/scope.go:541 blocked connection from constraining edge {"scope": "conn-19667", "edge": "system", "direction": "Inbound", "usefd": false, "current": 100, "attempted": 1, "limit": 100, "stat": {"NumStreamsInbound":28,"NumStreamsOutbound":66,"NumConnsInbound":37,"NumConnsOutbound":63,"NumFD":33,"Memory":8687616}, "error": "system: cannot reserve connection: resource limit exceeded"} ``` -------------------------------- ### Run the Local Peer with Remote Peer Discovery Source: https://github.com/libp2p/go-libp2p/blob/master/examples/http-proxy/README.md Start the local libp2p peer, providing the libp2p address of the remote peer using the '-d' flag. This configures the local peer to forward HTTP requests to the remote peer. ```bash > ./http-proxy -d /ip4/127.0.0.1/tcp/12000/p2p/QmddTrQXhA9AkCpXPTkcY7e22NK73TwkUms3a44DhTKJTD Proxy server is ready libp2p-peer addresses: /ip4/127.0.0.1/tcp/12001/p2p/Qmaa2AYTha1UqcFVX97p9R1UP7vbzDLY7bqWsZw1135QvN proxy listening on 127.0.0.1:9900 ``` -------------------------------- ### Start mDNS Service Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-mdns/README.md Activates the mDNS discovery service to begin searching for and announcing peers on the local network. ```go ser.Start() ``` -------------------------------- ### Run with Custom Nickname Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/chat/README.md Start the chat application with a custom nickname using the '-nick' flag. ```shell go run . -nick=zoidberg ``` -------------------------------- ### Tweak Default Resource Limits Source: https://github.com/libp2p/go-libp2p/blob/master/p2p/host/resource-manager/README.md An example demonstrating how to modify the default resource limits by copying the `DefaultLimits` struct and updating specific fields like `Streams`, `StreamsInbound`, and `StreamsOutbound` for the protocol scope. ```go // An example on how to tweak the default limits tweakedDefaults := DefaultLimits tweakedDefaults.ProtocolBaseLimit.Streams = 1024 tweakedDefaults.ProtocolBaseLimit.StreamsInbound = 512 tweakedDefaults.ProtocolBaseLimit.StreamsOutbound = 512 ``` -------------------------------- ### Start Echo Dialer Source: https://github.com/libp2p/go-libp2p/blob/master/examples/echo/README.md Launches the echo application in dial mode, connecting to a listener at the provided Multiaddress on port 10000. This node sends a message and waits for an echo. ```bash > ./echo -l 10001 -d /ip4/127.0.0.1/tcp/10000/p2p/QmYo41GybvrXk8y8Xnm1P7pfA4YEXCpfnLyzgRPnNbG35e ``` -------------------------------- ### Handle Incoming Streams Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-mdns/README.md The `handleStream` function processes new incoming streams. It sets up buffered readers and writers for non-blocking data exchange and starts goroutines for reading and writing data. ```go func handleStream(stream net.Stream) { // Create a buffer stream for non blocking read and write. rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream)) go readData(rw) go writeData(rw) // 'stream' will stay open until you close it (or the other side closes it). } ``` -------------------------------- ### Initialize libp2p Host and PubSub Service Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/chat/README.md Sets up a new libp2p host listening on a random TCP port and initializes a GossipSub PubSub service. Requires a context for the PubSub service. ```go func main() { // (omitted) parse flags, etc... // create a new libp2p Host that listens on a random TCP port h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/0.0.0.0/tcp/0")) if err != nil { panic(err) } // create a new PubSub service using the GossipSub router ps, err := pubsub.NewGossipSub(ctx, h) if err != nil { panic(err) } // (omitted) setup mDNS discovery... } ``` -------------------------------- ### Run the Sender Node Source: https://github.com/libp2p/go-libp2p/blob/master/examples/routed-echo/README.md Launch a second node that connects to the listener using its Peer ID. This node will send a "Hello, world!" message. ```bash > ./routed-echo -l 10001 -d QmfRY4vuKpU2tApACrbmYFn9xoeNzMQhLXg7nKnyvnzHeL ``` -------------------------------- ### Initialize Resource Manager with Custom Limits Source: https://github.com/libp2p/go-libp2p/blob/master/p2p/host/resource-manager/README.md Configure resource manager with default scaling limits, apply libp2p service limits, and then scale them based on system memory. Tweak specific settings like unlimited outbound streams and create a fixed limiter. Metrics are enabled by default, use WithMetricsDisabled to disable. ```go // Start with the default scaling limits. scalingLimits := rcmgr.DefaultLimits // Add limits around included libp2p protocols libp2p.SetDefaultServiceLimits(&scalingLimits) // Turn the scaling limits into a concrete set of limits using `.AutoScale`. This // scales the limits proportional to your system memory. scaledDefaultLimits := scalingLimits.AutoScale() // Tweak certain settings cfg := rcmgr.PartialLimitConfig{ System: rcmgr.ResourceLimits{ // Allow unlimited outbound streams StreamsOutbound: rcmgr.Unlimited, }, // Everything else is default. The exact values will come from `scaledDefaultLimits` above. } // Create our limits by using our cfg and replacing the default values with values from `scaledDefaultLimits` limits := cfg.Build(scaledDefaultLimits) // The resource manager expects a limiter, se we create one from our limits. limiter := rcmgr.NewFixedLimiter(limits) // Metrics are enabled by default. If you want to disable metrics, use the // WithMetricsDisabled option // Initialize the resource manager rm, err := rcmgr.NewResourceManager(limiter, rcmgr.WithMetricsDisabled()) if err != nil { panic(err) } // Create a libp2p host host, err := libp2p.New(libp2p.ResourceManager(rm)) ``` -------------------------------- ### Configure a p2p Host Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-mdns/README.md Initializes a new libp2p host, which is the core component for P2P communication. Additional configuration options can be passed here. ```go ctx := context.Background() // libp2p.New constructs a new libp2p Host. // Other options can be added here. host, err := libp2p.New() ``` -------------------------------- ### Configure a p2p Host Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-rendezvous/README.md Constructs a new libp2p Host with default configurations. Additional options can be provided here. ```go // libp2p.New constructs a new libp2p Host. // Other options can be added here. host, err := libp2p.New() ``` -------------------------------- ### Build the Chat Application Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-rendezvous/README.md Navigate to the chat-with-rendezvous directory and build the application using go build. ```bash > cd chat-with-rendezvous/ > go build -o chat ``` -------------------------------- ### Initialize DHT Client Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-rendezvous/README.md Creates a new Distributed Hash Table (DHT) client using the provided libp2p host. ```go dht, err := dht.New(ctx, host) ``` -------------------------------- ### Build go-libp2p Docker Image Source: https://github.com/libp2p/go-libp2p/blob/master/test-plans/README.md Build a Docker image for the go-libp2p head version to be used in interop tests. ```bash docker build -t go-libp2p-head -f test-plans/PingDockerfile . ``` -------------------------------- ### Run the Application Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-mdns/README.md Execute the built application in separate terminal windows, specifying different ports for each instance. ```bash ./chat-with-mdns -port 6666 ./chat-with-mdns -port 6668 ``` -------------------------------- ### Initialize mDNS Service Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-mdns/README.md Creates a new mDNS discovery service associated with the libp2p host. A Notifee interface is registered to receive notifications about discovered peers. ```go notifee := &discoveryNotifee{PeerChan: make(chan peer.AddrInfo)} ser, err := discovery.NewMdnsService(peerhost, rendezvous, notifee) ``` -------------------------------- ### Define Scaling Limits Configuration Source: https://github.com/libp2p/go-libp2p/blob/master/p2p/host/resource-manager/README.md Defines a `ScalingLimitConfig` with base limits and increases for various resources. The `SystemBaseLimit` is the minimum configuration, and `SystemLimitIncrease` is added per GB of memory. `FDFraction` determines the proportion of file descriptors allocated. ```go var scalingLimits = ScalingLimitConfig{ SystemBaseLimit: BaseLimit{ ConnsInbound: 64, ConnsOutbound: 128, Conns: 128, StreamsInbound: 512, StreamsOutbound: 1024, Streams: 1024, Memory: 128 << 20, FD: 256, }, SystemLimitIncrease: BaseLimitIncrease{ ConnsInbound: 32, ConnsOutbound: 64, Conns: 64, StreamsInbound: 256, StreamsOutbound: 512, Streams: 512, Memory: 256 << 20, FDFraction: 1, }, } ``` -------------------------------- ### Connect to Bootstrap Nodes Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-rendezvous/README.md Establishes connections to predefined bootstrap nodes to facilitate peer discovery within the network using the DHT. ```go for _, addr := range bootstrapPeers { iaddr, _ := ipfsaddr.ParseString(addr) peerinfo, _ := peerstore.InfoFromP2pAddr(iaddr.Multiaddr()) if err := host.Connect(ctx, *peerinfo); err != nil { fmt.Println(err) } else { fmt.Println("Connection established with bootstrap node: ", *peerinfo) } } ``` -------------------------------- ### Run Node A (Client) Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat/README.md On node 'A', run the chat executable with the '-d' flag, providing the multiaddr of node 'B'. This connects node 'A' to node 'B'. ```bash > ./chat -d /ip4/127.0.0.1/tcp/3001/p2p/QmdXGaeGiVA745XorV1jr11RHxB9z4fqykm6xCUPX1aTJo Run ./chat -d /ip4/127.0.0.1/tcp/3001/p2p/QmdXGaeGiVA745XorV1jr11RHxB9z4fqykm6xCUPX1aTJo This node's multiaddress: /ip4/0.0.0.0/tcp/0/p2p/QmWVx9NwsgaVWMRHNCpesq1WQAw2T3JurjGDNeVNWifPS7 > hi > hello ``` -------------------------------- ### Run Interop Tests with Docker Compose Source: https://github.com/libp2p/go-libp2p/blob/master/test-plans/README.md Execute interop tests against all released libp2p versions using npm and Docker Compose. Requires the test-plans repository to be checked out separately. ```bash GO_LIBP2P="$PWD"; (cd /libp2p/test-plans/transport-interop/ && npm run test -- --extra-version=$GO_LIBP2P/test-plans/ping-version.json --name-filter="go-libp2p-head") ``` -------------------------------- ### Run Node B (Server) Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat/README.md On node 'B', run the chat executable with the '-sp' flag to specify the source port. This node will listen for incoming connections. ```bash > ./chat -sp 3001 Run ./chat -d /ip4/127.0.0.1/tcp/3001/p2p/QmdXGaeGiVA745XorV1jr11RHxB9z4fqykm6xCUPX1aTJo 2018/02/27 01:21:32 Got a new stream! > hi (received messages in green colour) > hello (sent messages in white colour) > no ``` -------------------------------- ### Initiate Streams to Discovered Peers Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-rendezvous/README.md Iterates through discovered peers, establishes new streams, and launches goroutines for reading and writing data to enable chat communication. ```go go func() { for peer := range peerChan { if peer.ID == host.ID() { continue } fmt.Println("Found peer:", peer) fmt.Println("Connecting to:", peer) stream, err := host.NewStream(ctx, peer.ID, protocol.ID(config.ProtocolID)) if err != nil { fmt.Println("Connection failed:", err) continue } else { rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream)) go writeData(rw) go readData(rw) } fmt.Println("Connected to:", peer) } }() ``` -------------------------------- ### Configure Allowlisted Multiaddrs Source: https://github.com/libp2p/go-libp2p/blob/master/p2p/host/resource-manager/README.md Use the WithAllowlistedMultiaddrs option when creating the resource manager to specify a set of trusted peers and IP addresses. These peers will have their own limits, ensuring connectivity even when system limits are reached. ```go import ( "github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/p2p/host/resourceuse/rcmgr" "github.com/multiformats/go-multiaddr" ) func NewResourceManager(h host.Host, opts ...rcmgr.Option) (*rcmgr.ResourceManager, error) { // Example of using WithAllowlistedMultiaddrs allowlistAddrs := []multiaddr.Multiaddr{ // Add trusted multiaddrs here } options := append(opts, rcmgr.WithAllowlistedMultiaddrs(allowlistAddrs)) return rcmgr.New(h.ConnManager(), options...) } ``` -------------------------------- ### Join Chat Room Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/chat/README.md Joins a chat room using the initialized PubSub service, host ID, nickname, and room name. Requires a context, PubSub service, host ID, nickname, and room name. ```go // still in the main func cr, err := JoinChatRoom(ctx, ps, h.ID(), nick, room) if err != nil { panic(err) } ``` -------------------------------- ### Reproduce Flakiness with Coverage Profile Source: https://github.com/libp2p/go-libp2p/blob/master/docs/flaky-tests.md Enable coverage profiling when running tests to potentially reproduce flaky behavior. This is useful when flakiness is suspected to be related to additional goroutines introduced by coverage tracking. ```bash go test -coverprofile=module-coverage.txt ``` -------------------------------- ### Compile and Run Test within CPU Limits Source: https://github.com/libp2p/go-libp2p/blob/master/docs/flaky-tests.md Compile a test and then execute it within a cgroup that limits CPU resources to simulate CI conditions. This helps in reproducing timing-related test failures. ```bash # Compile some test we want to run. We do this outside the cgroup so this is # fast go test -c ./p2p/host/autorelay # Create the group sudo cgcreate -g cpu:/cpulimit # Limit the time to 10,000 microseconds for every 1s sudo cgset -r cpu.cfs_quota_us=10000 cpulimit sudo cgset -r cpu.cfs_period_us=1000000 cpulimit # Run a shell with in our limited environment sudo cgexec -g cpu:cpulimit bash # In the shell, run the test ./autorelay.test -test.v ``` -------------------------------- ### Save Resource Manager Limits Configuration as JSON Source: https://github.com/libp2p/go-libp2p/blob/master/p2p/host/resource-manager/README.md Serialize a PartialLimitConfig to JSON. This method omits defaults and explicitly serializes 'blockAll' and 'unlimited' values. The 'Memory' field is serialized as a string to handle potential 32-bit integer limitations. ```go noisyNeighbor, _ := peer.Decode("QmVvtzcZgCkMnSFf2dnrBPXrWuNFWNM9J3MpZQCvWPuVZf") cfg := rcmgr.PartialLimitConfig{ System: &rcmgr.ResourceLimits{ // Allow unlimited outbound streams StreamsOutbound: rcmgr.Unlimited, }, Peer: map[peer.ID]rcmgr.ResourceLimits{ noisyNeighbor: { // No inbound connections from this peer ConnsInbound: rcmgr.BlockAllLimit, // But let me open connections to them Conns: rcmgr.DefaultLimit, ConnsOutbound: rcmgr.DefaultLimit, // No inbound streams from this peer StreamsInbound: rcmgr.BlockAllLimit, // And let me open unlimited (by me) outbound streams (the peer may have their own limits on me) StreamsOutbound: rcmgr.Unlimited, }, }, } jsonBytes, _ := json.Marshal(&cfg) ``` -------------------------------- ### Connect to Discovered Peers Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-mdns/README.md Establishes a connection to a discovered peer and opens a new stream for communication. It includes logic to prevent simultaneous connection attempts from both peers by comparing their IDs. ```go peer := <-peerChan // will block until we discover a peer // this is used to avoid call `NewStream` from both side if peer.ID > host.ID() { // if other end peer id greater than us, don't connect to it, just wait for it to connect us fmt.Println("Found peer:", peer, " id is greater than us, wait for it to connect to us") continue } fmt.Println("Found peer:", peer, ", connecting") if err := host.Connect(ctx, peer); err != nil { fmt.Println("Connection failed:", err) continue } // open a stream, this stream will be handled by handleStream other end stream, err := host.NewStream(ctx, peer.ID, protocol.ID(cfg.ProtocolID)) if err != nil { fmt.Println("Stream open failed", err) } else { rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream)) go writeData(rw) go readData(rw) fmt.Println("Connected to:", peer) } ``` -------------------------------- ### Run Local Listener for Ping Test Source: https://github.com/libp2p/go-libp2p/blob/master/test-plans/README.md Execute the ping test as a listener. Requires a local Redis instance and specifies transport, security, and muxer protocols. ```bash redis_addr=localhost:6379 ip="0.0.0.0" transport=quic-v1 security=quic muxer=quic is_dialer="false" go run ./cmd/ping ``` -------------------------------- ### Run in a Specific Chat Room Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/chat/README.md Join a specific chat room by providing its name with the '-room' flag. Ensure all participants use the same room name for communication. ```shell go run . -room=planet-express ``` -------------------------------- ### Run Chat Application Instances Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-rendezvous/README.md Execute two instances of the chat application in separate terminals, specifying different listen addresses. ```bash ./chat -listen /ip4/127.0.0.1/tcp/6666 ./chat -listen /ip4/127.0.0.1/tcp/6668 ``` -------------------------------- ### Run Local Dialer for Ping Test Source: https://github.com/libp2p/go-libp2p/blob/master/test-plans/README.md Execute the ping test as a dialer. Requires a local Redis instance and specifies transport, security, and muxer protocols. ```bash redis_addr=localhost:6379 ip="0.0.0.0" transport=quic-v1 security=quic muxer=quic is_dialer="true" go run ./cmd/ping ``` -------------------------------- ### Use the HTTP Proxy with curl Source: https://github.com/libp2p/go-libp2p/blob/master/examples/http-proxy/README.md Utilize the local proxy address (e.g., 127.0.0.1:9900) with tools like curl to proxy HTTP requests to external services. ```bash > curl -x "127.0.0.1:9900" "http://ipfs.io/p2p/QmfUX75pGRBRDnjeoMkQzuQczuCup2aYbeLxz5NzeSu9G6" it works! ``` -------------------------------- ### Enable Resource Manager Debug Logging Source: https://github.com/libp2p/go-libp2p/blob/master/p2p/host/resource-manager/README.md Set the GOLOG_LOG_LEVEL environment variable to "rcmgr=debug" to enable detailed logging from the resource manager. This helps in diagnosing 'resource limit exceeded' errors by providing context in the logs. ```bash export GOLOG_LOG_LEVEL="rcmgr=debug" ``` -------------------------------- ### Expose Prometheus Metrics Endpoint Source: https://github.com/libp2p/go-libp2p/blob/master/dashboards/README.md Add this Go code to expose a metrics collection endpoint for Prometheus. This is useful for local development and debugging. It uses the same endpoint as Kubo. ```go import "github.com/prometheus/client_golang/prometheus/promhttp" go func() { http.Handle("/debug/metrics/prometheus", promhttp.Handler()) log.Fatal(http.ListenAndServe(":5001", nil)) }() ``` -------------------------------- ### Find Nearby Peers Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-rendezvous/README.md Searches for peers that have announced their presence for a given rendezvous string. This utilizes the DHT to find providers. ```go peerChan, err := routingDiscovery.FindPeers(ctx, config.RendezvousString) ``` -------------------------------- ### Publish Message to Chat Room Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/chat/README.md Encodes a string message into a ChatMessage struct, marshals it to JSON, and publishes it to the PubSub topic. Returns an error if JSON marshaling or publishing fails. ```go func (cr *ChatRoom) Publish(message string) error { m := ChatMessage{ Message: message, SenderID: cr.self.String(), SenderNick: cr.nick, } msgBytes, err := json.Marshal(m) if err != nil { return err } return cr.topic.Publish(cr.ctx, msgBytes) } ``` -------------------------------- ### Chat UI Event Handling Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/chat/README.md Manages the chat UI's event loop, handling user input for publishing messages, receiving messages from the chat room, and periodically refreshing the peer list. Stops when the chat room context is done or a done channel is signaled. ```go func (ui *ChatUI) handleEvents() { peerRefreshTicker := time.NewTicker(time.Second) defer peerRefreshTicker.Stop() for { select { case input := <-ui.inputCh: // when the user types in a line, publish it to the chat room and print to the message window err := ui.cr.Publish(input) if err != nil { printErr("publish error: %s", err) } ui.displaySelfMessage(input) case m := <-ui.cr.Messages: // when we receive a message from the chat room, print it to the message window ui.displayChatMessage(m) case <-peerRefreshTicker.C: // refresh the list of peers in the chat room periodically ui.refreshPeers() case <-ui.cr.ctx.Done(): return case <-ui.doneCh: return } } } ``` -------------------------------- ### Advertise Presence with Rendezvous Point Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-rendezvous/README.md Announces the node's presence and availability to provide a value for a specific key (rendezvous string) using the DHT's routing capabilities. ```go routingDiscovery := discovery.NewRoutingDiscovery(kademliaDHT) discovery.Advertise(ctx, routingDiscovery, config.RendezvousString) ``` -------------------------------- ### Read Loop for Incoming Messages Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/chat/README.md Continuously reads messages from the PubSub subscription, unmarshals them from JSON into ChatMessage structs, and sends valid messages to the Messages channel. Skips messages sent by the local peer. Closes the Messages channel on subscription error. ```go func (cr *ChatRoom) readLoop() { for { msg, err := cr.sub.Next(cr.ctx) if err != nil { close(cr.Messages) return } // only forward messages delivered by others if msg.ReceivedFrom == cr.self { continue } cm := new(ChatMessage) err = json.Unmarshal(msg.Data, cm) if err != nil { continue } // send valid messages onto the Messages channel cr.Messages <- cm } } ``` -------------------------------- ### Set Default Stream Handler Source: https://github.com/libp2p/go-libp2p/blob/master/examples/chat-with-mdns/README.md Defines a function to handle incoming data streams from remote peers. This function is invoked when a peer initiates a connection and opens a stream. ```go // Set a function as stream handler. host.SetStreamHandler("/chat/1.1.0", handleStream) ``` -------------------------------- ### Change Chat Topic Name Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/basic-chat-with-rendezvous/README.md Customize the chat topic by using the `-topicName` flag when running the application. This allows multiple independent chat rooms to exist. ```shell go run . -topicName=adifferenttopic ``` -------------------------------- ### ChatMessage Struct Definition Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/chat/README.md Defines the structure for messages exchanged in the chat room, including the message content, sender's ID, and sender's nickname. ```go type ChatMessage struct { Message string SenderID string SenderNick string } ``` -------------------------------- ### List Peers in Chat Room Source: https://github.com/libp2p/go-libp2p/blob/master/examples/pubsub/chat/README.md Retrieves a list of peer IDs currently subscribed to the chat room's topic using the underlying PubSub service. ```go func (cr *ChatRoom) ListPeers() []peer.ID { return cr.ps.ListPeers(topicName(cr.roomName)) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.