swarm.go 16 KB

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