swarm.go 10 KB

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