swarm.go 9.7 KB

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