swarm.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. log.Debug("Setup local storage")
  175. self.bzz = network.NewBzz(bzzconfig, to, stateStore, stream.Spec, self.streamer.Run)
  176. // Pss = postal service over swarm (devp2p over bzz)
  177. self.ps, err = pss.NewPss(to, config.Pss)
  178. if err != nil {
  179. return nil, err
  180. }
  181. if pss.IsActiveHandshake {
  182. pss.SetHandshakeController(self.ps, pss.NewHandshakeParams())
  183. }
  184. self.api = api.NewAPI(self.fileStore, self.dns, feedsHandler, self.privateKey)
  185. self.sfs = fuse.NewSwarmFS(self.api)
  186. log.Debug("Initialized FUSE filesystem")
  187. return self, nil
  188. }
  189. // parseEnsAPIAddress parses string according to format
  190. // [tld:][contract-addr@]url and returns ENSClientConfig structure
  191. // with endpoint, contract address and TLD.
  192. func parseEnsAPIAddress(s string) (tld, endpoint string, addr common.Address) {
  193. isAllLetterString := func(s string) bool {
  194. for _, r := range s {
  195. if !unicode.IsLetter(r) {
  196. return false
  197. }
  198. }
  199. return true
  200. }
  201. endpoint = s
  202. if i := strings.Index(endpoint, ":"); i > 0 {
  203. if isAllLetterString(endpoint[:i]) && len(endpoint) > i+2 && endpoint[i+1:i+3] != "//" {
  204. tld = endpoint[:i]
  205. endpoint = endpoint[i+1:]
  206. }
  207. }
  208. if i := strings.Index(endpoint, "@"); i > 0 {
  209. addr = common.HexToAddress(endpoint[:i])
  210. endpoint = endpoint[i+1:]
  211. }
  212. return
  213. }
  214. // ensClient provides functionality for api.ResolveValidator
  215. type ensClient struct {
  216. *ens.ENS
  217. *ethclient.Client
  218. }
  219. // newEnsClient creates a new ENS client for that is a consumer of
  220. // a ENS API on a specific endpoint. It is used as a helper function
  221. // for creating multiple resolvers in NewSwarm function.
  222. func newEnsClient(endpoint string, addr common.Address, config *api.Config, privkey *ecdsa.PrivateKey) (*ensClient, error) {
  223. log.Info("connecting to ENS API", "url", endpoint)
  224. client, err := rpc.Dial(endpoint)
  225. if err != nil {
  226. return nil, fmt.Errorf("error connecting to ENS API %s: %s", endpoint, err)
  227. }
  228. ethClient := ethclient.NewClient(client)
  229. ensRoot := config.EnsRoot
  230. if addr != (common.Address{}) {
  231. ensRoot = addr
  232. } else {
  233. a, err := detectEnsAddr(client)
  234. if err == nil {
  235. ensRoot = a
  236. } else {
  237. log.Warn(fmt.Sprintf("could not determine ENS contract address, using default %s", ensRoot), "err", err)
  238. }
  239. }
  240. transactOpts := bind.NewKeyedTransactor(privkey)
  241. dns, err := ens.NewENS(transactOpts, ensRoot, ethClient)
  242. if err != nil {
  243. return nil, err
  244. }
  245. log.Debug(fmt.Sprintf("-> Swarm Domain Name Registrar %v @ address %v", endpoint, ensRoot.Hex()))
  246. return &ensClient{
  247. ENS: dns,
  248. Client: ethClient,
  249. }, err
  250. }
  251. // detectEnsAddr determines the ENS contract address by getting both the
  252. // version and genesis hash using the client and matching them to either
  253. // mainnet or testnet addresses
  254. func detectEnsAddr(client *rpc.Client) (common.Address, error) {
  255. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  256. defer cancel()
  257. var version string
  258. if err := client.CallContext(ctx, &version, "net_version"); err != nil {
  259. return common.Address{}, err
  260. }
  261. block, err := ethclient.NewClient(client).BlockByNumber(ctx, big.NewInt(0))
  262. if err != nil {
  263. return common.Address{}, err
  264. }
  265. switch {
  266. case version == "1" && block.Hash() == params.MainnetGenesisHash:
  267. log.Info("using Mainnet ENS contract address", "addr", ens.MainNetAddress)
  268. return ens.MainNetAddress, nil
  269. case version == "3" && block.Hash() == params.TestnetGenesisHash:
  270. log.Info("using Testnet ENS contract address", "addr", ens.TestNetAddress)
  271. return ens.TestNetAddress, nil
  272. default:
  273. return common.Address{}, fmt.Errorf("unknown version and genesis hash: %s %s", version, block.Hash())
  274. }
  275. }
  276. /*
  277. Start is called when the stack is started
  278. * starts the network kademlia hive peer management
  279. * (starts netStore level 0 api)
  280. * starts DPA level 1 api (chunking -> store/retrieve requests)
  281. * (starts level 2 api)
  282. * starts http proxy server
  283. * registers url scheme handlers for bzz, etc
  284. * TODO: start subservices like sword, swear, swarmdns
  285. */
  286. // implements the node.Service interface
  287. func (self *Swarm) Start(srv *p2p.Server) error {
  288. startTime = time.Now()
  289. self.tracerClose = tracing.Closer
  290. // update uaddr to correct enode
  291. newaddr := self.bzz.UpdateLocalAddr([]byte(srv.Self().String()))
  292. log.Info("Updated bzz local addr", "oaddr", fmt.Sprintf("%x", newaddr.OAddr), "uaddr", fmt.Sprintf("%s", newaddr.UAddr))
  293. // set chequebook
  294. if self.config.SwapEnabled {
  295. ctx := context.Background() // The initial setup has no deadline.
  296. err := self.SetChequebook(ctx)
  297. if err != nil {
  298. return fmt.Errorf("Unable to set chequebook for SWAP: %v", err)
  299. }
  300. log.Debug(fmt.Sprintf("-> cheque book for SWAP: %v", self.config.Swap.Chequebook()))
  301. } else {
  302. log.Debug(fmt.Sprintf("SWAP disabled: no cheque book set"))
  303. }
  304. log.Info("Starting bzz service")
  305. err := self.bzz.Start(srv)
  306. if err != nil {
  307. log.Error("bzz failed", "err", err)
  308. return err
  309. }
  310. log.Info("Swarm network started", "bzzaddr", fmt.Sprintf("%x", self.bzz.Hive.BaseAddr()))
  311. if self.ps != nil {
  312. self.ps.Start(srv)
  313. }
  314. // start swarm http proxy server
  315. if self.config.Port != "" {
  316. addr := net.JoinHostPort(self.config.ListenAddr, self.config.Port)
  317. server := httpapi.NewServer(self.api, self.config.Cors)
  318. if self.config.Cors != "" {
  319. log.Debug("Swarm HTTP proxy CORS headers", "allowedOrigins", self.config.Cors)
  320. }
  321. log.Debug("Starting Swarm HTTP proxy", "port", self.config.Port)
  322. go func() {
  323. err := server.ListenAndServe(addr)
  324. if err != nil {
  325. log.Error("Could not start Swarm HTTP proxy", "err", err.Error())
  326. }
  327. }()
  328. }
  329. self.periodicallyUpdateGauges()
  330. startCounter.Inc(1)
  331. self.streamer.Start(srv)
  332. return nil
  333. }
  334. func (self *Swarm) periodicallyUpdateGauges() {
  335. ticker := time.NewTicker(updateGaugesPeriod)
  336. go func() {
  337. for range ticker.C {
  338. self.updateGauges()
  339. }
  340. }()
  341. }
  342. func (self *Swarm) updateGauges() {
  343. uptimeGauge.Update(time.Since(startTime).Nanoseconds())
  344. requestsCacheGauge.Update(int64(self.netStore.RequestsCacheLen()))
  345. }
  346. // implements the node.Service interface
  347. // stops all component services.
  348. func (self *Swarm) Stop() error {
  349. if self.tracerClose != nil {
  350. err := self.tracerClose.Close()
  351. if err != nil {
  352. return err
  353. }
  354. }
  355. if self.ps != nil {
  356. self.ps.Stop()
  357. }
  358. if ch := self.config.Swap.Chequebook(); ch != nil {
  359. ch.Stop()
  360. ch.Save()
  361. }
  362. if self.netStore != nil {
  363. self.netStore.Close()
  364. }
  365. self.sfs.Stop()
  366. stopCounter.Inc(1)
  367. self.streamer.Stop()
  368. return self.bzz.Stop()
  369. }
  370. // implements the node.Service interface
  371. func (self *Swarm) Protocols() (protos []p2p.Protocol) {
  372. protos = append(protos, self.bzz.Protocols()...)
  373. if self.ps != nil {
  374. protos = append(protos, self.ps.Protocols()...)
  375. }
  376. return
  377. }
  378. func (self *Swarm) RegisterPssProtocol(spec *protocols.Spec, targetprotocol *p2p.Protocol, options *pss.ProtocolParams) (*pss.Protocol, error) {
  379. if !pss.IsActiveProtocol {
  380. return nil, fmt.Errorf("Pss protocols not available (built with !nopssprotocol tag)")
  381. }
  382. topic := pss.ProtocolTopic(spec)
  383. return pss.RegisterProtocol(self.ps, &topic, spec, targetprotocol, options)
  384. }
  385. // implements node.Service
  386. // APIs returns the RPC API descriptors the Swarm implementation offers
  387. func (self *Swarm) APIs() []rpc.API {
  388. apis := []rpc.API{
  389. // public APIs
  390. {
  391. Namespace: "bzz",
  392. Version: "3.0",
  393. Service: &Info{self.config, chequebook.ContractParams},
  394. Public: true,
  395. },
  396. // admin APIs
  397. {
  398. Namespace: "bzz",
  399. Version: "3.0",
  400. Service: api.NewControl(self.api, self.bzz.Hive),
  401. Public: false,
  402. },
  403. {
  404. Namespace: "chequebook",
  405. Version: chequebook.Version,
  406. Service: chequebook.NewApi(self.config.Swap.Chequebook),
  407. Public: false,
  408. },
  409. {
  410. Namespace: "swarmfs",
  411. Version: fuse.Swarmfs_Version,
  412. Service: self.sfs,
  413. Public: false,
  414. },
  415. }
  416. apis = append(apis, self.bzz.APIs()...)
  417. if self.ps != nil {
  418. apis = append(apis, self.ps.APIs()...)
  419. }
  420. return apis
  421. }
  422. func (self *Swarm) Api() *api.API {
  423. return self.api
  424. }
  425. // SetChequebook ensures that the local checquebook is set up on chain.
  426. func (self *Swarm) SetChequebook(ctx context.Context) error {
  427. err := self.config.Swap.SetChequebook(ctx, self.backend, self.config.Path)
  428. if err != nil {
  429. return err
  430. }
  431. log.Info(fmt.Sprintf("new chequebook set (%v): saving config file, resetting all connections in the hive", self.config.Swap.Contract.Hex()))
  432. return nil
  433. }
  434. // serialisable info about swarm
  435. type Info struct {
  436. *api.Config
  437. *chequebook.Params
  438. }
  439. func (self *Info) Info() *Info {
  440. return self
  441. }