swarm.go 9.4 KB

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