github.com/pslzym/go-ethereum@v1.8.17-0.20180926104442-4b6824e07b1b/swarm/swarm.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package swarm
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"crypto/ecdsa"
    23  	"fmt"
    24  	"io"
    25  	"math/big"
    26  	"net"
    27  	"path/filepath"
    28  	"strings"
    29  	"time"
    30  	"unicode"
    31  
    32  	"github.com/ethereum/go-ethereum/accounts/abi/bind"
    33  	"github.com/ethereum/go-ethereum/common"
    34  	"github.com/ethereum/go-ethereum/contracts/chequebook"
    35  	"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"
    40  	"github.com/ethereum/go-ethereum/p2p/protocols"
    41  	"github.com/ethereum/go-ethereum/params"
    42  	"github.com/ethereum/go-ethereum/rpc"
    43  	"github.com/ethereum/go-ethereum/swarm/api"
    44  	httpapi "github.com/ethereum/go-ethereum/swarm/api/http"
    45  	"github.com/ethereum/go-ethereum/swarm/fuse"
    46  	"github.com/ethereum/go-ethereum/swarm/log"
    47  	"github.com/ethereum/go-ethereum/swarm/network"
    48  	"github.com/ethereum/go-ethereum/swarm/network/stream"
    49  	"github.com/ethereum/go-ethereum/swarm/pss"
    50  	"github.com/ethereum/go-ethereum/swarm/state"
    51  	"github.com/ethereum/go-ethereum/swarm/storage"
    52  	"github.com/ethereum/go-ethereum/swarm/storage/mock"
    53  	"github.com/ethereum/go-ethereum/swarm/storage/mru"
    54  	"github.com/ethereum/go-ethereum/swarm/tracing"
    55  )
    56  
    57  var (
    58  	startTime          time.Time
    59  	updateGaugesPeriod = 5 * time.Second
    60  	startCounter       = metrics.NewRegisteredCounter("stack,start", nil)
    61  	stopCounter        = metrics.NewRegisteredCounter("stack,stop", nil)
    62  	uptimeGauge        = metrics.NewRegisteredGauge("stack.uptime", nil)
    63  	requestsCacheGauge = metrics.NewRegisteredGauge("storage.cache.requests.size", nil)
    64  )
    65  
    66  // the swarm stack
    67  type Swarm struct {
    68  	config      *api.Config        // swarm configuration
    69  	api         *api.API           // high level api layer (fs/manifest)
    70  	dns         api.Resolver       // DNS registrar
    71  	fileStore   *storage.FileStore // distributed preimage archive, the local API to the storage with document level storage/retrieval support
    72  	streamer    *stream.Registry
    73  	bzz         *network.Bzz       // the logistic manager
    74  	backend     chequebook.Backend // simple blockchain Backend
    75  	privateKey  *ecdsa.PrivateKey
    76  	corsString  string
    77  	swapEnabled bool
    78  	netStore    *storage.NetStore
    79  	sfs         *fuse.SwarmFS // need this to cleanup all the active mounts on node exit
    80  	ps          *pss.Pss
    81  
    82  	tracerClose io.Closer
    83  }
    84  
    85  type SwarmAPI struct {
    86  	Api     *api.API
    87  	Backend chequebook.Backend
    88  }
    89  
    90  func (self *Swarm) API() *SwarmAPI {
    91  	return &SwarmAPI{
    92  		Api:     self.api,
    93  		Backend: self.backend,
    94  	}
    95  }
    96  
    97  // creates a new swarm service instance
    98  // implements node.Service
    99  // If mockStore is not nil, it will be used as the storage for chunk data.
   100  // MockStore should be used only for testing.
   101  func NewSwarm(config *api.Config, mockStore *mock.NodeStore) (self *Swarm, err error) {
   102  
   103  	if bytes.Equal(common.FromHex(config.PublicKey), storage.ZeroAddr) {
   104  		return nil, fmt.Errorf("empty public key")
   105  	}
   106  	if bytes.Equal(common.FromHex(config.BzzKey), storage.ZeroAddr) {
   107  		return nil, fmt.Errorf("empty bzz key")
   108  	}
   109  
   110  	var backend chequebook.Backend
   111  	if config.SwapAPI != "" && config.SwapEnabled {
   112  		log.Info("connecting to SWAP API", "url", config.SwapAPI)
   113  		backend, err = ethclient.Dial(config.SwapAPI)
   114  		if err != nil {
   115  			return nil, fmt.Errorf("error connecting to SWAP API %s: %s", config.SwapAPI, err)
   116  		}
   117  	}
   118  
   119  	self = &Swarm{
   120  		config:     config,
   121  		backend:    backend,
   122  		privateKey: config.ShiftPrivateKey(),
   123  	}
   124  	log.Debug("Setting up Swarm service components")
   125  
   126  	config.HiveParams.Discovery = true
   127  
   128  	bzzconfig := &network.BzzConfig{
   129  		NetworkID:   config.NetworkID,
   130  		OverlayAddr: common.FromHex(config.BzzKey),
   131  		HiveParams:  config.HiveParams,
   132  		LightNode:   config.LightNodeEnabled,
   133  	}
   134  
   135  	stateStore, err := state.NewDBStore(filepath.Join(config.Path, "state-store.db"))
   136  	if err != nil {
   137  		return
   138  	}
   139  
   140  	// set up high level api
   141  	var resolver *api.MultiResolver
   142  	if len(config.EnsAPIs) > 0 {
   143  		opts := []api.MultiResolverOption{}
   144  		for _, c := range config.EnsAPIs {
   145  			tld, endpoint, addr := parseEnsAPIAddress(c)
   146  			r, err := newEnsClient(endpoint, addr, config, self.privateKey)
   147  			if err != nil {
   148  				return nil, err
   149  			}
   150  			opts = append(opts, api.MultiResolverOptionWithResolver(r, tld))
   151  
   152  		}
   153  		resolver = api.NewMultiResolver(opts...)
   154  		self.dns = resolver
   155  	}
   156  
   157  	lstore, err := storage.NewLocalStore(config.LocalStoreParams, mockStore)
   158  	if err != nil {
   159  		return nil, err
   160  	}
   161  
   162  	self.netStore, err = storage.NewNetStore(lstore, nil)
   163  	if err != nil {
   164  		return nil, err
   165  	}
   166  
   167  	to := network.NewKademlia(
   168  		common.FromHex(config.BzzKey),
   169  		network.NewKadParams(),
   170  	)
   171  	delivery := stream.NewDelivery(to, self.netStore)
   172  	self.netStore.NewNetFetcherFunc = network.NewFetcherFactory(delivery.RequestFromPeers, config.DeliverySkipCheck).New
   173  
   174  	var nodeID enode.ID
   175  	if err := nodeID.UnmarshalText([]byte(config.NodeID)); err != nil {
   176  		return nil, err
   177  	}
   178  	self.streamer = stream.NewRegistry(nodeID, delivery, self.netStore, stateStore, &stream.RegistryOptions{
   179  		SkipCheck:       config.DeliverySkipCheck,
   180  		DoSync:          config.SyncEnabled,
   181  		DoRetrieve:      true,
   182  		SyncUpdateDelay: config.SyncUpdateDelay,
   183  	})
   184  
   185  	// Swarm Hash Merklised Chunking for Arbitrary-length Document/File storage
   186  	self.fileStore = storage.NewFileStore(self.netStore, self.config.FileStoreParams)
   187  
   188  	var resourceHandler *mru.Handler
   189  	rhparams := &mru.HandlerParams{}
   190  
   191  	resourceHandler = mru.NewHandler(rhparams)
   192  	resourceHandler.SetStore(self.netStore)
   193  
   194  	lstore.Validators = []storage.ChunkValidator{
   195  		storage.NewContentAddressValidator(storage.MakeHashFunc(storage.DefaultHash)),
   196  		resourceHandler,
   197  	}
   198  
   199  	log.Debug("Setup local storage")
   200  
   201  	self.bzz = network.NewBzz(bzzconfig, to, stateStore, stream.Spec, self.streamer.Run)
   202  
   203  	// Pss = postal service over swarm (devp2p over bzz)
   204  	self.ps, err = pss.NewPss(to, config.Pss)
   205  	if err != nil {
   206  		return nil, err
   207  	}
   208  	if pss.IsActiveHandshake {
   209  		pss.SetHandshakeController(self.ps, pss.NewHandshakeParams())
   210  	}
   211  
   212  	self.api = api.NewAPI(self.fileStore, self.dns, resourceHandler, self.privateKey)
   213  
   214  	self.sfs = fuse.NewSwarmFS(self.api)
   215  	log.Debug("Initialized FUSE filesystem")
   216  
   217  	return self, nil
   218  }
   219  
   220  // parseEnsAPIAddress parses string according to format
   221  // [tld:][contract-addr@]url and returns ENSClientConfig structure
   222  // with endpoint, contract address and TLD.
   223  func parseEnsAPIAddress(s string) (tld, endpoint string, addr common.Address) {
   224  	isAllLetterString := func(s string) bool {
   225  		for _, r := range s {
   226  			if !unicode.IsLetter(r) {
   227  				return false
   228  			}
   229  		}
   230  		return true
   231  	}
   232  	endpoint = s
   233  	if i := strings.Index(endpoint, ":"); i > 0 {
   234  		if isAllLetterString(endpoint[:i]) && len(endpoint) > i+2 && endpoint[i+1:i+3] != "//" {
   235  			tld = endpoint[:i]
   236  			endpoint = endpoint[i+1:]
   237  		}
   238  	}
   239  	if i := strings.Index(endpoint, "@"); i > 0 {
   240  		addr = common.HexToAddress(endpoint[:i])
   241  		endpoint = endpoint[i+1:]
   242  	}
   243  	return
   244  }
   245  
   246  // ensClient provides functionality for api.ResolveValidator
   247  type ensClient struct {
   248  	*ens.ENS
   249  	*ethclient.Client
   250  }
   251  
   252  // newEnsClient creates a new ENS client for that is a consumer of
   253  // a ENS API on a specific endpoint. It is used as a helper function
   254  // for creating multiple resolvers in NewSwarm function.
   255  func newEnsClient(endpoint string, addr common.Address, config *api.Config, privkey *ecdsa.PrivateKey) (*ensClient, error) {
   256  	log.Info("connecting to ENS API", "url", endpoint)
   257  	client, err := rpc.Dial(endpoint)
   258  	if err != nil {
   259  		return nil, fmt.Errorf("error connecting to ENS API %s: %s", endpoint, err)
   260  	}
   261  	ethClient := ethclient.NewClient(client)
   262  
   263  	ensRoot := config.EnsRoot
   264  	if addr != (common.Address{}) {
   265  		ensRoot = addr
   266  	} else {
   267  		a, err := detectEnsAddr(client)
   268  		if err == nil {
   269  			ensRoot = a
   270  		} else {
   271  			log.Warn(fmt.Sprintf("could not determine ENS contract address, using default %s", ensRoot), "err", err)
   272  		}
   273  	}
   274  	transactOpts := bind.NewKeyedTransactor(privkey)
   275  	dns, err := ens.NewENS(transactOpts, ensRoot, ethClient)
   276  	if err != nil {
   277  		return nil, err
   278  	}
   279  	log.Debug(fmt.Sprintf("-> Swarm Domain Name Registrar %v @ address %v", endpoint, ensRoot.Hex()))
   280  	return &ensClient{
   281  		ENS:    dns,
   282  		Client: ethClient,
   283  	}, err
   284  }
   285  
   286  // detectEnsAddr determines the ENS contract address by getting both the
   287  // version and genesis hash using the client and matching them to either
   288  // mainnet or testnet addresses
   289  func detectEnsAddr(client *rpc.Client) (common.Address, error) {
   290  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
   291  	defer cancel()
   292  
   293  	var version string
   294  	if err := client.CallContext(ctx, &version, "net_version"); err != nil {
   295  		return common.Address{}, err
   296  	}
   297  
   298  	block, err := ethclient.NewClient(client).BlockByNumber(ctx, big.NewInt(0))
   299  	if err != nil {
   300  		return common.Address{}, err
   301  	}
   302  
   303  	switch {
   304  
   305  	case version == "1" && block.Hash() == params.MainnetGenesisHash:
   306  		log.Info("using Mainnet ENS contract address", "addr", ens.MainNetAddress)
   307  		return ens.MainNetAddress, nil
   308  
   309  	case version == "3" && block.Hash() == params.TestnetGenesisHash:
   310  		log.Info("using Testnet ENS contract address", "addr", ens.TestNetAddress)
   311  		return ens.TestNetAddress, nil
   312  
   313  	default:
   314  		return common.Address{}, fmt.Errorf("unknown version and genesis hash: %s %s", version, block.Hash())
   315  	}
   316  }
   317  
   318  /*
   319  Start is called when the stack is started
   320  * starts the network kademlia hive peer management
   321  * (starts netStore level 0 api)
   322  * starts DPA level 1 api (chunking -> store/retrieve requests)
   323  * (starts level 2 api)
   324  * starts http proxy server
   325  * registers url scheme handlers for bzz, etc
   326  * TODO: start subservices like sword, swear, swarmdns
   327  */
   328  // implements the node.Service interface
   329  func (self *Swarm) Start(srv *p2p.Server) error {
   330  	startTime = time.Now()
   331  
   332  	self.tracerClose = tracing.Closer
   333  
   334  	// update uaddr to correct enode
   335  	newaddr := self.bzz.UpdateLocalAddr([]byte(srv.Self().String()))
   336  	log.Info("Updated bzz local addr", "oaddr", fmt.Sprintf("%x", newaddr.OAddr), "uaddr", fmt.Sprintf("%s", newaddr.UAddr))
   337  	// set chequebook
   338  	if self.config.SwapEnabled {
   339  		ctx := context.Background() // The initial setup has no deadline.
   340  		err := self.SetChequebook(ctx)
   341  		if err != nil {
   342  			return fmt.Errorf("Unable to set chequebook for SWAP: %v", err)
   343  		}
   344  		log.Debug(fmt.Sprintf("-> cheque book for SWAP: %v", self.config.Swap.Chequebook()))
   345  	} else {
   346  		log.Debug(fmt.Sprintf("SWAP disabled: no cheque book set"))
   347  	}
   348  
   349  	log.Info("Starting bzz service")
   350  
   351  	err := self.bzz.Start(srv)
   352  	if err != nil {
   353  		log.Error("bzz failed", "err", err)
   354  		return err
   355  	}
   356  	log.Info("Swarm network started", "bzzaddr", fmt.Sprintf("%x", self.bzz.Hive.BaseAddr()))
   357  
   358  	if self.ps != nil {
   359  		self.ps.Start(srv)
   360  	}
   361  
   362  	// start swarm http proxy server
   363  	if self.config.Port != "" {
   364  		addr := net.JoinHostPort(self.config.ListenAddr, self.config.Port)
   365  		server := httpapi.NewServer(self.api, self.config.Cors)
   366  
   367  		if self.config.Cors != "" {
   368  			log.Debug("Swarm HTTP proxy CORS headers", "allowedOrigins", self.config.Cors)
   369  		}
   370  
   371  		log.Debug("Starting Swarm HTTP proxy", "port", self.config.Port)
   372  		go func() {
   373  			err := server.ListenAndServe(addr)
   374  			if err != nil {
   375  				log.Error("Could not start Swarm HTTP proxy", "err", err.Error())
   376  			}
   377  		}()
   378  	}
   379  
   380  	self.periodicallyUpdateGauges()
   381  
   382  	startCounter.Inc(1)
   383  	self.streamer.Start(srv)
   384  	return nil
   385  }
   386  
   387  func (self *Swarm) periodicallyUpdateGauges() {
   388  	ticker := time.NewTicker(updateGaugesPeriod)
   389  
   390  	go func() {
   391  		for range ticker.C {
   392  			self.updateGauges()
   393  		}
   394  	}()
   395  }
   396  
   397  func (self *Swarm) updateGauges() {
   398  	uptimeGauge.Update(time.Since(startTime).Nanoseconds())
   399  	requestsCacheGauge.Update(int64(self.netStore.RequestsCacheLen()))
   400  }
   401  
   402  // implements the node.Service interface
   403  // stops all component services.
   404  func (self *Swarm) Stop() error {
   405  	if self.tracerClose != nil {
   406  		err := self.tracerClose.Close()
   407  		if err != nil {
   408  			return err
   409  		}
   410  	}
   411  
   412  	if self.ps != nil {
   413  		self.ps.Stop()
   414  	}
   415  	if ch := self.config.Swap.Chequebook(); ch != nil {
   416  		ch.Stop()
   417  		ch.Save()
   418  	}
   419  
   420  	if self.netStore != nil {
   421  		self.netStore.Close()
   422  	}
   423  	self.sfs.Stop()
   424  	stopCounter.Inc(1)
   425  	self.streamer.Stop()
   426  	return self.bzz.Stop()
   427  }
   428  
   429  // implements the node.Service interface
   430  func (self *Swarm) Protocols() (protos []p2p.Protocol) {
   431  	protos = append(protos, self.bzz.Protocols()...)
   432  
   433  	if self.ps != nil {
   434  		protos = append(protos, self.ps.Protocols()...)
   435  	}
   436  	return
   437  }
   438  
   439  func (self *Swarm) RegisterPssProtocol(spec *protocols.Spec, targetprotocol *p2p.Protocol, options *pss.ProtocolParams) (*pss.Protocol, error) {
   440  	if !pss.IsActiveProtocol {
   441  		return nil, fmt.Errorf("Pss protocols not available (built with !nopssprotocol tag)")
   442  	}
   443  	topic := pss.ProtocolTopic(spec)
   444  	return pss.RegisterProtocol(self.ps, &topic, spec, targetprotocol, options)
   445  }
   446  
   447  // implements node.Service
   448  // APIs returns the RPC API descriptors the Swarm implementation offers
   449  func (self *Swarm) APIs() []rpc.API {
   450  
   451  	apis := []rpc.API{
   452  		// public APIs
   453  		{
   454  			Namespace: "bzz",
   455  			Version:   "3.0",
   456  			Service:   &Info{self.config, chequebook.ContractParams},
   457  			Public:    true,
   458  		},
   459  		// admin APIs
   460  		{
   461  			Namespace: "bzz",
   462  			Version:   "3.0",
   463  			Service:   api.NewControl(self.api, self.bzz.Hive),
   464  			Public:    false,
   465  		},
   466  		{
   467  			Namespace: "chequebook",
   468  			Version:   chequebook.Version,
   469  			Service:   chequebook.NewApi(self.config.Swap.Chequebook),
   470  			Public:    false,
   471  		},
   472  		{
   473  			Namespace: "swarmfs",
   474  			Version:   fuse.Swarmfs_Version,
   475  			Service:   self.sfs,
   476  			Public:    false,
   477  		},
   478  	}
   479  
   480  	apis = append(apis, self.bzz.APIs()...)
   481  
   482  	if self.ps != nil {
   483  		apis = append(apis, self.ps.APIs()...)
   484  	}
   485  
   486  	return apis
   487  }
   488  
   489  func (self *Swarm) Api() *api.API {
   490  	return self.api
   491  }
   492  
   493  // SetChequebook ensures that the local checquebook is set up on chain.
   494  func (self *Swarm) SetChequebook(ctx context.Context) error {
   495  	err := self.config.Swap.SetChequebook(ctx, self.backend, self.config.Path)
   496  	if err != nil {
   497  		return err
   498  	}
   499  	log.Info(fmt.Sprintf("new chequebook set (%v): saving config file, resetting all connections in the hive", self.config.Swap.Contract.Hex()))
   500  	return nil
   501  }
   502  
   503  // serialisable info about swarm
   504  type Info struct {
   505  	*api.Config
   506  	*chequebook.Params
   507  }
   508  
   509  func (self *Info) Info() *Info {
   510  	return self
   511  }