main.go 1.86 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

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

	bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
	ps "gx/ipfs/QmPgDWmTmuzvP7QE5zwo1TmjbJme9pmZHNujB2453jkCTr/go-libp2p-peerstore"
	swarm "gx/ipfs/QmU219N3jn7QadVCeBUqGnAkwoXoUomrCwDuVQVuL7PB5W/go-libp2p-swarm"
	ma "gx/ipfs/QmXY77cVe7rVRQXZZQRioukUM7aRW3BTcAgJe12MCtb3Ji/go-multiaddr"
	peer "gx/ipfs/QmXYjuNuxVzXKJCfWasQk1RqkhVLDM9jtUKhqc2WPQmFSB/go-libp2p-peer"
	crypto "gx/ipfs/QmaPbCnUMBohSGo3KnxEa2bHqyJVVeEEcwtqJAYxerieBo/go-libp2p-crypto"
)

// 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
Aviv Eyal's avatar
Aviv Eyal committed
21
	priv, pub, _ := crypto.GenerateKeyPair(crypto.Secp256k1, 256)
22
23
24
25
26
27
28
29
	pid, _ := peer.IDFromPublicKey(pub)
	listen, _ := ma.NewMultiaddr(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", port))
	peerStore := ps.NewPeerstore()
	peerStore.AddPrivKey(pid, priv)
	peerStore.AddPubKey(pid, pub)
	n, _ := swarm.NewNetwork(context.Background(), []ma.Multiaddr{listen}, pid, peerStore, nil)
	host := bhost.New(n)

Aviv Eyal's avatar
Aviv Eyal committed
30
31
	log.Printf("New host id (base58 multihash):%s, length:%d", host.ID().Pretty(), len(host.ID().Pretty()))

32
33
34
35
36
37
38
39
40
41
42
43
44
45
	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
46
47
	h1.Peerstore().AddAddrs(h2.ID(), h2.Addrs(), ps.PermanentAddrTTL)
	h2.Peerstore().AddAddrs(h1.ID(), h1.Addrs(), ps.PermanentAddrTTL)
48

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

Aviv Eyal's avatar
Aviv Eyal committed
51
	// send messages using the protocols
Aviv Eyal's avatar
Aviv Eyal committed
52
53
54
55
	h1.Ping(h2.Host)
	h2.Ping(h1.Host)
	h1.Echo(h2.Host)
	h2.Echo(h1.Host)
56

Aviv Eyal's avatar
Aviv Eyal committed
57
58
59
60
	// block until all responses have been processed
	for i := 0; i < 4; i++ {
		<-done
	}
Aviv Eyal's avatar
Aviv Eyal committed
61
}