swarm.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. "net"
  23. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/contracts/chequebook"
  26. "github.com/ethereum/go-ethereum/contracts/ens"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/ethclient"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/node"
  31. "github.com/ethereum/go-ethereum/p2p"
  32. "github.com/ethereum/go-ethereum/p2p/discover"
  33. "github.com/ethereum/go-ethereum/rpc"
  34. "github.com/ethereum/go-ethereum/swarm/api"
  35. httpapi "github.com/ethereum/go-ethereum/swarm/api/http"
  36. "github.com/ethereum/go-ethereum/swarm/fuse"
  37. "github.com/ethereum/go-ethereum/swarm/network"
  38. "github.com/ethereum/go-ethereum/swarm/storage"
  39. )
  40. // the swarm stack
  41. type Swarm struct {
  42. config *api.Config // swarm configuration
  43. api *api.Api // high level api layer (fs/manifest)
  44. dns api.Resolver // DNS registrar
  45. dbAccess *network.DbAccess // access to local chunk db iterator and storage counter
  46. storage storage.ChunkStore // internal access to storage, common interface to cloud storage backends
  47. dpa *storage.DPA // distributed preimage archive, the local API to the storage with document level storage/retrieval support
  48. depo network.StorageHandler // remote request handler, interface between bzz protocol and the storage
  49. cloud storage.CloudStore // procurement, cloud storage backend (can multi-cloud)
  50. hive *network.Hive // the logistic manager
  51. backend chequebook.Backend // simple blockchain Backend
  52. privateKey *ecdsa.PrivateKey
  53. corsString string
  54. swapEnabled bool
  55. lstore *storage.LocalStore // local store, needs to store for releasing resources after node stopped
  56. sfs *fuse.SwarmFS // need this to cleanup all the active mounts on node exit
  57. }
  58. type SwarmAPI struct {
  59. Api *api.Api
  60. Backend chequebook.Backend
  61. PrvKey *ecdsa.PrivateKey
  62. }
  63. func (self *Swarm) API() *SwarmAPI {
  64. return &SwarmAPI{
  65. Api: self.api,
  66. Backend: self.backend,
  67. PrvKey: self.privateKey,
  68. }
  69. }
  70. // creates a new swarm service instance
  71. // implements node.Service
  72. func NewSwarm(ctx *node.ServiceContext, backend chequebook.Backend, ensClient *ethclient.Client, config *api.Config, swapEnabled, syncEnabled bool, cors string) (self *Swarm, err error) {
  73. if bytes.Equal(common.FromHex(config.PublicKey), storage.ZeroKey) {
  74. return nil, fmt.Errorf("empty public key")
  75. }
  76. if bytes.Equal(common.FromHex(config.BzzKey), storage.ZeroKey) {
  77. return nil, fmt.Errorf("empty bzz key")
  78. }
  79. self = &Swarm{
  80. config: config,
  81. swapEnabled: swapEnabled,
  82. backend: backend,
  83. privateKey: config.Swap.PrivateKey(),
  84. corsString: cors,
  85. }
  86. log.Debug(fmt.Sprintf("Setting up Swarm service components"))
  87. hash := storage.MakeHashFunc(config.ChunkerParams.Hash)
  88. self.lstore, err = storage.NewLocalStore(hash, config.StoreParams)
  89. if err != nil {
  90. return
  91. }
  92. // setup local store
  93. log.Debug(fmt.Sprintf("Set up local storage"))
  94. self.dbAccess = network.NewDbAccess(self.lstore)
  95. log.Debug(fmt.Sprintf("Set up local db access (iterator/counter)"))
  96. // set up the kademlia hive
  97. self.hive = network.NewHive(
  98. common.HexToHash(self.config.BzzKey), // key to hive (kademlia base address)
  99. config.HiveParams, // configuration parameters
  100. swapEnabled, // SWAP enabled
  101. syncEnabled, // syncronisation enabled
  102. )
  103. log.Debug(fmt.Sprintf("Set up swarm network with Kademlia hive"))
  104. // setup cloud storage backend
  105. self.cloud = network.NewForwarder(self.hive)
  106. log.Debug(fmt.Sprintf("-> set swarm forwarder as cloud storage backend"))
  107. // setup cloud storage internal access layer
  108. self.storage = storage.NewNetStore(hash, self.lstore, self.cloud, config.StoreParams)
  109. log.Debug(fmt.Sprintf("-> swarm net store shared access layer to Swarm Chunk Store"))
  110. // set up Depo (storage handler = cloud storage access layer for incoming remote requests)
  111. self.depo = network.NewDepo(hash, self.lstore, self.storage)
  112. log.Debug(fmt.Sprintf("-> REmote Access to CHunks"))
  113. // set up DPA, the cloud storage local access layer
  114. dpaChunkStore := storage.NewDpaChunkStore(self.lstore, self.storage)
  115. log.Debug(fmt.Sprintf("-> Local Access to Swarm"))
  116. // Swarm Hash Merklised Chunking for Arbitrary-length Document/File storage
  117. self.dpa = storage.NewDPA(dpaChunkStore, self.config.ChunkerParams)
  118. log.Debug(fmt.Sprintf("-> Content Store API"))
  119. // set up high level api
  120. transactOpts := bind.NewKeyedTransactor(self.privateKey)
  121. if ensClient == nil {
  122. log.Warn("No ENS, please specify non-empty --ens-api to use domain name resolution")
  123. } else {
  124. self.dns, err = ens.NewENS(transactOpts, config.EnsRoot, ensClient)
  125. if err != nil {
  126. return nil, err
  127. }
  128. }
  129. log.Debug(fmt.Sprintf("-> Swarm Domain Name Registrar @ address %v", config.EnsRoot.Hex()))
  130. self.api = api.NewApi(self.dpa, self.dns)
  131. // Manifests for Smart Hosting
  132. log.Debug(fmt.Sprintf("-> Web3 virtual server API"))
  133. self.sfs = fuse.NewSwarmFS(self.api)
  134. log.Debug("-> Initializing Fuse file system")
  135. return self, nil
  136. }
  137. /*
  138. Start is called when the stack is started
  139. * starts the network kademlia hive peer management
  140. * (starts netStore level 0 api)
  141. * starts DPA level 1 api (chunking -> store/retrieve requests)
  142. * (starts level 2 api)
  143. * starts http proxy server
  144. * registers url scheme handlers for bzz, etc
  145. * TODO: start subservices like sword, swear, swarmdns
  146. */
  147. // implements the node.Service interface
  148. func (self *Swarm) Start(srv *p2p.Server) error {
  149. connectPeer := func(url string) error {
  150. node, err := discover.ParseNode(url)
  151. if err != nil {
  152. return fmt.Errorf("invalid node URL: %v", err)
  153. }
  154. srv.AddPeer(node)
  155. return nil
  156. }
  157. // set chequebook
  158. if self.swapEnabled {
  159. ctx := context.Background() // The initial setup has no deadline.
  160. err := self.SetChequebook(ctx)
  161. if err != nil {
  162. return fmt.Errorf("Unable to set chequebook for SWAP: %v", err)
  163. }
  164. log.Debug(fmt.Sprintf("-> cheque book for SWAP: %v", self.config.Swap.Chequebook()))
  165. } else {
  166. log.Debug(fmt.Sprintf("SWAP disabled: no cheque book set"))
  167. }
  168. log.Warn(fmt.Sprintf("Starting Swarm service"))
  169. self.hive.Start(
  170. discover.PubkeyID(&srv.PrivateKey.PublicKey),
  171. func() string { return srv.ListenAddr },
  172. connectPeer,
  173. )
  174. log.Info(fmt.Sprintf("Swarm network started on bzz address: %v", self.hive.Addr()))
  175. self.dpa.Start()
  176. log.Debug(fmt.Sprintf("Swarm DPA started"))
  177. // start swarm http proxy server
  178. if self.config.Port != "" {
  179. addr := net.JoinHostPort(self.config.ListenAddr, self.config.Port)
  180. go httpapi.StartHttpServer(self.api, &httpapi.ServerConfig{
  181. Addr: addr,
  182. CorsString: self.corsString,
  183. })
  184. log.Info(fmt.Sprintf("Swarm http proxy started on %v", addr))
  185. if self.corsString != "" {
  186. log.Debug(fmt.Sprintf("Swarm http proxy started with corsdomain: %v", self.corsString))
  187. }
  188. }
  189. return nil
  190. }
  191. // implements the node.Service interface
  192. // stops all component services.
  193. func (self *Swarm) Stop() error {
  194. self.dpa.Stop()
  195. err := self.hive.Stop()
  196. if ch := self.config.Swap.Chequebook(); ch != nil {
  197. ch.Stop()
  198. ch.Save()
  199. }
  200. if self.lstore != nil {
  201. self.lstore.DbStore.Close()
  202. }
  203. self.sfs.Stop()
  204. return err
  205. }
  206. // implements the node.Service interface
  207. func (self *Swarm) Protocols() []p2p.Protocol {
  208. proto, err := network.Bzz(self.depo, self.backend, self.hive, self.dbAccess, self.config.Swap, self.config.SyncParams, self.config.NetworkId)
  209. if err != nil {
  210. return nil
  211. }
  212. return []p2p.Protocol{proto}
  213. }
  214. // implements node.Service
  215. // Apis returns the RPC Api descriptors the Swarm implementation offers
  216. func (self *Swarm) APIs() []rpc.API {
  217. return []rpc.API{
  218. // public APIs
  219. {
  220. Namespace: "bzz",
  221. Version: "0.1",
  222. Service: &Info{self.config, chequebook.ContractParams},
  223. Public: true,
  224. },
  225. // admin APIs
  226. {
  227. Namespace: "bzz",
  228. Version: "0.1",
  229. Service: api.NewControl(self.api, self.hive),
  230. Public: false,
  231. },
  232. {
  233. Namespace: "chequebook",
  234. Version: chequebook.Version,
  235. Service: chequebook.NewApi(self.config.Swap.Chequebook),
  236. Public: false,
  237. },
  238. {
  239. Namespace: "swarmfs",
  240. Version: fuse.Swarmfs_Version,
  241. Service: self.sfs,
  242. Public: false,
  243. },
  244. // storage APIs
  245. // DEPRECATED: Use the HTTP API instead
  246. {
  247. Namespace: "bzz",
  248. Version: "0.1",
  249. Service: api.NewStorage(self.api),
  250. Public: true,
  251. },
  252. {
  253. Namespace: "bzz",
  254. Version: "0.1",
  255. Service: api.NewFileSystem(self.api),
  256. Public: false,
  257. },
  258. // {Namespace, Version, api.NewAdmin(self), false},
  259. }
  260. }
  261. func (self *Swarm) Api() *api.Api {
  262. return self.api
  263. }
  264. // SetChequebook ensures that the local checquebook is set up on chain.
  265. func (self *Swarm) SetChequebook(ctx context.Context) error {
  266. err := self.config.Swap.SetChequebook(ctx, self.backend, self.config.Path)
  267. if err != nil {
  268. return err
  269. }
  270. log.Info(fmt.Sprintf("new chequebook set (%v): saving config file, resetting all connections in the hive", self.config.Swap.Contract.Hex()))
  271. self.hive.DropAll()
  272. return nil
  273. }
  274. // Local swarm without netStore
  275. func NewLocalSwarm(datadir, port string) (self *Swarm, err error) {
  276. prvKey, err := crypto.GenerateKey()
  277. if err != nil {
  278. return
  279. }
  280. config := api.NewDefaultConfig()
  281. config.Path = datadir
  282. config.Init(prvKey)
  283. config.Port = port
  284. dpa, err := storage.NewLocalDPA(datadir)
  285. if err != nil {
  286. return
  287. }
  288. self = &Swarm{
  289. api: api.NewApi(dpa, nil),
  290. config: config,
  291. }
  292. return
  293. }
  294. // serialisable info about swarm
  295. type Info struct {
  296. *api.Config
  297. *chequebook.Params
  298. }
  299. func (self *Info) Info() *Info {
  300. return self
  301. }