swarm.go 16 KB

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