swarm.go 16 KB

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