swarm.go 15 KB

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