main.go 4.64 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

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

Hector Sanjuan's avatar
Hector Sanjuan committed
25
26
27
28
29
30
31
32
33
34
35
36
// 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
37
38
39
40
	if err != nil {
		return nil, err
	}

Hector Sanjuan's avatar
Hector Sanjuan committed
41
42
43
44
45
46
47
48
	// 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
49
50
	ps := pstore.NewPeerstore()

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

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

Hector Sanjuan's avatar
Hector Sanjuan committed
66
67
68
69
70
71
72
73
74
75
76
77
78
	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
79
80
	}

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

func main() {
Hector Sanjuan's avatar
Hector Sanjuan committed
85
86
87
	// 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
88
	golog.SetAllLoggers(gologging.INFO) // Change to DEBUG for extra info
Hector Sanjuan's avatar
Hector Sanjuan committed
89
90

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

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

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

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

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

Hector Sanjuan's avatar
Hector Sanjuan committed
120
121
	// The following code extracts target's the peer ID from the
	// given multiaddress
Jeromy's avatar
Jeromy committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
	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
137
138
139
140
141
	// 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
142

Hector Sanjuan's avatar
Hector Sanjuan committed
143
144
145
	// 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
146

Lars Gierth's avatar
Lars Gierth committed
147
	log.Println("opening stream")
Jeromy's avatar
Jeromy committed
148
	// make a new stream from host B to host A
Hector Sanjuan's avatar
Hector Sanjuan committed
149
150
	// 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
151
	s, err := ha.NewStream(context.Background(), peerid, "/echo/1.0.0")
Jeromy's avatar
Jeromy committed
152
153
154
155
	if err != nil {
		log.Fatalln(err)
	}

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

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

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

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

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