swarm.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. "math/big"
  23. "net"
  24. "strings"
  25. "time"
  26. "unicode"
  27. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/contracts/chequebook"
  30. "github.com/ethereum/go-ethereum/contracts/ens"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/ethclient"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/metrics"
  35. "github.com/ethereum/go-ethereum/node"
  36. "github.com/ethereum/go-ethereum/p2p"
  37. "github.com/ethereum/go-ethereum/p2p/discover"
  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/network"
  44. "github.com/ethereum/go-ethereum/swarm/storage"
  45. )
  46. var (
  47. startTime time.Time
  48. updateGaugesPeriod = 5 * time.Second
  49. startCounter = metrics.NewRegisteredCounter("stack,start", nil)
  50. stopCounter = metrics.NewRegisteredCounter("stack,stop", nil)
  51. uptimeGauge = metrics.NewRegisteredGauge("stack.uptime", nil)
  52. dbSizeGauge = metrics.NewRegisteredGauge("storage.db.chunks.size", nil)
  53. cacheSizeGauge = metrics.NewRegisteredGauge("storage.db.cache.size", nil)
  54. )
  55. // the swarm stack
  56. type Swarm struct {
  57. config *api.Config // swarm configuration
  58. api *api.Api // high level api layer (fs/manifest)
  59. dns api.Resolver // DNS registrar
  60. dbAccess *network.DbAccess // access to local chunk db iterator and storage counter
  61. storage storage.ChunkStore // internal access to storage, common interface to cloud storage backends
  62. dpa *storage.DPA // distributed preimage archive, the local API to the storage with document level storage/retrieval support
  63. depo network.StorageHandler // remote request handler, interface between bzz protocol and the storage
  64. cloud storage.CloudStore // procurement, cloud storage backend (can multi-cloud)
  65. hive *network.Hive // the logistic manager
  66. backend chequebook.Backend // simple blockchain Backend
  67. privateKey *ecdsa.PrivateKey
  68. corsString string
  69. swapEnabled bool
  70. lstore *storage.LocalStore // local store, needs to store for releasing resources after node stopped
  71. sfs *fuse.SwarmFS // need this to cleanup all the active mounts on node exit
  72. }
  73. type SwarmAPI struct {
  74. Api *api.Api
  75. Backend chequebook.Backend
  76. PrvKey *ecdsa.PrivateKey
  77. }
  78. func (self *Swarm) API() *SwarmAPI {
  79. return &SwarmAPI{
  80. Api: self.api,
  81. Backend: self.backend,
  82. PrvKey: self.privateKey,
  83. }
  84. }
  85. // creates a new swarm service instance
  86. // implements node.Service
  87. func NewSwarm(ctx *node.ServiceContext, backend chequebook.Backend, config *api.Config) (self *Swarm, err error) {
  88. if bytes.Equal(common.FromHex(config.PublicKey), storage.ZeroKey) {
  89. return nil, fmt.Errorf("empty public key")
  90. }
  91. if bytes.Equal(common.FromHex(config.BzzKey), storage.ZeroKey) {
  92. return nil, fmt.Errorf("empty bzz key")
  93. }
  94. self = &Swarm{
  95. config: config,
  96. swapEnabled: config.SwapEnabled,
  97. backend: backend,
  98. privateKey: config.Swap.PrivateKey(),
  99. corsString: config.Cors,
  100. }
  101. log.Debug(fmt.Sprintf("Setting up Swarm service components"))
  102. hash := storage.MakeHashFunc(config.ChunkerParams.Hash)
  103. self.lstore, err = storage.NewLocalStore(hash, config.StoreParams)
  104. if err != nil {
  105. return
  106. }
  107. // setup local store
  108. log.Debug(fmt.Sprintf("Set up local storage"))
  109. self.dbAccess = network.NewDbAccess(self.lstore)
  110. log.Debug(fmt.Sprintf("Set up local db access (iterator/counter)"))
  111. // set up the kademlia hive
  112. self.hive = network.NewHive(
  113. common.HexToHash(self.config.BzzKey), // key to hive (kademlia base address)
  114. config.HiveParams, // configuration parameters
  115. config.SwapEnabled, // SWAP enabled
  116. config.SyncEnabled, // syncronisation enabled
  117. )
  118. log.Debug(fmt.Sprintf("Set up swarm network with Kademlia hive"))
  119. // setup cloud storage backend
  120. self.cloud = network.NewForwarder(self.hive)
  121. log.Debug(fmt.Sprintf("-> set swarm forwarder as cloud storage backend"))
  122. // setup cloud storage internal access layer
  123. self.storage = storage.NewNetStore(hash, self.lstore, self.cloud, config.StoreParams)
  124. log.Debug(fmt.Sprintf("-> swarm net store shared access layer to Swarm Chunk Store"))
  125. // set up Depo (storage handler = cloud storage access layer for incoming remote requests)
  126. self.depo = network.NewDepo(hash, self.lstore, self.storage)
  127. log.Debug(fmt.Sprintf("-> REmote Access to CHunks"))
  128. // set up DPA, the cloud storage local access layer
  129. dpaChunkStore := storage.NewDpaChunkStore(self.lstore, self.storage)
  130. log.Debug(fmt.Sprintf("-> Local Access to Swarm"))
  131. // Swarm Hash Merklised Chunking for Arbitrary-length Document/File storage
  132. self.dpa = storage.NewDPA(dpaChunkStore, self.config.ChunkerParams)
  133. log.Debug(fmt.Sprintf("-> Content Store API"))
  134. if len(config.EnsAPIs) > 0 {
  135. opts := []api.MultiResolverOption{}
  136. for _, c := range config.EnsAPIs {
  137. tld, endpoint, addr := parseEnsAPIAddress(c)
  138. r, err := newEnsClient(endpoint, addr, config)
  139. if err != nil {
  140. return nil, err
  141. }
  142. opts = append(opts, api.MultiResolverOptionWithResolver(r, tld))
  143. }
  144. self.dns = api.NewMultiResolver(opts...)
  145. }
  146. self.api = api.NewApi(self.dpa, self.dns)
  147. // Manifests for Smart Hosting
  148. log.Debug(fmt.Sprintf("-> Web3 virtual server API"))
  149. self.sfs = fuse.NewSwarmFS(self.api)
  150. log.Debug("-> Initializing Fuse file system")
  151. return self, nil
  152. }
  153. // parseEnsAPIAddress parses string according to format
  154. // [tld:][contract-addr@]url and returns ENSClientConfig structure
  155. // with endpoint, contract address and TLD.
  156. func parseEnsAPIAddress(s string) (tld, endpoint string, addr common.Address) {
  157. isAllLetterString := func(s string) bool {
  158. for _, r := range s {
  159. if !unicode.IsLetter(r) {
  160. return false
  161. }
  162. }
  163. return true
  164. }
  165. endpoint = s
  166. if i := strings.Index(endpoint, ":"); i > 0 {
  167. if isAllLetterString(endpoint[:i]) && len(endpoint) > i+2 && endpoint[i+1:i+3] != "//" {
  168. tld = endpoint[:i]
  169. endpoint = endpoint[i+1:]
  170. }
  171. }
  172. if i := strings.Index(endpoint, "@"); i > 0 {
  173. addr = common.HexToAddress(endpoint[:i])
  174. endpoint = endpoint[i+1:]
  175. }
  176. return
  177. }
  178. // newEnsClient creates a new ENS client for that is a consumer of
  179. // a ENS API on a specific endpoint. It is used as a helper function
  180. // for creating multiple resolvers in NewSwarm function.
  181. func newEnsClient(endpoint string, addr common.Address, config *api.Config) (*ens.ENS, error) {
  182. log.Info("connecting to ENS API", "url", endpoint)
  183. client, err := rpc.Dial(endpoint)
  184. if err != nil {
  185. return nil, fmt.Errorf("error connecting to ENS API %s: %s", endpoint, err)
  186. }
  187. ensClient := ethclient.NewClient(client)
  188. ensRoot := config.EnsRoot
  189. if addr != (common.Address{}) {
  190. ensRoot = addr
  191. } else {
  192. a, err := detectEnsAddr(client)
  193. if err == nil {
  194. ensRoot = a
  195. } else {
  196. log.Warn(fmt.Sprintf("could not determine ENS contract address, using default %s", ensRoot), "err", err)
  197. }
  198. }
  199. transactOpts := bind.NewKeyedTransactor(config.Swap.PrivateKey())
  200. dns, err := ens.NewENS(transactOpts, ensRoot, ensClient)
  201. if err != nil {
  202. return nil, err
  203. }
  204. log.Debug(fmt.Sprintf("-> Swarm Domain Name Registrar %v @ address %v", endpoint, ensRoot.Hex()))
  205. return dns, err
  206. }
  207. // detectEnsAddr determines the ENS contract address by getting both the
  208. // version and genesis hash using the client and matching them to either
  209. // mainnet or testnet addresses
  210. func detectEnsAddr(client *rpc.Client) (common.Address, error) {
  211. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  212. defer cancel()
  213. var version string
  214. if err := client.CallContext(ctx, &version, "net_version"); err != nil {
  215. return common.Address{}, err
  216. }
  217. block, err := ethclient.NewClient(client).BlockByNumber(ctx, big.NewInt(0))
  218. if err != nil {
  219. return common.Address{}, err
  220. }
  221. switch {
  222. case version == "1" && block.Hash() == params.MainnetGenesisHash:
  223. log.Info("using Mainnet ENS contract address", "addr", ens.MainNetAddress)
  224. return ens.MainNetAddress, nil
  225. case version == "3" && block.Hash() == params.TestnetGenesisHash:
  226. log.Info("using Testnet ENS contract address", "addr", ens.TestNetAddress)
  227. return ens.TestNetAddress, nil
  228. default:
  229. return common.Address{}, fmt.Errorf("unknown version and genesis hash: %s %s", version, block.Hash())
  230. }
  231. }
  232. /*
  233. Start is called when the stack is started
  234. * starts the network kademlia hive peer management
  235. * (starts netStore level 0 api)
  236. * starts DPA level 1 api (chunking -> store/retrieve requests)
  237. * (starts level 2 api)
  238. * starts http proxy server
  239. * registers url scheme handlers for bzz, etc
  240. * TODO: start subservices like sword, swear, swarmdns
  241. */
  242. // implements the node.Service interface
  243. func (self *Swarm) Start(srv *p2p.Server) error {
  244. startTime = time.Now()
  245. connectPeer := func(url string) error {
  246. node, err := discover.ParseNode(url)
  247. if err != nil {
  248. return fmt.Errorf("invalid node URL: %v", err)
  249. }
  250. srv.AddPeer(node)
  251. return nil
  252. }
  253. // set chequebook
  254. if self.swapEnabled {
  255. ctx := context.Background() // The initial setup has no deadline.
  256. err := self.SetChequebook(ctx)
  257. if err != nil {
  258. return fmt.Errorf("Unable to set chequebook for SWAP: %v", err)
  259. }
  260. log.Debug(fmt.Sprintf("-> cheque book for SWAP: %v", self.config.Swap.Chequebook()))
  261. } else {
  262. log.Debug(fmt.Sprintf("SWAP disabled: no cheque book set"))
  263. }
  264. log.Warn(fmt.Sprintf("Starting Swarm service"))
  265. self.hive.Start(
  266. discover.PubkeyID(&srv.PrivateKey.PublicKey),
  267. func() string { return srv.ListenAddr },
  268. connectPeer,
  269. )
  270. log.Info(fmt.Sprintf("Swarm network started on bzz address: %v", self.hive.Addr()))
  271. self.dpa.Start()
  272. log.Debug(fmt.Sprintf("Swarm DPA started"))
  273. // start swarm http proxy server
  274. if self.config.Port != "" {
  275. addr := net.JoinHostPort(self.config.ListenAddr, self.config.Port)
  276. go httpapi.StartHttpServer(self.api, &httpapi.ServerConfig{
  277. Addr: addr,
  278. CorsString: self.corsString,
  279. })
  280. log.Info(fmt.Sprintf("Swarm http proxy started on %v", addr))
  281. if self.corsString != "" {
  282. log.Debug(fmt.Sprintf("Swarm http proxy started with corsdomain: %v", self.corsString))
  283. }
  284. }
  285. self.periodicallyUpdateGauges()
  286. startCounter.Inc(1)
  287. return nil
  288. }
  289. func (self *Swarm) periodicallyUpdateGauges() {
  290. ticker := time.NewTicker(updateGaugesPeriod)
  291. go func() {
  292. for range ticker.C {
  293. self.updateGauges()
  294. }
  295. }()
  296. }
  297. func (self *Swarm) updateGauges() {
  298. dbSizeGauge.Update(int64(self.lstore.DbCounter()))
  299. cacheSizeGauge.Update(int64(self.lstore.CacheCounter()))
  300. uptimeGauge.Update(time.Since(startTime).Nanoseconds())
  301. }
  302. // implements the node.Service interface
  303. // stops all component services.
  304. func (self *Swarm) Stop() error {
  305. self.dpa.Stop()
  306. err := self.hive.Stop()
  307. if ch := self.config.Swap.Chequebook(); ch != nil {
  308. ch.Stop()
  309. ch.Save()
  310. }
  311. if self.lstore != nil {
  312. self.lstore.DbStore.Close()
  313. }
  314. self.sfs.Stop()
  315. stopCounter.Inc(1)
  316. return err
  317. }
  318. // implements the node.Service interface
  319. func (self *Swarm) Protocols() []p2p.Protocol {
  320. proto, err := network.Bzz(self.depo, self.backend, self.hive, self.dbAccess, self.config.Swap, self.config.SyncParams, self.config.NetworkId)
  321. if err != nil {
  322. return nil
  323. }
  324. return []p2p.Protocol{proto}
  325. }
  326. // implements node.Service
  327. // Apis returns the RPC Api descriptors the Swarm implementation offers
  328. func (self *Swarm) APIs() []rpc.API {
  329. return []rpc.API{
  330. // public APIs
  331. {
  332. Namespace: "bzz",
  333. Version: "0.1",
  334. Service: &Info{self.config, chequebook.ContractParams},
  335. Public: true,
  336. },
  337. // admin APIs
  338. {
  339. Namespace: "bzz",
  340. Version: "0.1",
  341. Service: api.NewControl(self.api, self.hive),
  342. Public: false,
  343. },
  344. {
  345. Namespace: "chequebook",
  346. Version: chequebook.Version,
  347. Service: chequebook.NewApi(self.config.Swap.Chequebook),
  348. Public: false,
  349. },
  350. {
  351. Namespace: "swarmfs",
  352. Version: fuse.Swarmfs_Version,
  353. Service: self.sfs,
  354. Public: false,
  355. },
  356. // storage APIs
  357. // DEPRECATED: Use the HTTP API instead
  358. {
  359. Namespace: "bzz",
  360. Version: "0.1",
  361. Service: api.NewStorage(self.api),
  362. Public: true,
  363. },
  364. {
  365. Namespace: "bzz",
  366. Version: "0.1",
  367. Service: api.NewFileSystem(self.api),
  368. Public: false,
  369. },
  370. // {Namespace, Version, api.NewAdmin(self), false},
  371. }
  372. }
  373. func (self *Swarm) Api() *api.Api {
  374. return self.api
  375. }
  376. // SetChequebook ensures that the local checquebook is set up on chain.
  377. func (self *Swarm) SetChequebook(ctx context.Context) error {
  378. err := self.config.Swap.SetChequebook(ctx, self.backend, self.config.Path)
  379. if err != nil {
  380. return err
  381. }
  382. log.Info(fmt.Sprintf("new chequebook set (%v): saving config file, resetting all connections in the hive", self.config.Swap.Contract.Hex()))
  383. self.hive.DropAll()
  384. return nil
  385. }
  386. // Local swarm without netStore
  387. func NewLocalSwarm(datadir, port string) (self *Swarm, err error) {
  388. prvKey, err := crypto.GenerateKey()
  389. if err != nil {
  390. return
  391. }
  392. config := api.NewDefaultConfig()
  393. config.Path = datadir
  394. config.Init(prvKey)
  395. config.Port = port
  396. dpa, err := storage.NewLocalDPA(datadir)
  397. if err != nil {
  398. return
  399. }
  400. self = &Swarm{
  401. api: api.NewApi(dpa, nil),
  402. config: config,
  403. }
  404. return
  405. }
  406. // serialisable info about swarm
  407. type Info struct {
  408. *api.Config
  409. *chequebook.Params
  410. }
  411. func (self *Info) Info() *Info {
  412. return self
  413. }