main.go 4.59 KB
Newer Older
Jeromy's avatar
Jeromy committed
1
2
3
package main

import (
Hector Sanjuan's avatar
Hector Sanjuan committed
4
	"bufio"
5
	"context"
Jeromy's avatar
Jeromy committed
6
7
8
9
10
	"flag"
	"fmt"
	"io/ioutil"
	"log"

Hector Sanjuan's avatar
Hector Sanjuan committed
11
	golog "github.com/ipfs/go-log"
Hector Sanjuan's avatar
Hector Sanjuan committed
12
	crypto "github.com/libp2p/go-libp2p-crypto"
Jeromy's avatar
Jeromy committed
13
	host "github.com/libp2p/go-libp2p-host"
Jeromy's avatar
Jeromy committed
14
	net "github.com/libp2p/go-libp2p-net"
Jeromy's avatar
Jeromy committed
15
16
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
Jeromy's avatar
Jeromy committed
17
	swarm "github.com/libp2p/go-libp2p-swarm"
Jeromy's avatar
Jeromy committed
18
	ma "github.com/multiformats/go-multiaddr"
Hector Sanjuan's avatar
Hector Sanjuan committed
19
	gologging "github.com/whyrusleeping/go-logging"
Hector Sanjuan's avatar
Hector Sanjuan committed
20
21

	bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
Jeromy's avatar
Jeromy committed
22
23
)

Hector Sanjuan's avatar
Hector Sanjuan committed
24
25
26
27
28
29
30
31
32
33
34
35
// makeBasicHost creates a LibP2P host with a random peer ID listening on the
// given multiaddress. It will use secio if secio is true.
func makeBasicHost(listenPort int, secio bool) (host.Host, error) {
	// Generate a key pair for this host. We will use it at least
	// to obtain a valid host ID.
	priv, pub, err := crypto.GenerateKeyPair(crypto.RSA, 2048)
	if err != nil {
		return nil, err
	}

	// Obtain Peer ID from public key
	pid, err := peer.IDFromPublicKey(pub)
Jeromy's avatar
Jeromy committed
36
37
38
39
	if err != nil {
		return nil, err
	}

Hector Sanjuan's avatar
Hector Sanjuan committed
40
41
42
43
44
45
46
47
	// Create a multiaddress
	addr, err := ma.NewMultiaddr(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", listenPort))

	if err != nil {
		return nil, err
	}

	// Create a peerstore
Jeromy's avatar
Jeromy committed
48
49
	ps := pstore.NewPeerstore()

Hector Sanjuan's avatar
Hector Sanjuan committed
50
51
	// If using secio, we add the keys to the peerstore
	// for this peer ID.
Jeromy's avatar
Jeromy committed
52
	if secio {
Hector Sanjuan's avatar
Hector Sanjuan committed
53
54
		ps.AddPrivKey(pid, priv)
		ps.AddPubKey(pid, pub)
Jeromy's avatar
Jeromy committed
55
56
	}

Hector Sanjuan's avatar
Hector Sanjuan committed
57
58
59
60
61
62
63
	// Create swarm (implements libP2P Network)
	netwrk, err := swarm.NewNetwork(
		context.Background(),
		[]ma.Multiaddr{addr},
		pid,
		ps,
		nil)
Jeromy's avatar
Jeromy committed
64

Hector Sanjuan's avatar
Hector Sanjuan committed
65
66
67
68
69
70
71
72
73
74
75
76
77
	basicHost := bhost.New(netwrk)

	// Build host multiaddress
	hostAddr, _ := ma.NewMultiaddr(fmt.Sprintf("/ipfs/%s", basicHost.ID().Pretty()))

	// Now we can build a full multiaddress to reach this host
	// by encapsulating both addresses:
	fullAddr := addr.Encapsulate(hostAddr)
	log.Printf("I am %s\n", fullAddr)
	if secio {
		log.Printf("Now run \"./echo -l %d -d %s -secio\" on a different terminal\n", listenPort+1, fullAddr)
	} else {
		log.Printf("Now run \"./echo -l %d -d %s\" on a different terminal\n", listenPort+1, fullAddr)
Jeromy's avatar
Jeromy committed
78
79
	}

Hector Sanjuan's avatar
Hector Sanjuan committed
80
	return basicHost, nil
Jeromy's avatar
Jeromy committed
81
82
83
}

func main() {
Hector Sanjuan's avatar
Hector Sanjuan committed
84
85
86
	// LibP2P code uses golog to log messages. They log with different
	// string IDs (i.e. "swarm"). We can control the verbosity level for
	// all loggers with:
Hector Sanjuan's avatar
Hector Sanjuan committed
87
	golog.SetAllLoggers(gologging.INFO) // Change to DEBUG for extra info
Hector Sanjuan's avatar
Hector Sanjuan committed
88
89

	// Parse options from the command line
Jeromy's avatar
Jeromy committed
90
91
	listenF := flag.Int("l", 0, "wait for incoming connections")
	target := flag.String("d", "", "target peer to dial")
Jeromy's avatar
Jeromy committed
92
	secio := flag.Bool("secio", false, "enable secio")
Jeromy's avatar
Jeromy committed
93
94
	flag.Parse()

Hector Sanjuan's avatar
Hector Sanjuan committed
95
96
97
98
	if *listenF == 0 {
		log.Fatal("Please provide a port to bind on with -l")
	}

Hector Sanjuan's avatar
Hector Sanjuan committed
99
100
	// Make a host that listens on the given multiaddress
	ha, err := makeBasicHost(*listenF, *secio)
Jeromy's avatar
Jeromy committed
101
102
103
104
	if err != nil {
		log.Fatal(err)
	}

Hector Sanjuan's avatar
Hector Sanjuan committed
105
106
	// Set a stream handler on host A. /echo/1.0.0 is
	// a user-defined protocol name.
Jeromy's avatar
Jeromy committed
107
	ha.SetStreamHandler("/echo/1.0.0", func(s net.Stream) {
Hector Sanjuan's avatar
Hector Sanjuan committed
108
		log.Println("Got a new stream!")
Jeromy's avatar
Jeromy committed
109
		defer s.Close()
Hector Sanjuan's avatar
Hector Sanjuan committed
110
		doEcho(s)
Jeromy's avatar
Jeromy committed
111
112
113
	})

	if *target == "" {
Lars Gierth's avatar
Lars Gierth committed
114
		log.Println("listening for connections")
Jeromy's avatar
Jeromy committed
115
		select {} // hang forever
Jeromy's avatar
Jeromy committed
116
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
117
	/**** This is where the listener code ends ****/
Jeromy's avatar
Jeromy committed
118

Hector Sanjuan's avatar
Hector Sanjuan committed
119
120
	// The following code extracts target's the peer ID from the
	// given multiaddress
Jeromy's avatar
Jeromy committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
	ipfsaddr, err := ma.NewMultiaddr(*target)
	if err != nil {
		log.Fatalln(err)
	}

	pid, err := ipfsaddr.ValueForProtocol(ma.P_IPFS)
	if err != nil {
		log.Fatalln(err)
	}

	peerid, err := peer.IDB58Decode(pid)
	if err != nil {
		log.Fatalln(err)
	}

Hector Sanjuan's avatar
Hector Sanjuan committed
136
137
138
139
140
	// Decapsulate the /ipfs/<peerID> part from the target
	// /ip4/<a.b.c.d>/ipfs/<peer> becomes /ip4/<a.b.c.d>
	targetPeerAddr, _ := ma.NewMultiaddr(
		fmt.Sprintf("/ipfs/%s", peer.IDB58Encode(peerid)))
	targetAddr := ipfsaddr.Decapsulate(targetPeerAddr)
Jeromy's avatar
Jeromy committed
141

Hector Sanjuan's avatar
Hector Sanjuan committed
142
143
144
	// We have a peer ID and a targetAddr so we add it to the peerstore
	// so LibP2P knows how to contact it
	ha.Peerstore().AddAddr(peerid, targetAddr, peerstore.PermanentAddrTTL)
Jeromy's avatar
Jeromy committed
145

Lars Gierth's avatar
Lars Gierth committed
146
	log.Println("opening stream")
Jeromy's avatar
Jeromy committed
147
	// make a new stream from host B to host A
Hector Sanjuan's avatar
Hector Sanjuan committed
148
149
	// it should be handled on host A by the handler we set above because
	// we use the same /echo/1.0.0 protocol
Lars Gierth's avatar
Lars Gierth committed
150
	s, err := ha.NewStream(context.Background(), peerid, "/echo/1.0.0")
Jeromy's avatar
Jeromy committed
151
152
153
154
	if err != nil {
		log.Fatalln(err)
	}

Hector Sanjuan's avatar
Hector Sanjuan committed
155
	_, err = s.Write([]byte("Hello, world!\n"))
Jeromy's avatar
Jeromy committed
156
157
158
159
	if err != nil {
		log.Fatalln(err)
	}

Jeromy's avatar
Jeromy committed
160
161
162
163
164
	out, err := ioutil.ReadAll(s)
	if err != nil {
		log.Fatalln(err)
	}

Lars Gierth's avatar
Lars Gierth committed
165
	log.Printf("read reply: %q\n", out)
Jeromy's avatar
Jeromy committed
166
}
Jeromy's avatar
Jeromy committed
167

Hector Sanjuan's avatar
Hector Sanjuan committed
168
// doEcho reads a line of data a stream and writes it back
169
func doEcho(s net.Stream) {
Hector Sanjuan's avatar
Hector Sanjuan committed
170
171
	buf := bufio.NewReader(s)
	str, err := buf.ReadString('\n')
Lars Gierth's avatar
Lars Gierth committed
172
173
174
175
	if err != nil {
		log.Println(err)
		return
	}
Jeromy's avatar
Jeromy committed
176

Hector Sanjuan's avatar
Hector Sanjuan committed
177
178
	log.Printf("read: %s\n", str)
	_, err = s.Write([]byte(str))
Lars Gierth's avatar
Lars Gierth committed
179
180
181
	if err != nil {
		log.Println(err)
		return
Jeromy's avatar
Jeromy committed
182
183
	}
}