swarm.go 10 KB

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