libp2p.go 5.13 KB
Newer Older
1
2
3
4
5
package libp2p

import (
	"context"
	"crypto/rand"
Jeromy's avatar
Jeromy committed
6
	"fmt"
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

	crypto "github.com/libp2p/go-libp2p-crypto"
	host "github.com/libp2p/go-libp2p-host"
	pnet "github.com/libp2p/go-libp2p-interface-pnet"
	metrics "github.com/libp2p/go-libp2p-metrics"
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
	swarm "github.com/libp2p/go-libp2p-swarm"
	transport "github.com/libp2p/go-libp2p-transport"
	bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
	mux "github.com/libp2p/go-stream-muxer"
	ma "github.com/multiformats/go-multiaddr"
	mplex "github.com/whyrusleeping/go-smux-multiplex"
	msmux "github.com/whyrusleeping/go-smux-multistream"
	yamux "github.com/whyrusleeping/go-smux-yamux"
)

Jeromy's avatar
Jeromy committed
24
// Config describes a set of settings for a libp2p node
25
type Config struct {
Jeromy's avatar
Jeromy committed
26
27
28
29
30
31
32
33
	Transports   []transport.Transport
	Muxer        mux.Transport
	ListenAddrs  []ma.Multiaddr
	PeerKey      crypto.PrivKey
	Peerstore    pstore.Peerstore
	Protector    pnet.Protector
	Reporter     metrics.Reporter
	DisableSecio bool
34
35
}

Jeromy's avatar
Jeromy committed
36
37
type Option func(cfg *Config) error

Jeromy's avatar
Jeromy committed
38
func Transports(tpts ...transport.Transport) Option {
Jeromy's avatar
Jeromy committed
39
	return func(cfg *Config) error {
Jeromy's avatar
Jeromy committed
40
		cfg.Transports = append(cfg.Transports, tpts...)
Jeromy's avatar
Jeromy committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
		return nil
	}
}

func ListenAddrStrings(s ...string) Option {
	return func(cfg *Config) error {
		for _, addrstr := range s {
			a, err := ma.NewMultiaddr(addrstr)
			if err != nil {
				return err
			}
			cfg.ListenAddrs = append(cfg.ListenAddrs, a)
		}
		return nil
	}
}

Jeromy's avatar
Jeromy committed
58
func ListenAddrs(addrs ...ma.Multiaddr) Option {
Jeromy's avatar
Jeromy committed
59
60
61
62
63
64
	return func(cfg *Config) error {
		cfg.ListenAddrs = append(cfg.ListenAddrs, addrs...)
		return nil
	}
}

Jeromy's avatar
Jeromy committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
type transportEncOpt int

const (
	EncPlaintext = transportEncOpt(0)
	EncSecio     = transportEncOpt(1)
)

func TransportEncryption(tenc ...transportEncOpt) Option {
	return func(cfg *Config) error {
		if len(tenc) != 1 {
			return fmt.Errorf("can only specify a single transport encryption option right now")
		}

		// TODO: actually make this pluggable, otherwise tls will get tricky
		switch tenc[0] {
		case EncPlaintext:
			cfg.DisableSecio = true
		case EncSecio:
			// noop
		default:
			return fmt.Errorf("unrecognized transport encryption option: %d", tenc[0])
		}
		return nil
	}
Jeromy's avatar
Jeromy committed
89
90
}

Jeromy's avatar
Jeromy committed
91
92
93
94
95
func NoEncryption() Option {
	return TransportEncryption(EncPlaintext)
}

func Muxer(m mux.Transport) Option {
Jeromy's avatar
Jeromy committed
96
	return func(cfg *Config) error {
Jeromy's avatar
Jeromy committed
97
98
99
100
		if cfg.Muxer != nil {
			return fmt.Errorf("cannot specify multiple muxer options")
		}

Jeromy's avatar
Jeromy committed
101
102
103
104
105
		cfg.Muxer = m
		return nil
	}
}

Jeromy's avatar
Jeromy committed
106
func Peerstore(ps pstore.Peerstore) Option {
Jeromy's avatar
Jeromy committed
107
	return func(cfg *Config) error {
Jeromy's avatar
Jeromy committed
108
109
110
111
		if cfg.Peerstore != nil {
			return fmt.Errorf("cannot specify multiple peerstore options")
		}

Jeromy's avatar
Jeromy committed
112
113
114
115
116
		cfg.Peerstore = ps
		return nil
	}
}

Jeromy's avatar
Jeromy committed
117
func PrivateNetwork(prot pnet.Protector) Option {
Jeromy's avatar
Jeromy committed
118
	return func(cfg *Config) error {
Jeromy's avatar
Jeromy committed
119
120
121
122
		if cfg.Protector != nil {
			return fmt.Errorf("cannot specify multiple private network options")
		}

Jeromy's avatar
Jeromy committed
123
124
125
126
127
		cfg.Protector = prot
		return nil
	}
}

Jeromy's avatar
Jeromy committed
128
func BandwidthReporter(rep metrics.Reporter) Option {
Jeromy's avatar
Jeromy committed
129
	return func(cfg *Config) error {
Jeromy's avatar
Jeromy committed
130
131
132
133
		if cfg.Reporter != nil {
			return fmt.Errorf("cannot specify multiple bandwidth reporter options")
		}

Jeromy's avatar
Jeromy committed
134
135
136
137
138
		cfg.Reporter = rep
		return nil
	}
}

Jeromy's avatar
Jeromy committed
139
140
141
142
func Identity(sk crypto.PrivKey) Option {
	return func(cfg *Config) error {
		if cfg.PeerKey != nil {
			return fmt.Errorf("cannot specify multiple identities")
Jeromy's avatar
Jeromy committed
143
144
145
146
147
		}

		cfg.PeerKey = sk
		return nil
	}
Jeromy's avatar
Jeromy committed
148
149
}

Jeromy's avatar
Jeromy committed
150
151
152
153
154
155
func New(ctx context.Context, opts ...Option) (host.Host, error) {
	var cfg Config
	for _, opt := range opts {
		if err := opt(&cfg); err != nil {
			return nil, err
		}
156
157
	}

Jeromy's avatar
Jeromy committed
158
159
160
161
	return newWithCfg(ctx, &cfg)
}

func newWithCfg(ctx context.Context, cfg *Config) (host.Host, error) {
Jeromy's avatar
Jeromy committed
162
	// If no key was given, generate a random 2048 bit RSA key
163
164
165
166
167
168
169
170
171
172
173
174
175
176
	if cfg.PeerKey == nil {
		priv, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, rand.Reader)
		if err != nil {
			return nil, err
		}
		cfg.PeerKey = priv
	}

	// Obtain Peer ID from public key
	pid, err := peer.IDFromPublicKey(cfg.PeerKey.GetPublic())
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
177
	// Create a new blank peerstore if none was passed in
178
179
180
181
182
	ps := cfg.Peerstore
	if ps == nil {
		ps = pstore.NewPeerstore()
	}

183
184
185
186
187
188
	// Set default muxer if none was passed in
	muxer := cfg.Muxer
	if muxer == nil {
		muxer = DefaultMuxer()
	}

Jeromy's avatar
Jeromy committed
189
190
191
192
193
	// If secio is disabled, don't add our private key to the peerstore
	if !cfg.DisableSecio {
		ps.AddPrivKey(pid, cfg.PeerKey)
		ps.AddPubKey(pid, cfg.PeerKey.GetPublic())
	}
194

195
	swrm, err := swarm.NewSwarmWithProtector(ctx, cfg.ListenAddrs, pid, ps, cfg.Protector, muxer, cfg.Reporter)
196
197
198
199
200
201
202
203
204
205
206
207
	if err != nil {
		return nil, err
	}

	netw := (*swarm.Network)(swrm)

	return bhost.New(netw), nil
}

func DefaultMuxer() mux.Transport {
	// Set up stream multiplexer
	tpt := msmux.NewBlankTransport()
Jeromy's avatar
Jeromy committed
208
209

	// By default, support yamux and multiplex
210
211
	tpt.AddTransport("/yamux/1.0.0", yamux.DefaultTransport)
	tpt.AddTransport("/mplex/6.3.0", mplex.DefaultTransport)
Jeromy's avatar
Jeromy committed
212

213
214
215
	return tpt
}

Jeromy's avatar
Jeromy committed
216
func Defaults(cfg *Config) error {
Jeromy's avatar
Jeromy committed
217
218
	// Create a multiaddress that listens on a random port on all interfaces
	addr, err := ma.NewMultiaddr("/ip4/0.0.0.0/tcp/0")
219
	if err != nil {
Jeromy's avatar
Jeromy committed
220
		return err
221
222
	}

Jeromy's avatar
Jeromy committed
223
224
225
226
	cfg.ListenAddrs = []ma.Multiaddr{addr}
	cfg.Peerstore = pstore.NewPeerstore()
	cfg.Muxer = DefaultMuxer()
	return nil
227
}