swarm.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. "math/big"
  23. "net"
  24. "strings"
  25. "time"
  26. "unicode"
  27. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/contracts/chequebook"
  30. "github.com/ethereum/go-ethereum/contracts/ens"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/ethclient"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/node"
  35. "github.com/ethereum/go-ethereum/p2p"
  36. "github.com/ethereum/go-ethereum/p2p/discover"
  37. "github.com/ethereum/go-ethereum/params"
  38. "github.com/ethereum/go-ethereum/rpc"
  39. "github.com/ethereum/go-ethereum/swarm/api"
  40. httpapi "github.com/ethereum/go-ethereum/swarm/api/http"
  41. "github.com/ethereum/go-ethereum/swarm/fuse"
  42. "github.com/ethereum/go-ethereum/swarm/network"
  43. "github.com/ethereum/go-ethereum/swarm/storage"
  44. )
  45. // the swarm stack
  46. type Swarm struct {
  47. config *api.Config // swarm configuration
  48. api *api.Api // high level api layer (fs/manifest)
  49. dns api.Resolver // DNS registrar
  50. dbAccess *network.DbAccess // access to local chunk db iterator and storage counter
  51. storage storage.ChunkStore // internal access to storage, common interface to cloud storage backends
  52. dpa *storage.DPA // distributed preimage archive, the local API to the storage with document level storage/retrieval support
  53. depo network.StorageHandler // remote request handler, interface between bzz protocol and the storage
  54. cloud storage.CloudStore // procurement, cloud storage backend (can multi-cloud)
  55. hive *network.Hive // the logistic manager
  56. backend chequebook.Backend // simple blockchain Backend
  57. privateKey *ecdsa.PrivateKey
  58. corsString string
  59. swapEnabled bool
  60. lstore *storage.LocalStore // local store, needs to store for releasing resources after node stopped
  61. sfs *fuse.SwarmFS // need this to cleanup all the active mounts on node exit
  62. }
  63. type SwarmAPI struct {
  64. Api *api.Api
  65. Backend chequebook.Backend
  66. PrvKey *ecdsa.PrivateKey
  67. }
  68. func (self *Swarm) API() *SwarmAPI {
  69. return &SwarmAPI{
  70. Api: self.api,
  71. Backend: self.backend,
  72. PrvKey: self.privateKey,
  73. }
  74. }
  75. // creates a new swarm service instance
  76. // implements node.Service
  77. func NewSwarm(ctx *node.ServiceContext, backend chequebook.Backend, config *api.Config) (self *Swarm, err error) {
  78. if bytes.Equal(common.FromHex(config.PublicKey), storage.ZeroKey) {
  79. return nil, fmt.Errorf("empty public key")
  80. }
  81. if bytes.Equal(common.FromHex(config.BzzKey), storage.ZeroKey) {
  82. return nil, fmt.Errorf("empty bzz key")
  83. }
  84. self = &Swarm{
  85. config: config,
  86. swapEnabled: config.SwapEnabled,
  87. backend: backend,
  88. privateKey: config.Swap.PrivateKey(),
  89. corsString: config.Cors,
  90. }
  91. log.Debug(fmt.Sprintf("Setting up Swarm service components"))
  92. hash := storage.MakeHashFunc(config.ChunkerParams.Hash)
  93. self.lstore, err = storage.NewLocalStore(hash, config.StoreParams)
  94. if err != nil {
  95. return
  96. }
  97. // setup local store
  98. log.Debug(fmt.Sprintf("Set up local storage"))
  99. self.dbAccess = network.NewDbAccess(self.lstore)
  100. log.Debug(fmt.Sprintf("Set up local db access (iterator/counter)"))
  101. // set up the kademlia hive
  102. self.hive = network.NewHive(
  103. common.HexToHash(self.config.BzzKey), // key to hive (kademlia base address)
  104. config.HiveParams, // configuration parameters
  105. config.SwapEnabled, // SWAP enabled
  106. config.SyncEnabled, // syncronisation enabled
  107. )
  108. log.Debug(fmt.Sprintf("Set up swarm network with Kademlia hive"))
  109. // setup cloud storage backend
  110. self.cloud = network.NewForwarder(self.hive)
  111. log.Debug(fmt.Sprintf("-> set swarm forwarder as cloud storage backend"))
  112. // setup cloud storage internal access layer
  113. self.storage = storage.NewNetStore(hash, self.lstore, self.cloud, config.StoreParams)
  114. log.Debug(fmt.Sprintf("-> swarm net store shared access layer to Swarm Chunk Store"))
  115. // set up Depo (storage handler = cloud storage access layer for incoming remote requests)
  116. self.depo = network.NewDepo(hash, self.lstore, self.storage)
  117. log.Debug(fmt.Sprintf("-> REmote Access to CHunks"))
  118. // set up DPA, the cloud storage local access layer
  119. dpaChunkStore := storage.NewDpaChunkStore(self.lstore, self.storage)
  120. log.Debug(fmt.Sprintf("-> Local Access to Swarm"))
  121. // Swarm Hash Merklised Chunking for Arbitrary-length Document/File storage
  122. self.dpa = storage.NewDPA(dpaChunkStore, self.config.ChunkerParams)
  123. log.Debug(fmt.Sprintf("-> Content Store API"))
  124. if len(config.EnsAPIs) > 0 {
  125. opts := []api.MultiResolverOption{}
  126. for _, c := range config.EnsAPIs {
  127. tld, endpoint, addr := parseEnsAPIAddress(c)
  128. r, err := newEnsClient(endpoint, addr, config)
  129. if err != nil {
  130. return nil, err
  131. }
  132. opts = append(opts, api.MultiResolverOptionWithResolver(r, tld))
  133. }
  134. self.dns = api.NewMultiResolver(opts...)
  135. }
  136. self.api = api.NewApi(self.dpa, self.dns)
  137. // Manifests for Smart Hosting
  138. log.Debug(fmt.Sprintf("-> Web3 virtual server API"))
  139. self.sfs = fuse.NewSwarmFS(self.api)
  140. log.Debug("-> Initializing Fuse file system")
  141. return self, nil
  142. }
  143. // parseEnsAPIAddress parses string according to format
  144. // [tld:][contract-addr@]url and returns ENSClientConfig structure
  145. // with endpoint, contract address and TLD.
  146. func parseEnsAPIAddress(s string) (tld, endpoint string, addr common.Address) {
  147. isAllLetterString := func(s string) bool {
  148. for _, r := range s {
  149. if !unicode.IsLetter(r) {
  150. return false
  151. }
  152. }
  153. return true
  154. }
  155. endpoint = s
  156. if i := strings.Index(endpoint, ":"); i > 0 {
  157. if isAllLetterString(endpoint[:i]) && len(endpoint) > i+2 && endpoint[i+1:i+3] != "//" {
  158. tld = endpoint[:i]
  159. endpoint = endpoint[i+1:]
  160. }
  161. }
  162. if i := strings.Index(endpoint, "@"); i > 0 {
  163. addr = common.HexToAddress(endpoint[:i])
  164. endpoint = endpoint[i+1:]
  165. }
  166. return
  167. }
  168. // newEnsClient creates a new ENS client for that is a consumer of
  169. // a ENS API on a specific endpoint. It is used as a helper function
  170. // for creating multiple resolvers in NewSwarm function.
  171. func newEnsClient(endpoint string, addr common.Address, config *api.Config) (*ens.ENS, error) {
  172. log.Info("connecting to ENS API", "url", endpoint)
  173. client, err := rpc.Dial(endpoint)
  174. if err != nil {
  175. return nil, fmt.Errorf("error connecting to ENS API %s: %s", endpoint, err)
  176. }
  177. ensClient := ethclient.NewClient(client)
  178. ensRoot := config.EnsRoot
  179. if addr != (common.Address{}) {
  180. ensRoot = addr
  181. } else {
  182. a, err := detectEnsAddr(client)
  183. if err == nil {
  184. ensRoot = a
  185. } else {
  186. log.Warn(fmt.Sprintf("could not determine ENS contract address, using default %s", ensRoot), "err", err)
  187. }
  188. }
  189. transactOpts := bind.NewKeyedTransactor(config.Swap.PrivateKey())
  190. dns, err := ens.NewENS(transactOpts, ensRoot, ensClient)
  191. if err != nil {
  192. return nil, err
  193. }
  194. log.Debug(fmt.Sprintf("-> Swarm Domain Name Registrar %v @ address %v", endpoint, ensRoot.Hex()))
  195. return dns, err
  196. }
  197. // detectEnsAddr determines the ENS contract address by getting both the
  198. // version and genesis hash using the client and matching them to either
  199. // mainnet or testnet addresses
  200. func detectEnsAddr(client *rpc.Client) (common.Address, error) {
  201. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  202. defer cancel()
  203. var version string
  204. if err := client.CallContext(ctx, &version, "net_version"); err != nil {
  205. return common.Address{}, err
  206. }
  207. block, err := ethclient.NewClient(client).BlockByNumber(ctx, big.NewInt(0))
  208. if err != nil {
  209. return common.Address{}, err
  210. }
  211. switch {
  212. case version == "1" && block.Hash() == params.MainnetGenesisHash:
  213. log.Info("using Mainnet ENS contract address", "addr", ens.MainNetAddress)
  214. return ens.MainNetAddress, nil
  215. case version == "3" && block.Hash() == params.TestnetGenesisHash:
  216. log.Info("using Testnet ENS contract address", "addr", ens.TestNetAddress)
  217. return ens.TestNetAddress, nil
  218. default:
  219. return common.Address{}, fmt.Errorf("unknown version and genesis hash: %s %s", version, block.Hash())
  220. }
  221. }
  222. /*
  223. Start is called when the stack is started
  224. * starts the network kademlia hive peer management
  225. * (starts netStore level 0 api)
  226. * starts DPA level 1 api (chunking -> store/retrieve requests)
  227. * (starts level 2 api)
  228. * starts http proxy server
  229. * registers url scheme handlers for bzz, etc
  230. * TODO: start subservices like sword, swear, swarmdns
  231. */
  232. // implements the node.Service interface
  233. func (self *Swarm) Start(srv *p2p.Server) error {
  234. connectPeer := func(url string) error {
  235. node, err := discover.ParseNode(url)
  236. if err != nil {
  237. return fmt.Errorf("invalid node URL: %v", err)
  238. }
  239. srv.AddPeer(node)
  240. return nil
  241. }
  242. // set chequebook
  243. if self.swapEnabled {
  244. ctx := context.Background() // The initial setup has no deadline.
  245. err := self.SetChequebook(ctx)
  246. if err != nil {
  247. return fmt.Errorf("Unable to set chequebook for SWAP: %v", err)
  248. }
  249. log.Debug(fmt.Sprintf("-> cheque book for SWAP: %v", self.config.Swap.Chequebook()))
  250. } else {
  251. log.Debug(fmt.Sprintf("SWAP disabled: no cheque book set"))
  252. }
  253. log.Warn(fmt.Sprintf("Starting Swarm service"))
  254. self.hive.Start(
  255. discover.PubkeyID(&srv.PrivateKey.PublicKey),
  256. func() string { return srv.ListenAddr },
  257. connectPeer,
  258. )
  259. log.Info(fmt.Sprintf("Swarm network started on bzz address: %v", self.hive.Addr()))
  260. self.dpa.Start()
  261. log.Debug(fmt.Sprintf("Swarm DPA started"))
  262. // start swarm http proxy server
  263. if self.config.Port != "" {
  264. addr := net.JoinHostPort(self.config.ListenAddr, self.config.Port)
  265. go httpapi.StartHttpServer(self.api, &httpapi.ServerConfig{
  266. Addr: addr,
  267. CorsString: self.corsString,
  268. })
  269. log.Info(fmt.Sprintf("Swarm http proxy started on %v", addr))
  270. if self.corsString != "" {
  271. log.Debug(fmt.Sprintf("Swarm http proxy started with corsdomain: %v", self.corsString))
  272. }
  273. }
  274. return nil
  275. }
  276. // implements the node.Service interface
  277. // stops all component services.
  278. func (self *Swarm) Stop() error {
  279. self.dpa.Stop()
  280. err := self.hive.Stop()
  281. if ch := self.config.Swap.Chequebook(); ch != nil {
  282. ch.Stop()
  283. ch.Save()
  284. }
  285. if self.lstore != nil {
  286. self.lstore.DbStore.Close()
  287. }
  288. self.sfs.Stop()
  289. return err
  290. }
  291. // implements the node.Service interface
  292. func (self *Swarm) Protocols() []p2p.Protocol {
  293. proto, err := network.Bzz(self.depo, self.backend, self.hive, self.dbAccess, self.config.Swap, self.config.SyncParams, self.config.NetworkId)
  294. if err != nil {
  295. return nil
  296. }
  297. return []p2p.Protocol{proto}
  298. }
  299. // implements node.Service
  300. // Apis returns the RPC Api descriptors the Swarm implementation offers
  301. func (self *Swarm) APIs() []rpc.API {
  302. return []rpc.API{
  303. // public APIs
  304. {
  305. Namespace: "bzz",
  306. Version: "0.1",
  307. Service: &Info{self.config, chequebook.ContractParams},
  308. Public: true,
  309. },
  310. // admin APIs
  311. {
  312. Namespace: "bzz",
  313. Version: "0.1",
  314. Service: api.NewControl(self.api, self.hive),
  315. Public: false,
  316. },
  317. {
  318. Namespace: "chequebook",
  319. Version: chequebook.Version,
  320. Service: chequebook.NewApi(self.config.Swap.Chequebook),
  321. Public: false,
  322. },
  323. {
  324. Namespace: "swarmfs",
  325. Version: fuse.Swarmfs_Version,
  326. Service: self.sfs,
  327. Public: false,
  328. },
  329. // storage APIs
  330. // DEPRECATED: Use the HTTP API instead
  331. {
  332. Namespace: "bzz",
  333. Version: "0.1",
  334. Service: api.NewStorage(self.api),
  335. Public: true,
  336. },
  337. {
  338. Namespace: "bzz",
  339. Version: "0.1",
  340. Service: api.NewFileSystem(self.api),
  341. Public: false,
  342. },
  343. // {Namespace, Version, api.NewAdmin(self), false},
  344. }
  345. }
  346. func (self *Swarm) Api() *api.Api {
  347. return self.api
  348. }
  349. // SetChequebook ensures that the local checquebook is set up on chain.
  350. func (self *Swarm) SetChequebook(ctx context.Context) error {
  351. err := self.config.Swap.SetChequebook(ctx, self.backend, self.config.Path)
  352. if err != nil {
  353. return err
  354. }
  355. log.Info(fmt.Sprintf("new chequebook set (%v): saving config file, resetting all connections in the hive", self.config.Swap.Contract.Hex()))
  356. self.hive.DropAll()
  357. return nil
  358. }
  359. // Local swarm without netStore
  360. func NewLocalSwarm(datadir, port string) (self *Swarm, err error) {
  361. prvKey, err := crypto.GenerateKey()
  362. if err != nil {
  363. return
  364. }
  365. config := api.NewDefaultConfig()
  366. config.Path = datadir
  367. config.Init(prvKey)
  368. config.Port = port
  369. dpa, err := storage.NewLocalDPA(datadir)
  370. if err != nil {
  371. return
  372. }
  373. self = &Swarm{
  374. api: api.NewApi(dpa, nil),
  375. config: config,
  376. }
  377. return
  378. }
  379. // serialisable info about swarm
  380. type Info struct {
  381. *api.Config
  382. *chequebook.Params
  383. }
  384. func (self *Info) Info() *Info {
  385. return self
  386. }