swarm.go 15 KB

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