github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/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/PlatONnetwork/PlatON-Go/accounts/abi/bind"
    33  	"github.com/PlatONnetwork/PlatON-Go/common"
    34  	"github.com/PlatONnetwork/PlatON-Go/contracts/chequebook"
    35  	"github.com/PlatONnetwork/PlatON-Go/contracts/ens"
    36  	"github.com/PlatONnetwork/PlatON-Go/ethclient"
    37  	"github.com/PlatONnetwork/PlatON-Go/metrics"
    38  	"github.com/PlatONnetwork/PlatON-Go/p2p"
    39  	"github.com/PlatONnetwork/PlatON-Go/p2p/discover"
    40  	"github.com/PlatONnetwork/PlatON-Go/p2p/protocols"
    41  	"github.com/PlatONnetwork/PlatON-Go/params"
    42  	"github.com/PlatONnetwork/PlatON-Go/rpc"
    43  	"github.com/PlatONnetwork/PlatON-Go/swarm/api"
    44  	httpapi "github.com/PlatONnetwork/PlatON-Go/swarm/api/http"
    45  	"github.com/PlatONnetwork/PlatON-Go/swarm/fuse"
    46  	"github.com/PlatONnetwork/PlatON-Go/swarm/log"
    47  	"github.com/PlatONnetwork/PlatON-Go/swarm/network"
    48  	"github.com/PlatONnetwork/PlatON-Go/swarm/network/stream"
    49  	"github.com/PlatONnetwork/PlatON-Go/swarm/pss"
    50  	"github.com/PlatONnetwork/PlatON-Go/swarm/state"
    51  	"github.com/PlatONnetwork/PlatON-Go/swarm/storage"
    52  	"github.com/PlatONnetwork/PlatON-Go/swarm/storage/mock"
    53  	"github.com/PlatONnetwork/PlatON-Go/swarm/storage/mru"
    54  	"github.com/PlatONnetwork/PlatON-Go/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  	nodeID, err := discover.HexID(config.NodeID)
   129  	if err != nil {
   130  		return nil, err
   131  	}
   132  	addr := &network.BzzAddr{
   133  		OAddr: common.FromHex(config.BzzKey),
   134  		UAddr: []byte(discover.NewNode(nodeID, net.IP{127, 0, 0, 1}, 16789, 16789).String()),
   135  	}
   136  
   137  	bzzconfig := &network.BzzConfig{
   138  		NetworkID:    config.NetworkID,
   139  		OverlayAddr:  addr.OAddr,
   140  		UnderlayAddr: addr.UAddr,
   141  		HiveParams:   config.HiveParams,
   142  		LightNode:    config.LightNodeEnabled,
   143  	}
   144  
   145  	stateStore, err := state.NewDBStore(filepath.Join(config.Path, "state-store.db"))
   146  	if err != nil {
   147  		return
   148  	}
   149  
   150  	// set up high level api
   151  	var resolver *api.MultiResolver
   152  	if len(config.EnsAPIs) > 0 {
   153  		opts := []api.MultiResolverOption{}
   154  		for _, c := range config.EnsAPIs {
   155  			tld, endpoint, addr := parseEnsAPIAddress(c)
   156  			r, err := newEnsClient(endpoint, addr, config, self.privateKey)
   157  			if err != nil {
   158  				return nil, err
   159  			}
   160  			opts = append(opts, api.MultiResolverOptionWithResolver(r, tld))
   161  
   162  		}
   163  		resolver = api.NewMultiResolver(opts...)
   164  		self.dns = resolver
   165  	}
   166  
   167  	lstore, err := storage.NewLocalStore(config.LocalStoreParams, mockStore)
   168  	if err != nil {
   169  		return nil, err
   170  	}
   171  
   172  	self.netStore, err = storage.NewNetStore(lstore, nil)
   173  	if err != nil {
   174  		return nil, err
   175  	}
   176  
   177  	to := network.NewKademlia(
   178  		common.FromHex(config.BzzKey),
   179  		network.NewKadParams(),
   180  	)
   181  	delivery := stream.NewDelivery(to, self.netStore)
   182  	self.netStore.NewNetFetcherFunc = network.NewFetcherFactory(delivery.RequestFromPeers, config.DeliverySkipCheck).New
   183  
   184  	self.streamer = stream.NewRegistry(addr, delivery, self.netStore, stateStore, &stream.RegistryOptions{
   185  		SkipCheck:       config.SyncingSkipCheck,
   186  		DoSync:          config.SyncEnabled,
   187  		DoRetrieve:      true,
   188  		SyncUpdateDelay: config.SyncUpdateDelay,
   189  	})
   190  
   191  	// Swarm Hash Merklised Chunking for Arbitrary-length Document/File storage
   192  	self.fileStore = storage.NewFileStore(self.netStore, self.config.FileStoreParams)
   193  
   194  	var resourceHandler *mru.Handler
   195  	rhparams := &mru.HandlerParams{}
   196  
   197  	resourceHandler = mru.NewHandler(rhparams)
   198  	resourceHandler.SetStore(self.netStore)
   199  
   200  	lstore.Validators = []storage.ChunkValidator{
   201  		storage.NewContentAddressValidator(storage.MakeHashFunc(storage.DefaultHash)),
   202  		resourceHandler,
   203  	}
   204  
   205  	log.Debug("Setup local storage")
   206  
   207  	self.bzz = network.NewBzz(bzzconfig, to, stateStore, stream.Spec, self.streamer.Run)
   208  
   209  	// Pss = postal service over swarm (devp2p over bzz)
   210  	self.ps, err = pss.NewPss(to, config.Pss)
   211  	if err != nil {
   212  		return nil, err
   213  	}
   214  	if pss.IsActiveHandshake {
   215  		pss.SetHandshakeController(self.ps, pss.NewHandshakeParams())
   216  	}
   217  
   218  	self.api = api.NewAPI(self.fileStore, self.dns, resourceHandler, self.privateKey)
   219  
   220  	self.sfs = fuse.NewSwarmFS(self.api)
   221  	log.Debug("Initialized FUSE filesystem")
   222  
   223  	return self, nil
   224  }
   225  
   226  // parseEnsAPIAddress parses string according to format
   227  // [tld:][contract-addr@]url and returns ENSClientConfig structure
   228  // with endpoint, contract address and TLD.
   229  func parseEnsAPIAddress(s string) (tld, endpoint string, addr common.Address) {
   230  	isAllLetterString := func(s string) bool {
   231  		for _, r := range s {
   232  			if !unicode.IsLetter(r) {
   233  				return false
   234  			}
   235  		}
   236  		return true
   237  	}
   238  	endpoint = s
   239  	if i := strings.Index(endpoint, ":"); i > 0 {
   240  		if isAllLetterString(endpoint[:i]) && len(endpoint) > i+2 && endpoint[i+1:i+3] != "//" {
   241  			tld = endpoint[:i]
   242  			endpoint = endpoint[i+1:]
   243  		}
   244  	}
   245  	if i := strings.Index(endpoint, "@"); i > 0 {
   246  		addr = common.HexToAddress(endpoint[:i])
   247  		endpoint = endpoint[i+1:]
   248  	}
   249  	return
   250  }
   251  
   252  // ensClient provides functionality for api.ResolveValidator
   253  type ensClient struct {
   254  	*ens.ENS
   255  	*ethclient.Client
   256  }
   257  
   258  // newEnsClient creates a new ENS client for that is a consumer of
   259  // a ENS API on a specific endpoint. It is used as a helper function
   260  // for creating multiple resolvers in NewSwarm function.
   261  func newEnsClient(endpoint string, addr common.Address, config *api.Config, privkey *ecdsa.PrivateKey) (*ensClient, error) {
   262  	log.Info("connecting to ENS API", "url", endpoint)
   263  	client, err := rpc.Dial(endpoint)
   264  	if err != nil {
   265  		return nil, fmt.Errorf("error connecting to ENS API %s: %s", endpoint, err)
   266  	}
   267  	ethClient := ethclient.NewClient(client)
   268  
   269  	ensRoot := config.EnsRoot
   270  	if addr != (common.Address{}) {
   271  		ensRoot = addr
   272  	} else {
   273  		a, err := detectEnsAddr(client)
   274  		if err == nil {
   275  			ensRoot = a
   276  		} else {
   277  			log.Warn(fmt.Sprintf("could not determine ENS contract address, using default %s", ensRoot), "err", err)
   278  		}
   279  	}
   280  	transactOpts := bind.NewKeyedTransactor(privkey)
   281  	dns, err := ens.NewENS(transactOpts, ensRoot, ethClient)
   282  	if err != nil {
   283  		return nil, err
   284  	}
   285  	log.Debug(fmt.Sprintf("-> Swarm Domain Name Registrar %v @ address %v", endpoint, ensRoot.Hex()))
   286  	return &ensClient{
   287  		ENS:    dns,
   288  		Client: ethClient,
   289  	}, err
   290  }
   291  
   292  // detectEnsAddr determines the ENS contract address by getting both the
   293  // version and genesis hash using the client and matching them to either
   294  // mainnet or testnet addresses
   295  func detectEnsAddr(client *rpc.Client) (common.Address, error) {
   296  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
   297  	defer cancel()
   298  
   299  	var version string
   300  	if err := client.CallContext(ctx, &version, "net_version"); err != nil {
   301  		return common.Address{}, err
   302  	}
   303  
   304  	block, err := ethclient.NewClient(client).BlockByNumber(ctx, big.NewInt(0))
   305  	if err != nil {
   306  		return common.Address{}, err
   307  	}
   308  
   309  	switch {
   310  
   311  	case version == "1" && block.Hash() == params.MainnetGenesisHash:
   312  		log.Info("using Mainnet ENS contract address", "addr", ens.MainNetAddress)
   313  		return ens.MainNetAddress, nil
   314  
   315  	case version == "3" && block.Hash() == params.TestnetGenesisHash:
   316  		log.Info("using Testnet ENS contract address", "addr", ens.TestNetAddress)
   317  		return ens.TestNetAddress, nil
   318  
   319  	default:
   320  		return common.Address{}, fmt.Errorf("unknown version and genesis hash: %s %s", version, block.Hash())
   321  	}
   322  }
   323  
   324  /*
   325  Start is called when the stack is started
   326  * starts the network kademlia hive peer management
   327  * (starts netStore level 0 api)
   328  * starts DPA level 1 api (chunking -> store/retrieve requests)
   329  * (starts level 2 api)
   330  * starts http proxy server
   331  * registers url scheme handlers for bzz, etc
   332  * TODO: start subservices like sword, swear, swarmdns
   333  */
   334  // implements the node.Service interface
   335  func (self *Swarm) Start(srv *p2p.Server) error {
   336  	startTime = time.Now()
   337  
   338  	self.tracerClose = tracing.Closer
   339  
   340  	// update uaddr to correct enode
   341  	newaddr := self.bzz.UpdateLocalAddr([]byte(srv.Self().String()))
   342  	log.Info("Updated bzz local addr", "oaddr", fmt.Sprintf("%x", newaddr.OAddr), "uaddr", fmt.Sprintf("%s", newaddr.UAddr))
   343  	// set chequebook
   344  	if self.config.SwapEnabled {
   345  		ctx := context.Background() // The initial setup has no deadline.
   346  		err := self.SetChequebook(ctx)
   347  		if err != nil {
   348  			return fmt.Errorf("Unable to set chequebook for SWAP: %v", err)
   349  		}
   350  		log.Debug(fmt.Sprintf("-> cheque book for SWAP: %v", self.config.Swap.Chequebook()))
   351  	} else {
   352  		log.Debug(fmt.Sprintf("SWAP disabled: no cheque book set"))
   353  	}
   354  
   355  	log.Info("Starting bzz service")
   356  
   357  	err := self.bzz.Start(srv)
   358  	if err != nil {
   359  		log.Error("bzz failed", "err", err)
   360  		return err
   361  	}
   362  	log.Info("Swarm network started", "bzzaddr", fmt.Sprintf("%x", self.bzz.Hive.BaseAddr()))
   363  
   364  	if self.ps != nil {
   365  		self.ps.Start(srv)
   366  	}
   367  
   368  	// start swarm http proxy server
   369  	if self.config.Port != "" {
   370  		addr := net.JoinHostPort(self.config.ListenAddr, self.config.Port)
   371  		server := httpapi.NewServer(self.api, self.config.Cors)
   372  
   373  		if self.config.Cors != "" {
   374  			log.Debug("Swarm HTTP proxy CORS headers", "allowedOrigins", self.config.Cors)
   375  		}
   376  
   377  		log.Debug("Starting Swarm HTTP proxy", "port", self.config.Port)
   378  		go func() {
   379  			err := server.ListenAndServe(addr)
   380  			if err != nil {
   381  				log.Error("Could not start Swarm HTTP proxy", "err", err.Error())
   382  			}
   383  		}()
   384  	}
   385  
   386  	self.periodicallyUpdateGauges()
   387  
   388  	startCounter.Inc(1)
   389  	self.streamer.Start(srv)
   390  	return nil
   391  }
   392  
   393  func (self *Swarm) periodicallyUpdateGauges() {
   394  	ticker := time.NewTicker(updateGaugesPeriod)
   395  
   396  	go func() {
   397  		for range ticker.C {
   398  			self.updateGauges()
   399  		}
   400  	}()
   401  }
   402  
   403  func (self *Swarm) updateGauges() {
   404  	uptimeGauge.Update(time.Since(startTime).Nanoseconds())
   405  	requestsCacheGauge.Update(int64(self.netStore.RequestsCacheLen()))
   406  }
   407  
   408  // implements the node.Service interface
   409  // stops all component services.
   410  func (self *Swarm) Stop() error {
   411  	if self.tracerClose != nil {
   412  		err := self.tracerClose.Close()
   413  		if err != nil {
   414  			return err
   415  		}
   416  	}
   417  
   418  	if self.ps != nil {
   419  		self.ps.Stop()
   420  	}
   421  	if ch := self.config.Swap.Chequebook(); ch != nil {
   422  		ch.Stop()
   423  		ch.Save()
   424  	}
   425  
   426  	if self.netStore != nil {
   427  		self.netStore.Close()
   428  	}
   429  	self.sfs.Stop()
   430  	stopCounter.Inc(1)
   431  	self.streamer.Stop()
   432  	return self.bzz.Stop()
   433  }
   434  
   435  // implements the node.Service interface
   436  func (self *Swarm) Protocols() (protos []p2p.Protocol) {
   437  	protos = append(protos, self.bzz.Protocols()...)
   438  
   439  	if self.ps != nil {
   440  		protos = append(protos, self.ps.Protocols()...)
   441  	}
   442  	return
   443  }
   444  
   445  func (self *Swarm) RegisterPssProtocol(spec *protocols.Spec, targetprotocol *p2p.Protocol, options *pss.ProtocolParams) (*pss.Protocol, error) {
   446  	if !pss.IsActiveProtocol {
   447  		return nil, fmt.Errorf("Pss protocols not available (built with !nopssprotocol tag)")
   448  	}
   449  	topic := pss.ProtocolTopic(spec)
   450  	return pss.RegisterProtocol(self.ps, &topic, spec, targetprotocol, options)
   451  }
   452  
   453  // implements node.Service
   454  // APIs returns the RPC API descriptors the Swarm implementation offers
   455  func (self *Swarm) APIs() []rpc.API {
   456  
   457  	apis := []rpc.API{
   458  		// public APIs
   459  		{
   460  			Namespace: "bzz",
   461  			Version:   "3.0",
   462  			Service:   &Info{self.config, chequebook.ContractParams},
   463  			Public:    true,
   464  		},
   465  		// admin APIs
   466  		{
   467  			Namespace: "bzz",
   468  			Version:   "3.0",
   469  			Service:   api.NewControl(self.api, self.bzz.Hive),
   470  			Public:    false,
   471  		},
   472  		{
   473  			Namespace: "chequebook",
   474  			Version:   chequebook.Version,
   475  			Service:   chequebook.NewApi(self.config.Swap.Chequebook),
   476  			Public:    false,
   477  		},
   478  		{
   479  			Namespace: "swarmfs",
   480  			Version:   fuse.Swarmfs_Version,
   481  			Service:   self.sfs,
   482  			Public:    false,
   483  		},
   484  	}
   485  
   486  	apis = append(apis, self.bzz.APIs()...)
   487  
   488  	if self.ps != nil {
   489  		apis = append(apis, self.ps.APIs()...)
   490  	}
   491  
   492  	return apis
   493  }
   494  
   495  func (self *Swarm) Api() *api.API {
   496  	return self.api
   497  }
   498  
   499  // SetChequebook ensures that the local checquebook is set up on chain.
   500  func (self *Swarm) SetChequebook(ctx context.Context) error {
   501  	err := self.config.Swap.SetChequebook(ctx, self.backend, self.config.Path)
   502  	if err != nil {
   503  		return err
   504  	}
   505  	log.Info(fmt.Sprintf("new chequebook set (%v): saving config file, resetting all connections in the hive", self.config.Swap.Contract.Hex()))
   506  	return nil
   507  }
   508  
   509  // serialisable info about swarm
   510  type Info struct {
   511  	*api.Config
   512  	*chequebook.Params
   513  }
   514  
   515  func (self *Info) Info() *Info {
   516  	return self
   517  }