main.go 1.35 KB
Newer Older
1
2
3
4
5
6
7
8
package main

import (
	"context"
	"fmt"
	"log"
	"math/rand"

Steven Allen's avatar
Steven Allen committed
9
	libp2p "github.com/libp2p/go-libp2p"
Steven Allen's avatar
Steven Allen committed
10
11
12
	crypto "github.com/libp2p/go-libp2p-crypto"
	ps "github.com/libp2p/go-libp2p-peerstore"
	ma "github.com/multiformats/go-multiaddr"
13
14
15
16
17
18
)

// helper method - create a lib-p2p host to listen on a port
func makeRandomNode(port int, done chan bool) *Node {
	// Ignoring most errors for brevity
	// See echo example for more details and better implementation
Steven Allen's avatar
Steven Allen committed
19
	priv, _, _ := crypto.GenerateKeyPair(crypto.Secp256k1, 256)
20
	listen, _ := ma.NewMultiaddr(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", port))
Steven Allen's avatar
Steven Allen committed
21
22
23
24
25
	host, _ := libp2p.New(
		context.Background(),
		libp2p.ListenAddrs(listen),
		libp2p.Identity(priv),
	)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

	return NewNode(host, done)
}

func main() {
	// Choose random ports between 10000-10100
	rand.Seed(666)
	port1 := rand.Intn(100) + 10000
	port2 := port1 + 1

	done := make(chan bool, 1)

	// Make 2 hosts
	h1 := makeRandomNode(port1, done)
	h2 := makeRandomNode(port2, done)
Aviv Eyal's avatar
Aviv Eyal committed
41
42
	h1.Peerstore().AddAddrs(h2.ID(), h2.Addrs(), ps.PermanentAddrTTL)
	h2.Peerstore().AddAddrs(h1.ID(), h1.Addrs(), ps.PermanentAddrTTL)
43

Aviv Eyal's avatar
Aviv Eyal committed
44
	log.Printf("This is a conversation between %s and %s\n", h1.ID(), h2.ID())
45

Aviv Eyal's avatar
Aviv Eyal committed
46
	// send messages using the protocols
Aviv Eyal's avatar
Aviv Eyal committed
47
48
49
50
	h1.Ping(h2.Host)
	h2.Ping(h1.Host)
	h1.Echo(h2.Host)
	h2.Echo(h1.Host)
51

Aviv Eyal's avatar
Aviv Eyal committed
52
53
54
55
	// block until all responses have been processed
	for i := 0; i < 4; i++ {
		<-done
	}
Aviv Eyal's avatar
Aviv Eyal committed
56
}