core.go 26.7 KB
Newer Older
1 2 3 4
/*
Package core implements the IpfsNode object and related methods.

Packages underneath core/ provide a (relatively) stable, low-level API
5 6 7 8
to carry out most IPFS-related tasks.  For more details on the other
interfaces and how core/... fits into the bigger IPFS picture, see:

  $ godoc github.com/ipfs/go-ipfs
9
*/
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10 11
package core

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12
import (
Jakub Sztandera's avatar
Jakub Sztandera committed
13
	"bytes"
14
	"context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
	"errors"
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
16
	"fmt"
17
	"io"
18
	"io/ioutil"
Jeromy's avatar
Jeromy committed
19
	"net"
20 21
	"os"
	"strings"
22
	"time"
23

24 25 26 27
	bserv "github.com/ipfs/go-ipfs/blockservice"
	bitswap "github.com/ipfs/go-ipfs/exchange/bitswap"
	bsnet "github.com/ipfs/go-ipfs/exchange/bitswap/network"
	rp "github.com/ipfs/go-ipfs/exchange/reprovide"
28
	filestore "github.com/ipfs/go-ipfs/filestore"
29 30 31 32 33
	mount "github.com/ipfs/go-ipfs/fuse/mount"
	merkledag "github.com/ipfs/go-ipfs/merkledag"
	mfs "github.com/ipfs/go-ipfs/mfs"
	namesys "github.com/ipfs/go-ipfs/namesys"
	ipnsrp "github.com/ipfs/go-ipfs/namesys/republisher"
Łukasz Magiera's avatar
Łukasz Magiera committed
34
	p2p "github.com/ipfs/go-ipfs/p2p"
35
	"github.com/ipfs/go-ipfs/path/resolver"
36 37 38 39
	pin "github.com/ipfs/go-ipfs/pin"
	repo "github.com/ipfs/go-ipfs/repo"
	config "github.com/ipfs/go-ipfs/repo/config"
	ft "github.com/ipfs/go-ipfs/unixfs"
Jeromy's avatar
Jeromy committed
40

Steven Allen's avatar
Steven Allen committed
41
	u "gx/ipfs/QmNiJuT8Ja3hMVpBHXv3Q6dwmperaQ6JjLtpMQgMCD7xvx/go-ipfs-util"
Steven Allen's avatar
Steven Allen committed
42 43 44
	circuit "gx/ipfs/QmR5sXZi68rm9m2E3KiXj6hE5m3GeLaDjbLPUeV6W3MLR8/go-libp2p-circuit"
	floodsub "gx/ipfs/QmRMgHdiLHJvySrXbtLBehr1W1yTQyuNmZG8HghG54ZPDz/go-libp2p-floodsub"
	swarm "gx/ipfs/QmRpKdg1xs4Yyrn9yrVYRBp7AQqyRxMLpD6Jgp1eZAGqEr/go-libp2p-swarm"
45
	goprocess "gx/ipfs/QmSF8fPo3jgVBAy8fpdjjYqgG87dkJgUprRBHRd2tmfgpP/goprocess"
Steven Allen's avatar
Steven Allen committed
46
	pnet "gx/ipfs/QmSGoP33Ufev1UDsUuHco8rfhVTzxfq6smXhwhN16c5CWd/go-libp2p-pnet"
Jeromy's avatar
Jeromy committed
47
	mamask "gx/ipfs/QmSMZwvs3n4GBikZ7hKzT17c3bk65FmyZo2JqtJ16swqCv/multiaddr-filter"
Steven Allen's avatar
Steven Allen committed
48 49
	logging "gx/ipfs/QmTG23dvpBCBjqQwyDxV8CQT6jmS4PSftNr1VqHhE3MLy7/go-log"
	addrutil "gx/ipfs/QmTGSre9j1otFgsr1opCUQDXTPSM6BTZnMWwPeA5nYJM7w/go-addr-util"
50
	record "gx/ipfs/QmTUyK82BVPA6LmSzEJpfEunk9uBaQzWtMsNP917tVj4sT/go-libp2p-record"
Steven Allen's avatar
Steven Allen committed
51 52
	routing "gx/ipfs/QmUHRKTeaoASDvDj7cTAXsmjAY7KQ13ErtzkQHZQq6uFUz/go-libp2p-routing"
	metrics "gx/ipfs/QmVvu4bS5QLfS19ePkp5Wgzn2ZUma5oXTT9BgDFyQLxUZF/go-libp2p-metrics"
Steven Allen's avatar
Steven Allen committed
53
	psrouter "gx/ipfs/QmWKLW1C2jmGAEzX8jNpCTii6n2ScGxytnoRMRdNTK5Knt/go-libp2p-pubsub-router"
Steven Allen's avatar
Steven Allen committed
54
	ma "gx/ipfs/QmWWQ2Txc2c6tqjsBpzg5Ar652cHPGNsQQp2SejkNmkUMb/go-multiaddr"
Steven Allen's avatar
Steven Allen committed
55 56 57 58 59 60
	mssmux "gx/ipfs/QmWzjXAyBTygw6CeCTUnhJzhFucfxY5FJivSoiGuiSbPjS/go-smux-multistream"
	discovery "gx/ipfs/QmY6iAoG9DVgZwh5ZRcQEpa2uErAe1Hbei8qXPCjpDS9Ge/go-libp2p/p2p/discovery"
	p2pbhost "gx/ipfs/QmY6iAoG9DVgZwh5ZRcQEpa2uErAe1Hbei8qXPCjpDS9Ge/go-libp2p/p2p/host/basic"
	rhost "gx/ipfs/QmY6iAoG9DVgZwh5ZRcQEpa2uErAe1Hbei8qXPCjpDS9Ge/go-libp2p/p2p/host/routed"
	identify "gx/ipfs/QmY6iAoG9DVgZwh5ZRcQEpa2uErAe1Hbei8qXPCjpDS9Ge/go-libp2p/p2p/protocol/identify"
	ping "gx/ipfs/QmY6iAoG9DVgZwh5ZRcQEpa2uErAe1Hbei8qXPCjpDS9Ge/go-libp2p/p2p/protocol/ping"
Steven Allen's avatar
Steven Allen committed
61
	smux "gx/ipfs/QmY9JXR3FupnYAYJWK9aMr9bCpqWKcToQ1tz8DVGTrHpHw/go-stream-muxer"
Steven Allen's avatar
Steven Allen committed
62 63
	mplex "gx/ipfs/QmZeGmoJ3bEwEe6Huz6GKcHENWZCx7DReuAS5va4zP24PB/go-smux-multiplex"
	p2phost "gx/ipfs/QmaSfSMvc1VPZ8JbMponFs4WHvF9FgEruF56opm5E1RgQA/go-libp2p-host"
Steven Allen's avatar
Steven Allen committed
64 65
	bstore "gx/ipfs/QmayRSLCiM2gWR7Kay8vqu3Yy5mf7yPqocF9ZRgDUPYMcc/go-ipfs-blockstore"
	connmgr "gx/ipfs/Qmbe3mKoxoRtHoziHxfAGoTJPPTh4QTB7nmhZjqeviLhs4/go-libp2p-connmgr"
Steven Allen's avatar
Steven Allen committed
66 67
	nilrouting "gx/ipfs/QmcE3B6ittYBmctva8Q155LPa1YPcVqg8N7pPcgt9i7iAQ/go-ipfs-routing/none"
	offroute "gx/ipfs/QmcE3B6ittYBmctva8Q155LPa1YPcVqg8N7pPcgt9i7iAQ/go-ipfs-routing/offline"
Steven Allen's avatar
Steven Allen committed
68
	peer "gx/ipfs/QmcJukH2sAFjY3HdBKq35WDzWoL3UUu2gt9wdfqZTUyM74/go-libp2p-peer"
Steven Allen's avatar
Steven Allen committed
69
	cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
Steven Allen's avatar
Steven Allen committed
70
	yamux "gx/ipfs/QmcsgrV3nCAKjiHKZhKVXWc4oY3WBECJCqahXEMpHeMrev/go-smux-yamux"
Steven Allen's avatar
Steven Allen committed
71
	ipnet "gx/ipfs/Qmd3oYWVLCVWryDV6Pobv6whZcvDXAHqS3chemZ658y4a8/go-libp2p-interface-pnet"
72
	exchange "gx/ipfs/QmdcAXgEHUueP4A7b5hjabKn2EooeHgMreMvFC249dGCgc/go-ipfs-exchange-interface"
Steven Allen's avatar
Steven Allen committed
73 74
	pstore "gx/ipfs/QmdeiKhUy1TVGBaKxt7y1QmBDLBdisSrLJ1x58Eoj4PXUh/go-libp2p-peerstore"
	ic "gx/ipfs/Qme1knMqwt1hKZbc1BmQFmnm9f36nyQGwXxPGVpVJ9rMK5/go-libp2p-crypto"
75
	ipld "gx/ipfs/Qme5bWv7wtjUNGsK2BNGVUFPKiuxWrsqrtvYwCLRw8YFES/go-ipld-format"
Steven Allen's avatar
Steven Allen committed
76 77
	dht "gx/ipfs/Qme6C1xZFKUQVxvj8Sb7afWiQxzkQt67gq5V2o85pivCjV/go-libp2p-kad-dht"
	dhtopts "gx/ipfs/Qme6C1xZFKUQVxvj8Sb7afWiQxzkQt67gq5V2o85pivCjV/go-libp2p-kad-dht/opts"
Steven Allen's avatar
Steven Allen committed
78
	ds "gx/ipfs/QmeiCcJfDW1GJnWUArudsv5rQsihpi4oyddPhdqo3CfX6i/go-datastore"
79
	rhelpers "gx/ipfs/QmeoG1seQ8a9b2vS3XJ8HPz9tXr6dzpS5NizjuDDSntQEk/go-libp2p-routing-helpers"
Steven Allen's avatar
Steven Allen committed
80
	mafilter "gx/ipfs/Qmf2UAmRwDG4TvnkQpHZWPAzw7rpCYVhxmRXmYxXr5LD1g/go-maddr-filter"
Steven Allen's avatar
Steven Allen committed
81
	ifconnmgr "gx/ipfs/QmfQNieWBPwmnUjXWPZbjJPzhNwFFabTb5RQ79dyVWGujQ/go-libp2p-interface-connmgr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82 83
)

Jeromy's avatar
Jeromy committed
84
const IpnsValidatorTag = "ipns"
85

86
const kReprovideFrequency = time.Hour * 12
87
const discoveryConnTimeout = time.Second * 30
Jeromy's avatar
Jeromy committed
88

Jeromy's avatar
Jeromy committed
89
var log = logging.Logger("core")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90

91 92 93 94
type mode int

const (
	// zero value is not a valid mode, must be explicitly set
95
	localMode mode = iota
96 97 98 99
	offlineMode
	onlineMode
)

100 101 102 103
func init() {
	identify.ClientVersion = "go-ipfs/" + config.CurrentVersionNumber + "/" + config.CurrentCommit
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
104
// IpfsNode is IPFS Core module. It represents an IPFS instance.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105 106
type IpfsNode struct {

107
	// Self
108
	Identity peer.ID // the local node's identity
109

110
	Repo repo.Repo
111 112

	// Local node
113 114 115 116
	Pinning         pin.Pinner // the pinning manager
	Mounts          Mounts     // current mount state, if any.
	PrivateKey      ic.PrivKey // the local node's private Key
	PNetFingerprint []byte     // fingerprint of private network
117 118

	// Services
Jeromy's avatar
Jeromy committed
119
	Peerstore  pstore.Peerstore     // storage for other Peer instances
120
	Blockstore bstore.GCBlockstore  // the block store (lower level)
121 122 123
	Filestore  *filestore.Filestore // the filestore blockstore
	BaseBlocks bstore.Blockstore    // the raw blockstore, no filestore wrapping
	GCLocker   bstore.GCLocker      // the locker used to protect the blockstore during gc
124
	Blocks     bserv.BlockService   // the block service, get/add blocks.
125
	DAG        ipld.DAGService      // the merkle dag service, get/add objects.
126
	Resolver   *resolver.Resolver   // the path resolution system
Jeromy's avatar
Jeromy committed
127
	Reporter   metrics.Reporter
128
	Discovery  discovery.Service
Jeromy's avatar
Jeromy committed
129
	FilesRoot  *mfs.Root
130 131

	// Online
132 133 134 135 136
	PeerHost     p2phost.Host        // the network host (server+client)
	Bootstrapper io.Closer           // the periodic bootstrapper
	Routing      routing.IpfsRouting // the routing system. recommend ipfs-dht
	Exchange     exchange.Interface  // the block exchange + strategy (bitswap)
	Namesys      namesys.NameSystem  // the name system, resolves paths to hashes
Jeromy's avatar
Jeromy committed
137 138
	Ping         *ping.PingService
	Reprovider   *rp.Reprovider // the value reprovider system
Jeromy's avatar
Jeromy committed
139
	IpnsRepub    *ipnsrp.Republisher
140

Jeromy's avatar
Jeromy committed
141
	Floodsub *floodsub.PubSub
142
	PSRouter *psrouter.PubsubValueStore
Łukasz Magiera's avatar
Łukasz Magiera committed
143
	P2P      *p2p.P2P
Jeromy's avatar
Jeromy committed
144

145 146
	proc goprocess.Process
	ctx  context.Context
147

Jeromy's avatar
Jeromy committed
148
	mode         mode
149
	localModeSet bool
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150 151
}

152 153 154 155 156 157 158 159
// Mounts defines what the node's mount state is. This should
// perhaps be moved to the daemon or mount. It's here because
// it needs to be accessible across daemon requests.
type Mounts struct {
	Ipfs mount.Mount
	Ipns mount.Mount
}

vyzo's avatar
vyzo committed
160
func (n *IpfsNode) startOnlineServices(ctx context.Context, routingOption RoutingOption, hostOption HostOption, do DiscoveryOption, pubsub, ipnsps, mplex bool) error {
161 162

	if n.PeerHost != nil { // already online.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163
		return errors.New("node already online")
164 165 166
	}

	// load private key
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167
	if err := n.LoadPrivateKey(); err != nil {
168 169 170
		return err
	}

Jeromy's avatar
Jeromy committed
171
	// get undialable addrs from config
172 173 174 175
	cfg, err := n.Repo.Config()
	if err != nil {
		return err
	}
Jeromy's avatar
Jeromy committed
176
	var addrfilter []*net.IPNet
177
	for _, s := range cfg.Swarm.AddrFilters {
Jeromy's avatar
Jeromy committed
178 179
		f, err := mamask.NewMask(s)
		if err != nil {
180
			return fmt.Errorf("incorrectly formatted address filter in config: %s", s)
Jeromy's avatar
Jeromy committed
181 182 183 184
		}
		addrfilter = append(addrfilter, f)
	}

185 186 187 188 189
	if !cfg.Swarm.DisableBandwidthMetrics {
		// Set reporter
		n.Reporter = metrics.NewBandwidthCounter()
	}

190 191
	tpt := makeSmuxTransport(mplex)

Jakub Sztandera's avatar
Jakub Sztandera committed
192 193 194 195 196 197 198 199 200
	swarmkey, err := n.Repo.SwarmKey()
	if err != nil {
		return err
	}

	var protec ipnet.Protector
	if swarmkey != nil {
		protec, err = pnet.NewProtector(bytes.NewReader(swarmkey))
		if err != nil {
201
			return fmt.Errorf("failed to configure private network: %s", err)
Jakub Sztandera's avatar
Jakub Sztandera committed
202
		}
203
		n.PNetFingerprint = protec.Fingerprint()
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
		go func() {
			t := time.NewTicker(30 * time.Second)
			<-t.C // swallow one tick
			for {
				select {
				case <-t.C:
					if ph := n.PeerHost; ph != nil {
						if len(ph.Network().Peers()) == 0 {
							log.Warning("We are in private network and have no peers.")
							log.Warning("This might be configuration mistake.")
						}
					}
				case <-n.Process().Closing():
					t.Stop()
					return
				}
			}
		}()
Jakub Sztandera's avatar
Jakub Sztandera committed
222 223
	}

224 225 226 227 228
	addrsFactory, err := makeAddrsFactory(cfg.Addresses)
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
229 230 231 232 233
	connmgr, err := constructConnMgr(cfg.Swarm.ConnMgr)
	if err != nil {
		return err
	}

234 235 236
	hostopts := &ConstructPeerHostOpts{
		AddrsFactory:      addrsFactory,
		DisableNatPortMap: cfg.Swarm.DisableNatPortMap,
vyzo's avatar
vyzo committed
237 238
		DisableRelay:      cfg.Swarm.DisableRelay,
		EnableRelayHop:    cfg.Swarm.EnableRelayHop,
Jeromy's avatar
Jeromy committed
239
		ConnectionManager: connmgr,
240
	}
Jakub Sztandera's avatar
Jakub Sztandera committed
241
	peerhost, err := hostOption(ctx, n.Identity, n.Peerstore, n.Reporter,
242
		addrfilter, tpt, protec, hostopts)
vyzo's avatar
vyzo committed
243

244
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245
		return err
246 247
	}

248
	if err := n.startOnlineServicesWithHost(ctx, peerhost, routingOption, pubsub, ipnsps); err != nil {
249
		return err
250 251 252
	}

	// Ok, now we're ready to listen.
Łukasz Magiera's avatar
Łukasz Magiera committed
253
	if err := startListening(n.PeerHost, cfg); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
254
		return err
255
	}
256

Łukasz Magiera's avatar
Łukasz Magiera committed
257
	n.P2P = p2p.NewP2P(n.Identity, n.PeerHost, n.Peerstore)
258

259
	// setup local discovery
Jeromy's avatar
Jeromy committed
260
	if do != nil {
Jeromy's avatar
Jeromy committed
261
		service, err := do(ctx, n.PeerHost)
Jeromy's avatar
Jeromy committed
262
		if err != nil {
Jeromy's avatar
Jeromy committed
263 264 265 266
			log.Error("mdns error: ", err)
		} else {
			service.RegisterNotifee(n)
			n.Discovery = service
Jeromy's avatar
Jeromy committed
267
		}
268 269
	}

270
	return n.Bootstrap(DefaultBootstrapConfig)
271 272
}

Jeromy's avatar
Jeromy committed
273 274
func constructConnMgr(cfg config.ConnMgr) (ifconnmgr.ConnManager, error) {
	switch cfg.Type {
275 276 277 278
	case "":
		// 'default' value is the basic connection manager
		return connmgr.NewConnManager(config.DefaultConnMgrLowWater, config.DefaultConnMgrHighWater, config.DefaultConnMgrGracePeriod), nil
	case "none":
Jeromy's avatar
Jeromy committed
279 280 281 282 283 284 285 286 287 288 289 290 291
		return nil, nil
	case "basic":
		grace, err := time.ParseDuration(cfg.GracePeriod)
		if err != nil {
			return nil, fmt.Errorf("parsing Swarm.ConnMgr.GracePeriod: %s", err)
		}

		return connmgr.NewConnManager(cfg.LowWater, cfg.HighWater, grace), nil
	default:
		return nil, fmt.Errorf("unrecognized ConnMgr.Type: %q", cfg.Type)
	}
}

Łukasz Magiera's avatar
Łukasz Magiera committed
292 293 294 295 296 297
func (n *IpfsNode) startLateOnlineServices(ctx context.Context) error {
	cfg, err := n.Repo.Config()
	if err != nil {
		return err
	}

298
	var keyProvider rp.KeyChanFunc
Łukasz Magiera's avatar
Łukasz Magiera committed
299 300 301 302 303 304 305 306 307 308 309

	switch cfg.Reprovider.Strategy {
	case "all":
		fallthrough
	case "":
		keyProvider = rp.NewBlockstoreProvider(n.Blockstore)
	case "roots":
		keyProvider = rp.NewPinnedProvider(n.Pinning, n.DAG, true)
	case "pinned":
		keyProvider = rp.NewPinnedProvider(n.Pinning, n.DAG, false)
	default:
310
		return fmt.Errorf("unknown reprovider strategy '%s'", cfg.Reprovider.Strategy)
Łukasz Magiera's avatar
Łukasz Magiera committed
311
	}
312
	n.Reprovider = rp.NewReprovider(ctx, n.Routing, keyProvider)
Łukasz Magiera's avatar
Łukasz Magiera committed
313

314 315 316 317 318
	reproviderInterval := kReprovideFrequency
	if cfg.Reprovider.Interval != "" {
		dur, err := time.ParseDuration(cfg.Reprovider.Interval)
		if err != nil {
			return err
Łukasz Magiera's avatar
Łukasz Magiera committed
319 320
		}

321
		reproviderInterval = dur
Łukasz Magiera's avatar
Łukasz Magiera committed
322 323
	}

324 325
	go n.Reprovider.Run(reproviderInterval)

Łukasz Magiera's avatar
Łukasz Magiera committed
326 327 328
	return nil
}

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
func makeAddrsFactory(cfg config.Addresses) (p2pbhost.AddrsFactory, error) {
	var annAddrs []ma.Multiaddr
	for _, addr := range cfg.Announce {
		maddr, err := ma.NewMultiaddr(addr)
		if err != nil {
			return nil, err
		}
		annAddrs = append(annAddrs, maddr)
	}

	filters := mafilter.NewFilters()
	noAnnAddrs := map[string]bool{}
	for _, addr := range cfg.NoAnnounce {
		f, err := mamask.NewMask(addr)
		if err == nil {
			filters.AddDialFilter(f)
			continue
		}
		maddr, err := ma.NewMultiaddr(addr)
		if err != nil {
			return nil, err
		}
		noAnnAddrs[maddr.String()] = true
	}

	return func(allAddrs []ma.Multiaddr) []ma.Multiaddr {
		var addrs []ma.Multiaddr
		if len(annAddrs) > 0 {
			addrs = annAddrs
		} else {
			addrs = allAddrs
		}

		var out []ma.Multiaddr
		for _, maddr := range addrs {
			// check for exact matches
			ok, _ := noAnnAddrs[maddr.String()]
			// check for /ipcidr matches
			if !ok && !filters.AddrBlocked(maddr) {
				out = append(out, maddr)
			}
		}
		return out
	}, nil
}

375 376 377 378
func makeSmuxTransport(mplexExp bool) smux.Transport {
	mstpt := mssmux.NewBlankTransport()

	ymxtpt := &yamux.Transport{
Steven Allen's avatar
Steven Allen committed
379
		AcceptBacklog:          512,
380 381 382 383 384 385 386
		ConnectionWriteTimeout: time.Second * 10,
		KeepAliveInterval:      time.Second * 30,
		EnableKeepAlive:        true,
		MaxStreamWindowSize:    uint32(1024 * 512),
		LogOutput:              ioutil.Discard,
	}

387 388 389 390
	if os.Getenv("YAMUX_DEBUG") != "" {
		ymxtpt.LogOutput = os.Stderr
	}

391 392 393 394 395 396 397 398 399 400 401 402 403 404
	mstpt.AddTransport("/yamux/1.0.0", ymxtpt)

	if mplexExp {
		mstpt.AddTransport("/mplex/6.7.0", mplex.DefaultTransport)
	}

	// Allow muxer preference order overriding
	if prefs := os.Getenv("LIBP2P_MUX_PREFS"); prefs != "" {
		mstpt.OrderPreference = strings.Fields(prefs)
	}

	return mstpt
}

Jeromy's avatar
Jeromy committed
405 406
func setupDiscoveryOption(d config.Discovery) DiscoveryOption {
	if d.MDNS.Enabled {
Jeromy's avatar
Jeromy committed
407
		return func(ctx context.Context, h p2phost.Host) (discovery.Service, error) {
Jeromy's avatar
Jeromy committed
408 409 410
			if d.MDNS.Interval == 0 {
				d.MDNS.Interval = 5
			}
Jeromy's avatar
Jeromy committed
411
			return discovery.NewMdnsService(ctx, h, time.Duration(d.MDNS.Interval)*time.Second, discovery.ServiceTag)
Jeromy's avatar
Jeromy committed
412 413 414 415 416
		}
	}
	return nil
}

417 418
// HandlePeerFound attempts to connect to peer from `PeerInfo`, if it fails
// logs a warning log.
Jeromy's avatar
Jeromy committed
419
func (n *IpfsNode) HandlePeerFound(p pstore.PeerInfo) {
420
	log.Warning("trying peer info: ", p)
421
	ctx, cancel := context.WithTimeout(n.Context(), discoveryConnTimeout)
rht's avatar
rht committed
422
	defer cancel()
423
	if err := n.PeerHost.Connect(ctx, p); err != nil {
424 425 426 427
		log.Warning("Failed to connect to peer found by discovery: ", err)
	}
}

428 429
// startOnlineServicesWithHost  is the set of services which need to be
// initialized with the host and _before_ we start listening.
430
func (n *IpfsNode) startOnlineServicesWithHost(ctx context.Context, host p2phost.Host, routingOption RoutingOption, pubsub bool, ipnsps bool) error {
431
	// setup diagnostics service
Jeromy's avatar
Jeromy committed
432
	n.Ping = ping.NewPingService(host)
433

434 435 436 437 438 439 440 441 442 443 444 445 446
	if pubsub || ipnsps {
		service, err := floodsub.NewFloodSub(ctx, host)
		if err != nil {
			return err
		}
		n.Floodsub = service
	}

	validator := record.NamespacedValidator{
		"pk":   record.PublicKeyValidator{},
		"ipns": namesys.IpnsValidator{KeyBook: host.Peerstore()},
	}

447
	// setup routing service
448
	r, err := routingOption(ctx, host, n.Repo.Datastore(), validator)
Jeromy's avatar
Jeromy committed
449
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
450
		return err
451
	}
Jeromy's avatar
Jeromy committed
452
	n.Routing = r
453

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
	if ipnsps {
		n.PSRouter = psrouter.NewPubsubValueStore(
			ctx,
			host,
			n.Routing,
			n.Floodsub,
			validator,
		)
		n.Routing = rhelpers.Tiered{
			// Always check pubsub first.
			&rhelpers.Compose{
				ValueStore: &rhelpers.LimitedValueStore{
					ValueStore: n.PSRouter,
					Namespaces: []string{"ipns"},
				},
			},
			n.Routing,
		}
	}

474 475 476
	// Wrap standard peer host with routing system to allow unknown peer lookups
	n.PeerHost = rhost.Wrap(host, n.Routing)

477
	// setup exchange service
478
	bitswapNetwork := bsnet.NewFromIpfsHost(n.PeerHost, n.Routing)
Łukasz Magiera's avatar
Łukasz Magiera committed
479
	n.Exchange = bitswap.New(ctx, bitswapNetwork, n.Blockstore)
480

481 482 483 484 485
	size, err := n.getCacheSize()
	if err != nil {
		return err
	}

486
	// setup name system
487
	n.Namesys = namesys.NewNameSystem(n.Routing, n.Repo.Datastore(), size)
488

Jeromy's avatar
Jeromy committed
489
	// setup ipns republishing
490
	return n.setupIpnsRepublisher()
491 492
}

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
// getCacheSize returns cache life and cache size
func (n *IpfsNode) getCacheSize() (int, error) {
	cfg, err := n.Repo.Config()
	if err != nil {
		return 0, err
	}

	cs := cfg.Ipns.ResolveCacheSize
	if cs == 0 {
		cs = 128
	}
	if cs < 0 {
		return 0, fmt.Errorf("cannot specify negative resolve cache size")
	}
	return cs, nil
}

510
func (n *IpfsNode) setupIpnsRepublisher() error {
Jeromy's avatar
Jeromy committed
511 512 513 514
	cfg, err := n.Repo.Config()
	if err != nil {
		return err
	}
515

516
	n.IpnsRepub = ipnsrp.NewRepublisher(n.Namesys, n.Repo.Datastore(), n.PrivateKey, n.Repo.Keystore())
517

Jeromy's avatar
Jeromy committed
518 519 520 521 522 523
	if cfg.Ipns.RepublishPeriod != "" {
		d, err := time.ParseDuration(cfg.Ipns.RepublishPeriod)
		if err != nil {
			return fmt.Errorf("failure to parse config setting IPNS.RepublishPeriod: %s", err)
		}

524
		if !u.Debug && (d < time.Minute || d > (time.Hour*24)) {
Jeromy's avatar
Jeromy committed
525 526 527 528 529 530
			return fmt.Errorf("config setting IPNS.RepublishPeriod is not between 1min and 1day: %s", d)
		}

		n.IpnsRepub.Interval = d
	}

531 532 533 534 535 536 537 538 539
	if cfg.Ipns.RecordLifetime != "" {
		d, err := time.ParseDuration(cfg.Ipns.RepublishPeriod)
		if err != nil {
			return fmt.Errorf("failure to parse config setting IPNS.RecordLifetime: %s", err)
		}

		n.IpnsRepub.RecordLifetime = d
	}

Jeromy's avatar
Jeromy committed
540 541
	n.Process().Go(n.IpnsRepub.Run)

542 543 544
	return nil
}

545 546 547 548 549 550 551 552 553 554 555 556
// Process returns the Process object
func (n *IpfsNode) Process() goprocess.Process {
	return n.proc
}

// Close calls Close() on the Process object
func (n *IpfsNode) Close() error {
	return n.proc.Close()
}

// Context returns the IpfsNode context
func (n *IpfsNode) Context() context.Context {
557 558 559
	if n.ctx == nil {
		n.ctx = context.TODO()
	}
560 561 562
	return n.ctx
}

563 564
// teardown closes owned children. If any errors occur, this function returns
// the first error.
Brian Tiger Chow's avatar
Brian Tiger Chow committed
565
func (n *IpfsNode) teardown() error {
566
	log.Debug("core is shutting down...")
567 568
	// owned objects are closed in this teardown to ensure that they're closed
	// regardless of which constructor was used to add them to the node.
Jeromy's avatar
Jeromy committed
569 570
	var closers []io.Closer

571
	// NOTE: The order that objects are added(closed) matters, if an object
Jeromy's avatar
Jeromy committed
572 573 574 575 576
	// needs to use another during its shutdown/cleanup process, it should be
	// closed before that other object

	if n.FilesRoot != nil {
		closers = append(closers, n.FilesRoot)
Jeromy's avatar
Jeromy committed
577
	}
578

579 580 581 582
	if n.Exchange != nil {
		closers = append(closers, n.Exchange)
	}

583
	if n.Mounts.Ipfs != nil && !n.Mounts.Ipfs.IsActive() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
584 585
		closers = append(closers, mount.Closer(n.Mounts.Ipfs))
	}
586
	if n.Mounts.Ipns != nil && !n.Mounts.Ipns.IsActive() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
587 588 589
		closers = append(closers, mount.Closer(n.Mounts.Ipns))
	}

Jeromy's avatar
Jeromy committed
590 591 592 593
	if dht, ok := n.Routing.(*dht.IpfsDHT); ok {
		closers = append(closers, dht.Process())
	}

Jeromy's avatar
Jeromy committed
594 595 596 597
	if n.Blocks != nil {
		closers = append(closers, n.Blocks)
	}

Jeromy's avatar
Jeromy committed
598 599
	if n.Bootstrapper != nil {
		closers = append(closers, n.Bootstrapper)
600 601
	}

Jeromy's avatar
Jeromy committed
602 603
	if n.PeerHost != nil {
		closers = append(closers, n.PeerHost)
604
	}
605

Jeromy's avatar
Jeromy committed
606 607 608
	// Repo closed last, most things need to preserve state here
	closers = append(closers, n.Repo)

609
	var errs []error
610
	for _, closer := range closers {
611 612
		if err := closer.Close(); err != nil {
			errs = append(errs, err)
613 614 615 616
		}
	}
	if len(errs) > 0 {
		return errs[0]
Brian Tiger Chow's avatar
Brian Tiger Chow committed
617 618
	}
	return nil
Brian Tiger Chow's avatar
Brian Tiger Chow committed
619 620
}

621
// OnlineMode returns whether or not the IpfsNode is in OnlineMode.
Brian Tiger Chow's avatar
Brian Tiger Chow committed
622
func (n *IpfsNode) OnlineMode() bool {
623
	return n.mode == onlineMode
Brian Tiger Chow's avatar
Brian Tiger Chow committed
624 625
}

626
// SetLocal will set the IpfsNode to local mode
627 628 629 630 631 632 633
func (n *IpfsNode) SetLocal(isLocal bool) {
	if isLocal {
		n.mode = localMode
	}
	n.localModeSet = true
}

634
// LocalMode returns whether or not the IpfsNode is in LocalMode
635 636 637 638 639
func (n *IpfsNode) LocalMode() bool {
	if !n.localModeSet {
		// programmer error should not happen
		panic("local mode not set")
	}
640
	return n.mode == localMode
641 642
}

643
// Bootstrap will set and call the IpfsNodes bootstrap function.
644
func (n *IpfsNode) Bootstrap(cfg BootstrapConfig) error {
645
	// TODO what should return value be when in offlineMode?
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
646 647 648 649
	if n.Routing == nil {
		return nil
	}

650 651 652 653 654 655 656
	if n.Bootstrapper != nil {
		n.Bootstrapper.Close() // stop previous bootstrap process.
	}

	// if the caller did not specify a bootstrap peer function, get the
	// freshest bootstrap peers from config. this responds to live changes.
	if cfg.BootstrapPeers == nil {
Jeromy's avatar
Jeromy committed
657
		cfg.BootstrapPeers = func() []pstore.PeerInfo {
658
			ps, err := n.loadBootstrapPeers()
659
			if err != nil {
660
				log.Warning("failed to parse bootstrap peers from config")
661 662 663 664 665 666 667 668 669
				return nil
			}
			return ps
		}
	}

	var err error
	n.Bootstrapper, err = Bootstrap(n, cfg)
	return err
670 671
}

672 673
func (n *IpfsNode) loadID() error {
	if n.Identity != "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
674
		return errors.New("identity already loaded")
675 676
	}

677 678 679 680 681 682
	cfg, err := n.Repo.Config()
	if err != nil {
		return err
	}

	cid := cfg.Identity.PeerID
683
	if cid == "" {
684
		return errors.New("identity was not set in config (was 'ipfs init' run?)")
685 686
	}
	if len(cid) == 0 {
687
		return errors.New("no peer ID in config! (was 'ipfs init' run?)")
688 689
	}

Steven Allen's avatar
Steven Allen committed
690 691 692 693 694 695
	id, err := peer.IDB58Decode(cid)
	if err != nil {
		return fmt.Errorf("peer ID invalid: %s", err)
	}

	n.Identity = id
696 697
	return nil
}
698

699
// GetKey will return a key from the Keystore with name `name`.
700 701 702 703 704 705 706 707
func (n *IpfsNode) GetKey(name string) (ic.PrivKey, error) {
	if name == "self" {
		return n.PrivateKey, nil
	} else {
		return n.Repo.Keystore().Get(name)
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
708
func (n *IpfsNode) LoadPrivateKey() error {
709
	if n.Identity == "" || n.Peerstore == nil {
Łukasz Magiera's avatar
Łukasz Magiera committed
710
		return errors.New("loaded private key out of order")
711 712
	}

713
	if n.PrivateKey != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
714
		return errors.New("private key already loaded")
715 716
	}

717 718 719 720 721 722
	cfg, err := n.Repo.Config()
	if err != nil {
		return err
	}

	sk, err := loadPrivateKey(&cfg.Identity, n.Identity)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
723
	if err != nil {
724
		return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
725
	}
726

727 728
	n.PrivateKey = sk
	n.Peerstore.AddPrivKey(n.Identity, n.PrivateKey)
Jeromy's avatar
Jeromy committed
729 730 731 732
	n.Peerstore.AddPubKey(n.Identity, sk.GetPublic())
	return nil
}

Jeromy's avatar
Jeromy committed
733
func (n *IpfsNode) loadBootstrapPeers() ([]pstore.PeerInfo, error) {
734 735 736 737 738 739
	cfg, err := n.Repo.Config()
	if err != nil {
		return nil, err
	}

	parsed, err := cfg.BootstrapPeers()
740 741 742 743 744 745
	if err != nil {
		return nil, err
	}
	return toPeerInfos(parsed), nil
}

Jeromy's avatar
Jeromy committed
746
func (n *IpfsNode) loadFilesRoot() error {
Jeromy's avatar
Jeromy committed
747
	dsk := ds.NewKey("/local/filesroot")
Jeromy's avatar
Jeromy committed
748 749
	pf := func(ctx context.Context, c *cid.Cid) error {
		return n.Repo.Datastore().Put(dsk, c.Bytes())
Jeromy's avatar
Jeromy committed
750 751
	}

752
	var nd *merkledag.ProtoNode
Jeromy's avatar
Jeromy committed
753 754 755 756
	val, err := n.Repo.Datastore().Get(dsk)

	switch {
	case err == ds.ErrNotFound || val == nil:
757
		nd = ft.EmptyDirNode()
758
		err := n.DAG.Add(n.Context(), nd)
Jeromy's avatar
Jeromy committed
759 760 761 762
		if err != nil {
			return fmt.Errorf("failure writing to dagstore: %s", err)
		}
	case err == nil:
Jeromy's avatar
Jeromy committed
763 764 765 766 767
		c, err := cid.Cast(val.([]byte))
		if err != nil {
			return err
		}

768
		rnd, err := n.DAG.Get(n.Context(), c)
Jeromy's avatar
Jeromy committed
769 770 771
		if err != nil {
			return fmt.Errorf("error loading filesroot from DAG: %s", err)
		}
772 773 774 775 776 777 778

		pbnd, ok := rnd.(*merkledag.ProtoNode)
		if !ok {
			return merkledag.ErrNotProtobuf
		}

		nd = pbnd
Jeromy's avatar
Jeromy committed
779 780 781 782 783 784 785 786 787 788 789 790 791
	default:
		return err
	}

	mr, err := mfs.NewRoot(n.Context(), n.DAG, nd, pf)
	if err != nil {
		return err
	}

	n.FilesRoot = mr
	return nil
}

Jeromy's avatar
Jeromy committed
792 793 794
// SetupOfflineRouting loads the local nodes private key and
// uses it to instantiate a routing system in offline mode.
// This is primarily used for offline ipns modifications.
Jeromy's avatar
Jeromy committed
795
func (n *IpfsNode) SetupOfflineRouting() error {
796 797 798 799
	if n.Routing != nil {
		// Routing was already set up
		return nil
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
800
	err := n.LoadPrivateKey()
Jeromy's avatar
Jeromy committed
801 802 803 804 805
	if err != nil {
		return err
	}

	n.Routing = offroute.NewOfflineRouter(n.Repo.Datastore(), n.PrivateKey)
806

807 808 809 810 811 812
	size, err := n.getCacheSize()
	if err != nil {
		return err
	}

	n.Namesys = namesys.NewNameSystem(n.Routing, n.Repo.Datastore(), size)
813

814
	return nil
815 816 817 818
}

func loadPrivateKey(cfg *config.Identity, id peer.ID) (ic.PrivKey, error) {
	sk, err := cfg.DecodePrivateKey("passphrase todo!")
819 820 821
	if err != nil {
		return nil, err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
822

823 824 825 826
	id2, err := peer.IDFromPrivateKey(sk)
	if err != nil {
		return nil, err
	}
827

828 829
	if id2 != id {
		return nil, fmt.Errorf("private key in config does not match id: %s != %s", id, id2)
830 831
	}

832
	return sk, nil
833
}
834

835
func listenAddresses(cfg *config.Config) ([]ma.Multiaddr, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
836 837 838
	var listen []ma.Multiaddr
	for _, addr := range cfg.Addresses.Swarm {
		maddr, err := ma.NewMultiaddr(addr)
839
		if err != nil {
Łukasz Magiera's avatar
Łukasz Magiera committed
840
			return nil, fmt.Errorf("failure to parse config.Addresses.Swarm: %s", cfg.Addresses.Swarm)
841
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
842
		listen = append(listen, maddr)
843 844 845 846
	}

	return listen, nil
}
847

Kevin Atkinson's avatar
Kevin Atkinson committed
848
type ConstructPeerHostOpts struct {
849
	AddrsFactory      p2pbhost.AddrsFactory
vyzo's avatar
vyzo committed
850 851 852
	DisableNatPortMap bool
	DisableRelay      bool
	EnableRelayHop    bool
Jeromy's avatar
Jeromy committed
853
	ConnectionManager ifconnmgr.ConnManager
Kevin Atkinson's avatar
Kevin Atkinson committed
854 855 856
}

type HostOption func(ctx context.Context, id peer.ID, ps pstore.Peerstore, bwr metrics.Reporter, fs []*net.IPNet, tpt smux.Transport, protc ipnet.Protector, opts *ConstructPeerHostOpts) (p2phost.Host, error)
Jeromy's avatar
Jeromy committed
857 858 859

var DefaultHostOption HostOption = constructPeerHost

860
// isolates the complex initialization steps
Kevin Atkinson's avatar
Kevin Atkinson committed
861
func constructPeerHost(ctx context.Context, id peer.ID, ps pstore.Peerstore, bwr metrics.Reporter, fs []*net.IPNet, tpt smux.Transport, protec ipnet.Protector, opts *ConstructPeerHostOpts) (p2phost.Host, error) {
862 863

	// no addresses to begin with. we'll start later.
Jakub Sztandera's avatar
Jakub Sztandera committed
864
	swrm, err := swarm.NewSwarmWithProtector(ctx, nil, id, ps, protec, tpt, bwr)
865
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
866
		return nil, err
867
	}
868

869 870
	network := (*swarm.Network)(swrm)

871 872 873 874
	for _, f := range fs {
		network.Swarm().Filters.AddDialFilter(f)
	}

Kevin Atkinson's avatar
Kevin Atkinson committed
875 876 877 878
	hostOpts := []interface{}{bwr}
	if !opts.DisableNatPortMap {
		hostOpts = append(hostOpts, p2pbhost.NATPortMap)
	}
Jeromy's avatar
Jeromy committed
879 880 881
	if opts.ConnectionManager != nil {
		hostOpts = append(hostOpts, opts.ConnectionManager)
	}
Kevin Atkinson's avatar
Kevin Atkinson committed
882

883
	addrsFactory := opts.AddrsFactory
vyzo's avatar
vyzo committed
884
	if !opts.DisableRelay {
885
		if addrsFactory != nil {
886
			addrsFactory = composeAddrsFactory(addrsFactory, filterRelayAddrs)
887
		} else {
888
			addrsFactory = filterRelayAddrs
889 890 891 892 893
		}
	}

	if addrsFactory != nil {
		hostOpts = append(hostOpts, addrsFactory)
vyzo's avatar
vyzo committed
894 895
	}

Kevin Atkinson's avatar
Kevin Atkinson committed
896
	host := p2pbhost.New(network, hostOpts...)
Jeromy's avatar
Jeromy committed
897

vyzo's avatar
vyzo committed
898 899 900 901 902 903 904 905
	if !opts.DisableRelay {
		var relayOpts []circuit.RelayOpt
		if opts.EnableRelayHop {
			relayOpts = append(relayOpts, circuit.OptHop)
		}

		err := circuit.AddRelayTransport(ctx, host, relayOpts...)
		if err != nil {
906
			host.Close()
vyzo's avatar
vyzo committed
907 908 909 910
			return nil, err
		}
	}

911 912 913
	return host, nil
}

914 915 916 917 918 919 920 921 922 923 924 925
func filterRelayAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {
	var raddrs []ma.Multiaddr
	for _, addr := range addrs {
		_, err := addr.ValueForProtocol(circuit.P_CIRCUIT)
		if err == nil {
			continue
		}
		raddrs = append(raddrs, addr)
	}
	return raddrs
}

926 927 928 929 930 931
func composeAddrsFactory(f, g p2pbhost.AddrsFactory) p2pbhost.AddrsFactory {
	return func(addrs []ma.Multiaddr) []ma.Multiaddr {
		return f(g(addrs))
	}
}

932
// startListening on the network addresses
Łukasz Magiera's avatar
Łukasz Magiera committed
933
func startListening(host p2phost.Host, cfg *config.Config) error {
934 935
	listenAddrs, err := listenAddresses(cfg)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
936
		return err
937 938
	}

939
	// make sure we error out if our config does not have addresses we can use
940
	log.Debugf("Config.Addresses.Swarm:%s", listenAddrs)
941
	filteredAddrs := addrutil.FilterUsableAddrs(listenAddrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
942
	log.Debugf("Config.Addresses.Swarm:%s (filtered)", filteredAddrs)
943
	if len(filteredAddrs) < 1 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
944
		return fmt.Errorf("addresses in config not usable: %s", listenAddrs)
945 946
	}

947 948 949
	// Actually start listening:
	if err := host.Network().Listen(filteredAddrs...); err != nil {
		return err
950 951
	}

952
	// list out our addresses
953
	addrs, err := host.Network().InterfaceListenAddresses()
954
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
955
		return err
956
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
957
	log.Infof("Swarm listening at: %s", addrs)
958
	return nil
959
}
960

961 962 963 964 965 966
func constructDHTRouting(ctx context.Context, host p2phost.Host, dstore ds.Batching, validator record.Validator) (routing.IpfsRouting, error) {
	return dht.New(
		ctx, host,
		dhtopts.Datastore(dstore),
		dhtopts.Validator(validator),
	)
967
}
Jeromy's avatar
Jeromy committed
968

969 970 971 972 973 974 975
func constructClientDHTRouting(ctx context.Context, host p2phost.Host, dstore ds.Batching, validator record.Validator) (routing.IpfsRouting, error) {
	return dht.New(
		ctx, host,
		dhtopts.Client(true),
		dhtopts.Datastore(dstore),
		dhtopts.Validator(validator),
	)
Jeromy's avatar
Jeromy committed
976 977
}

978
type RoutingOption func(context.Context, p2phost.Host, ds.Batching, record.Validator) (routing.IpfsRouting, error)
Jeromy's avatar
Jeromy committed
979

Jeromy's avatar
Jeromy committed
980
type DiscoveryOption func(context.Context, p2phost.Host) (discovery.Service, error)
Jeromy's avatar
Jeromy committed
981

982
var DHTOption RoutingOption = constructDHTRouting
Jeromy's avatar
Jeromy committed
983
var DHTClientOption RoutingOption = constructClientDHTRouting
984
var NilRouterOption RoutingOption = nilrouting.ConstructNilRouting