swarm.go 15.5 KB
Newer Older
H
holisticode 已提交
1
// Copyright 2018 The go-ethereum Authors
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package swarm

import (
	"bytes"
21
	"context"
22 23
	"crypto/ecdsa"
	"fmt"
24
	"io"
25
	"math/big"
26
	"net"
E
ethersphere 已提交
27
	"path/filepath"
28
	"strings"
29
	"time"
30
	"unicode"
31 32 33 34 35

	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/contracts/chequebook"
	"github.com/ethereum/go-ethereum/contracts/ens"
36
	"github.com/ethereum/go-ethereum/ethclient"
37
	"github.com/ethereum/go-ethereum/metrics"
38
	"github.com/ethereum/go-ethereum/p2p"
39
	"github.com/ethereum/go-ethereum/p2p/enode"
E
ethersphere 已提交
40
	"github.com/ethereum/go-ethereum/p2p/protocols"
41
	"github.com/ethereum/go-ethereum/params"
42 43 44
	"github.com/ethereum/go-ethereum/rpc"
	"github.com/ethereum/go-ethereum/swarm/api"
	httpapi "github.com/ethereum/go-ethereum/swarm/api/http"
45
	"github.com/ethereum/go-ethereum/swarm/fuse"
E
ethersphere 已提交
46
	"github.com/ethereum/go-ethereum/swarm/log"
47
	"github.com/ethereum/go-ethereum/swarm/network"
E
ethersphere 已提交
48 49 50
	"github.com/ethereum/go-ethereum/swarm/network/stream"
	"github.com/ethereum/go-ethereum/swarm/pss"
	"github.com/ethereum/go-ethereum/swarm/state"
51
	"github.com/ethereum/go-ethereum/swarm/storage"
52
	"github.com/ethereum/go-ethereum/swarm/storage/feed"
E
ethersphere 已提交
53
	"github.com/ethereum/go-ethereum/swarm/storage/mock"
H
holisticode 已提交
54
	"github.com/ethereum/go-ethereum/swarm/swap"
55
	"github.com/ethereum/go-ethereum/swarm/tracing"
56 57
)

58 59 60 61 62
var (
	updateGaugesPeriod = 5 * time.Second
	startCounter       = metrics.NewRegisteredCounter("stack,start", nil)
	stopCounter        = metrics.NewRegisteredCounter("stack,stop", nil)
	uptimeGauge        = metrics.NewRegisteredGauge("stack.uptime", nil)
E
ethersphere 已提交
63
	requestsCacheGauge = metrics.NewRegisteredGauge("storage.cache.requests.size", nil)
64 65
)

66 67
// the swarm stack
type Swarm struct {
H
holisticode 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81
	config            *api.Config        // swarm configuration
	api               *api.API           // high level api layer (fs/manifest)
	dns               api.Resolver       // DNS registrar
	fileStore         *storage.FileStore // distributed preimage archive, the local API to the storage with document level storage/retrieval support
	streamer          *stream.Registry
	bzz               *network.Bzz       // the logistic manager
	backend           chequebook.Backend // simple blockchain Backend
	privateKey        *ecdsa.PrivateKey
	netStore          *storage.NetStore
	sfs               *fuse.SwarmFS // need this to cleanup all the active mounts on node exit
	ps                *pss.Pss
	swap              *swap.Swap
	stateStore        *state.DBStore
	accountingMetrics *protocols.AccountingMetrics
82
	startTime         time.Time
83 84

	tracerClose io.Closer
85 86
}

87
// NewSwarm creates a new swarm service instance
88
// implements node.Service
E
ethersphere 已提交
89 90 91 92
// If mockStore is not nil, it will be used as the storage for chunk data.
// MockStore should be used only for testing.
func NewSwarm(config *api.Config, mockStore *mock.NodeStore) (self *Swarm, err error) {
	if bytes.Equal(common.FromHex(config.PublicKey), storage.ZeroAddr) {
93 94
		return nil, fmt.Errorf("empty public key")
	}
E
ethersphere 已提交
95
	if bytes.Equal(common.FromHex(config.BzzKey), storage.ZeroAddr) {
96 97 98
		return nil, fmt.Errorf("empty bzz key")
	}

E
ethersphere 已提交
99 100 101 102 103 104 105
	var backend chequebook.Backend
	if config.SwapAPI != "" && config.SwapEnabled {
		log.Info("connecting to SWAP API", "url", config.SwapAPI)
		backend, err = ethclient.Dial(config.SwapAPI)
		if err != nil {
			return nil, fmt.Errorf("error connecting to SWAP API %s: %s", config.SwapAPI, err)
		}
106 107
	}

E
ethersphere 已提交
108 109 110 111
	self = &Swarm{
		config:     config,
		backend:    backend,
		privateKey: config.ShiftPrivateKey(),
112
	}
113
	log.Debug("Setting up Swarm service components")
114

E
ethersphere 已提交
115
	config.HiveParams.Discovery = true
116

E
ethersphere 已提交
117
	bzzconfig := &network.BzzConfig{
118 119 120 121 122
		NetworkID:    config.NetworkID,
		OverlayAddr:  common.FromHex(config.BzzKey),
		HiveParams:   config.HiveParams,
		LightNode:    config.LightNodeEnabled,
		BootnodeMode: config.BootnodeMode,
E
ethersphere 已提交
123
	}
124

H
holisticode 已提交
125
	self.stateStore, err = state.NewDBStore(filepath.Join(config.Path, "state-store.db"))
E
ethersphere 已提交
126 127 128
	if err != nil {
		return
	}
129

E
ethersphere 已提交
130 131
	// set up high level api
	var resolver *api.MultiResolver
132 133 134 135
	if len(config.EnsAPIs) > 0 {
		opts := []api.MultiResolverOption{}
		for _, c := range config.EnsAPIs {
			tld, endpoint, addr := parseEnsAPIAddress(c)
E
ethersphere 已提交
136
			r, err := newEnsClient(endpoint, addr, config, self.privateKey)
137 138 139
			if err != nil {
				return nil, err
			}
140
			opts = append(opts, api.MultiResolverOptionWithResolver(r, tld))
E
ethersphere 已提交
141

142
		}
E
ethersphere 已提交
143 144 145 146
		resolver = api.NewMultiResolver(opts...)
		self.dns = resolver
	}

B
Balint Gabor 已提交
147
	lstore, err := storage.NewLocalStore(config.LocalStoreParams, mockStore)
E
ethersphere 已提交
148
	if err != nil {
B
Balint Gabor 已提交
149 150 151 152 153 154
		return nil, err
	}

	self.netStore, err = storage.NewNetStore(lstore, nil)
	if err != nil {
		return nil, err
E
ethersphere 已提交
155 156 157 158 159 160
	}

	to := network.NewKademlia(
		common.FromHex(config.BzzKey),
		network.NewKadParams(),
	)
B
Balint Gabor 已提交
161 162
	delivery := stream.NewDelivery(to, self.netStore)
	self.netStore.NewNetFetcherFunc = network.NewFetcherFactory(delivery.RequestFromPeers, config.DeliverySkipCheck).New
E
ethersphere 已提交
163

H
holisticode 已提交
164 165 166 167 168 169
	if config.SwapEnabled {
		balancesStore, err := state.NewDBStore(filepath.Join(config.Path, "balances.db"))
		if err != nil {
			return nil, err
		}
		self.swap = swap.New(balancesStore)
H
holisticode 已提交
170
		self.accountingMetrics = protocols.SetupAccountingMetrics(10*time.Second, filepath.Join(config.Path, "metrics.db"))
H
holisticode 已提交
171 172
	}

173 174 175 176
	var nodeID enode.ID
	if err := nodeID.UnmarshalText([]byte(config.NodeID)); err != nil {
		return nil, err
	}
177 178 179 180 181 182 183 184 185 186 187

	syncing := stream.SyncingAutoSubscribe
	if !config.SyncEnabled || config.LightNodeEnabled {
		syncing = stream.SyncingDisabled
	}

	retrieval := stream.RetrievalEnabled
	if config.LightNodeEnabled {
		retrieval = stream.RetrievalClientOnly
	}

188
	registryOptions := &stream.RegistryOptions{
189
		SkipCheck:       config.DeliverySkipCheck,
190 191
		Syncing:         syncing,
		Retrieval:       retrieval,
E
ethersphere 已提交
192
		SyncUpdateDelay: config.SyncUpdateDelay,
193
		MaxPeerServers:  config.MaxStreamPeerServers,
194
	}
H
holisticode 已提交
195
	self.streamer = stream.NewRegistry(nodeID, delivery, self.netStore, self.stateStore, registryOptions, self.swap)
E
ethersphere 已提交
196 197

	// Swarm Hash Merklised Chunking for Arbitrary-length Document/File storage
B
Balint Gabor 已提交
198
	self.fileStore = storage.NewFileStore(self.netStore, self.config.FileStoreParams)
E
ethersphere 已提交
199

200 201
	var feedsHandler *feed.Handler
	fhParams := &feed.HandlerParams{}
202

203
	feedsHandler = feed.NewHandler(fhParams)
204
	feedsHandler.SetStore(self.netStore)
E
ethersphere 已提交
205

B
Balint Gabor 已提交
206
	lstore.Validators = []storage.ChunkValidator{
207
		storage.NewContentAddressValidator(storage.MakeHashFunc(storage.DefaultHash)),
208
		feedsHandler,
E
ethersphere 已提交
209 210
	}

211 212 213 214 215
	err = lstore.Migrate()
	if err != nil {
		return nil, err
	}

216
	log.Debug("Setup local storage")
E
ethersphere 已提交
217

H
holisticode 已提交
218
	self.bzz = network.NewBzz(bzzconfig, to, self.stateStore, self.streamer.GetSpec(), self.streamer.Run)
E
ethersphere 已提交
219 220 221 222 223 224 225 226

	// Pss = postal service over swarm (devp2p over bzz)
	self.ps, err = pss.NewPss(to, config.Pss)
	if err != nil {
		return nil, err
	}
	if pss.IsActiveHandshake {
		pss.SetHandshakeController(self.ps, pss.NewHandshakeParams())
227 228
	}

229
	self.api = api.NewAPI(self.fileStore, self.dns, feedsHandler, self.privateKey)
230

231
	self.sfs = fuse.NewSwarmFS(self.api)
232
	log.Debug("Initialized FUSE filesystem")
233

234 235 236
	return self, nil
}

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
// parseEnsAPIAddress parses string according to format
// [tld:][contract-addr@]url and returns ENSClientConfig structure
// with endpoint, contract address and TLD.
func parseEnsAPIAddress(s string) (tld, endpoint string, addr common.Address) {
	isAllLetterString := func(s string) bool {
		for _, r := range s {
			if !unicode.IsLetter(r) {
				return false
			}
		}
		return true
	}
	endpoint = s
	if i := strings.Index(endpoint, ":"); i > 0 {
		if isAllLetterString(endpoint[:i]) && len(endpoint) > i+2 && endpoint[i+1:i+3] != "//" {
			tld = endpoint[:i]
			endpoint = endpoint[i+1:]
		}
	}
	if i := strings.Index(endpoint, "@"); i > 0 {
		addr = common.HexToAddress(endpoint[:i])
		endpoint = endpoint[i+1:]
	}
	return
261 262
}

E
ethersphere 已提交
263 264 265 266 267 268
// ensClient provides functionality for api.ResolveValidator
type ensClient struct {
	*ens.ENS
	*ethclient.Client
}

269 270 271
// newEnsClient creates a new ENS client for that is a consumer of
// a ENS API on a specific endpoint. It is used as a helper function
// for creating multiple resolvers in NewSwarm function.
E
ethersphere 已提交
272
func newEnsClient(endpoint string, addr common.Address, config *api.Config, privkey *ecdsa.PrivateKey) (*ensClient, error) {
273 274 275 276 277
	log.Info("connecting to ENS API", "url", endpoint)
	client, err := rpc.Dial(endpoint)
	if err != nil {
		return nil, fmt.Errorf("error connecting to ENS API %s: %s", endpoint, err)
	}
E
ethersphere 已提交
278
	ethClient := ethclient.NewClient(client)
279 280

	ensRoot := config.EnsRoot
281 282
	if addr != (common.Address{}) {
		ensRoot = addr
283 284 285 286 287 288 289 290
	} else {
		a, err := detectEnsAddr(client)
		if err == nil {
			ensRoot = a
		} else {
			log.Warn(fmt.Sprintf("could not determine ENS contract address, using default %s", ensRoot), "err", err)
		}
	}
E
ethersphere 已提交
291 292
	transactOpts := bind.NewKeyedTransactor(privkey)
	dns, err := ens.NewENS(transactOpts, ensRoot, ethClient)
293 294 295 296
	if err != nil {
		return nil, err
	}
	log.Debug(fmt.Sprintf("-> Swarm Domain Name Registrar %v @ address %v", endpoint, ensRoot.Hex()))
E
ethersphere 已提交
297 298 299 300
	return &ensClient{
		ENS:    dns,
		Client: ethClient,
	}, err
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
}

// detectEnsAddr determines the ENS contract address by getting both the
// version and genesis hash using the client and matching them to either
// mainnet or testnet addresses
func detectEnsAddr(client *rpc.Client) (common.Address, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	var version string
	if err := client.CallContext(ctx, &version, "net_version"); err != nil {
		return common.Address{}, err
	}

	block, err := ethclient.NewClient(client).BlockByNumber(ctx, big.NewInt(0))
	if err != nil {
		return common.Address{}, err
	}

	switch {

	case version == "1" && block.Hash() == params.MainnetGenesisHash:
		log.Info("using Mainnet ENS contract address", "addr", ens.MainNetAddress)
		return ens.MainNetAddress, nil

	case version == "3" && block.Hash() == params.TestnetGenesisHash:
		log.Info("using Testnet ENS contract address", "addr", ens.TestNetAddress)
		return ens.TestNetAddress, nil

	default:
		return common.Address{}, fmt.Errorf("unknown version and genesis hash: %s %s", version, block.Hash())
	}
}

335 336 337 338 339 340 341 342 343 344 345
/*
Start is called when the stack is started
* starts the network kademlia hive peer management
* (starts netStore level 0 api)
* starts DPA level 1 api (chunking -> store/retrieve requests)
* (starts level 2 api)
* starts http proxy server
* registers url scheme handlers for bzz, etc
* TODO: start subservices like sword, swear, swarmdns
*/
// implements the node.Service interface
346
func (self *Swarm) Start(srv *p2p.Server) error {
347
	self.startTime = time.Now()
E
ethersphere 已提交
348

349 350
	self.tracerClose = tracing.Closer

E
ethersphere 已提交
351 352
	// update uaddr to correct enode
	newaddr := self.bzz.UpdateLocalAddr([]byte(srv.Self().String()))
353
	log.Info("Updated bzz local addr", "oaddr", fmt.Sprintf("%x", newaddr.OAddr), "uaddr", fmt.Sprintf("%s", newaddr.UAddr))
354
	// set chequebook
H
holisticode 已提交
355 356 357
	//TODO: Currently if swap is enabled and no chequebook (or inexistent) contract is provided, the node would crash.
	//Once we integrate back the contracts, this check MUST be revisited
	if self.config.SwapEnabled && self.config.SwapAPI != "" {
358 359 360 361 362
		ctx := context.Background() // The initial setup has no deadline.
		err := self.SetChequebook(ctx)
		if err != nil {
			return fmt.Errorf("Unable to set chequebook for SWAP: %v", err)
		}
363
		log.Debug(fmt.Sprintf("-> cheque book for SWAP: %v", self.config.Swap.Chequebook()))
364
	} else {
365
		log.Debug(fmt.Sprintf("SWAP disabled: no cheque book set"))
366 367
	}

368
	log.Info("Starting bzz service")
369

E
ethersphere 已提交
370 371 372 373 374
	err := self.bzz.Start(srv)
	if err != nil {
		log.Error("bzz failed", "err", err)
		return err
	}
V
Viktor Trón 已提交
375
	log.Info("Swarm network started", "bzzaddr", fmt.Sprintf("%x", self.bzz.Hive.BaseAddr()))
E
ethersphere 已提交
376 377 378 379

	if self.ps != nil {
		self.ps.Start(srv)
	}
380 381 382

	// start swarm http proxy server
	if self.config.Port != "" {
383
		addr := net.JoinHostPort(self.config.ListenAddr, self.config.Port)
384 385
		server := httpapi.NewServer(self.api, self.config.Cors)

386 387 388
		if self.config.Cors != "" {
			log.Debug("Swarm HTTP proxy CORS headers", "allowedOrigins", self.config.Cors)
		}
E
ethersphere 已提交
389

390 391 392 393 394 395 396
		log.Debug("Starting Swarm HTTP proxy", "port", self.config.Port)
		go func() {
			err := server.ListenAndServe(addr)
			if err != nil {
				log.Error("Could not start Swarm HTTP proxy", "err", err.Error())
			}
		}()
397 398
	}

399 400 401
	self.periodicallyUpdateGauges()

	startCounter.Inc(1)
E
ethersphere 已提交
402
	self.streamer.Start(srv)
403 404 405
	return nil
}

406 407 408 409 410 411 412 413 414 415 416
func (self *Swarm) periodicallyUpdateGauges() {
	ticker := time.NewTicker(updateGaugesPeriod)

	go func() {
		for range ticker.C {
			self.updateGauges()
		}
	}()
}

func (self *Swarm) updateGauges() {
417
	uptimeGauge.Update(time.Since(self.startTime).Nanoseconds())
B
Balint Gabor 已提交
418
	requestsCacheGauge.Update(int64(self.netStore.RequestsCacheLen()))
419 420
}

421 422 423
// implements the node.Service interface
// stops all component services.
func (self *Swarm) Stop() error {
424 425 426 427 428 429 430
	if self.tracerClose != nil {
		err := self.tracerClose.Close()
		if err != nil {
			return err
		}
	}

E
ethersphere 已提交
431 432 433
	if self.ps != nil {
		self.ps.Stop()
	}
434 435 436 437
	if ch := self.config.Swap.Chequebook(); ch != nil {
		ch.Stop()
		ch.Save()
	}
H
holisticode 已提交
438 439 440 441 442 443
	if self.swap != nil {
		self.swap.Close()
	}
	if self.accountingMetrics != nil {
		self.accountingMetrics.Close()
	}
B
Balint Gabor 已提交
444 445
	if self.netStore != nil {
		self.netStore.Close()
446
	}
447
	self.sfs.Stop()
448
	stopCounter.Inc(1)
E
ethersphere 已提交
449
	self.streamer.Stop()
H
holisticode 已提交
450 451 452 453 454 455

	err := self.bzz.Stop()
	if self.stateStore != nil {
		self.stateStore.Close()
	}
	return err
456 457
}

458 459 460 461 462 463
// Protocols implements the node.Service interface
func (s *Swarm) Protocols() (protos []p2p.Protocol) {
	if s.config.BootnodeMode {
		protos = append(protos, s.bzz.Protocols()...)
	} else {
		protos = append(protos, s.bzz.Protocols()...)
E
ethersphere 已提交
464

465 466 467
		if s.ps != nil {
			protos = append(protos, s.ps.Protocols()...)
		}
E
ethersphere 已提交
468 469 470 471
	}
	return
}

472
// implements node.Service
E
ethersphere 已提交
473
// APIs returns the RPC API descriptors the Swarm implementation offers
474
func (self *Swarm) APIs() []rpc.API {
E
ethersphere 已提交
475 476

	apis := []rpc.API{
477 478 479
		// public APIs
		{
			Namespace: "bzz",
E
ethersphere 已提交
480
			Version:   "3.0",
481 482 483 484 485 486
			Service:   &Info{self.config, chequebook.ContractParams},
			Public:    true,
		},
		// admin APIs
		{
			Namespace: "bzz",
E
ethersphere 已提交
487 488
			Version:   "3.0",
			Service:   api.NewControl(self.api, self.bzz.Hive),
489 490 491 492 493
			Public:    false,
		},
		{
			Namespace: "chequebook",
			Version:   chequebook.Version,
494
			Service:   chequebook.NewAPI(self.config.Swap.Chequebook),
495 496
			Public:    false,
		},
497 498
		{
			Namespace: "swarmfs",
499
			Version:   fuse.Swarmfs_Version,
500 501 502
			Service:   self.sfs,
			Public:    false,
		},
503 504 505 506 507 508
		{
			Namespace: "accounting",
			Version:   protocols.AccountingVersion,
			Service:   protocols.NewAccountingApi(self.accountingMetrics),
			Public:    false,
		},
509
	}
E
ethersphere 已提交
510 511 512 513 514 515 516 517

	apis = append(apis, self.bzz.APIs()...)

	if self.ps != nil {
		apis = append(apis, self.ps.APIs()...)
	}

	return apis
518 519 520 521 522 523 524 525
}

// SetChequebook ensures that the local checquebook is set up on chain.
func (self *Swarm) SetChequebook(ctx context.Context) error {
	err := self.config.Swap.SetChequebook(ctx, self.backend, self.config.Path)
	if err != nil {
		return err
	}
526
	log.Info(fmt.Sprintf("new chequebook set (%v): saving config file, resetting all connections in the hive", self.config.Swap.Contract.Hex()))
527 528 529 530 531 532 533 534 535 536 537 538
	return nil
}

// serialisable info about swarm
type Info struct {
	*api.Config
	*chequebook.Params
}

func (self *Info) Info() *Info {
	return self
}