main.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU 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. // go-ethereum 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 General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "context"
  19. "crypto/ecdsa"
  20. "fmt"
  21. "io/ioutil"
  22. "math/big"
  23. "os"
  24. "os/signal"
  25. "runtime"
  26. "strconv"
  27. "strings"
  28. "syscall"
  29. "time"
  30. "github.com/ethereum/go-ethereum/accounts"
  31. "github.com/ethereum/go-ethereum/accounts/keystore"
  32. "github.com/ethereum/go-ethereum/cmd/utils"
  33. "github.com/ethereum/go-ethereum/common"
  34. "github.com/ethereum/go-ethereum/console"
  35. "github.com/ethereum/go-ethereum/contracts/ens"
  36. "github.com/ethereum/go-ethereum/crypto"
  37. "github.com/ethereum/go-ethereum/ethclient"
  38. "github.com/ethereum/go-ethereum/internal/debug"
  39. "github.com/ethereum/go-ethereum/log"
  40. "github.com/ethereum/go-ethereum/node"
  41. "github.com/ethereum/go-ethereum/p2p"
  42. "github.com/ethereum/go-ethereum/p2p/discover"
  43. "github.com/ethereum/go-ethereum/params"
  44. "github.com/ethereum/go-ethereum/rpc"
  45. "github.com/ethereum/go-ethereum/swarm"
  46. bzzapi "github.com/ethereum/go-ethereum/swarm/api"
  47. "gopkg.in/urfave/cli.v1"
  48. )
  49. const clientIdentifier = "swarm"
  50. var (
  51. gitCommit string // Git SHA1 commit hash of the release (set via linker flags)
  52. testbetBootNodes = []string{
  53. "enode://ec8ae764f7cb0417bdfb009b9d0f18ab3818a3a4e8e7c67dd5f18971a93510a2e6f43cd0b69a27e439a9629457ea804104f37c85e41eed057d3faabbf7744cdf@13.74.157.139:30429",
  54. "enode://c2e1fceb3bf3be19dff71eec6cccf19f2dbf7567ee017d130240c670be8594bc9163353ca55dd8df7a4f161dd94b36d0615c17418b5a3cdcbb4e9d99dfa4de37@13.74.157.139:30430",
  55. "enode://fe29b82319b734ce1ec68b84657d57145fee237387e63273989d354486731e59f78858e452ef800a020559da22dcca759536e6aa5517c53930d29ce0b1029286@13.74.157.139:30431",
  56. "enode://1d7187e7bde45cf0bee489ce9852dd6d1a0d9aa67a33a6b8e6db8a4fbc6fcfa6f0f1a5419343671521b863b187d1c73bad3603bae66421d157ffef357669ddb8@13.74.157.139:30432",
  57. "enode://0e4cba800f7b1ee73673afa6a4acead4018f0149d2e3216be3f133318fd165b324cd71b81fbe1e80deac8dbf56e57a49db7be67f8b9bc81bd2b7ee496434fb5d@13.74.157.139:30433",
  58. }
  59. )
  60. var (
  61. ChequebookAddrFlag = cli.StringFlag{
  62. Name: "chequebook",
  63. Usage: "chequebook contract address",
  64. }
  65. SwarmAccountFlag = cli.StringFlag{
  66. Name: "bzzaccount",
  67. Usage: "Swarm account key file",
  68. }
  69. SwarmListenAddrFlag = cli.StringFlag{
  70. Name: "httpaddr",
  71. Usage: "Swarm HTTP API listening interface",
  72. }
  73. SwarmPortFlag = cli.StringFlag{
  74. Name: "bzzport",
  75. Usage: "Swarm local http api port",
  76. }
  77. SwarmNetworkIdFlag = cli.IntFlag{
  78. Name: "bzznetworkid",
  79. Usage: "Network identifier (integer, default 3=swarm testnet)",
  80. }
  81. SwarmConfigPathFlag = cli.StringFlag{
  82. Name: "bzzconfig",
  83. Usage: "Swarm config file path (datadir/bzz)",
  84. }
  85. SwarmSwapEnabledFlag = cli.BoolFlag{
  86. Name: "swap",
  87. Usage: "Swarm SWAP enabled (default false)",
  88. }
  89. SwarmSwapAPIFlag = cli.StringFlag{
  90. Name: "swap-api",
  91. Usage: "URL of the Ethereum API provider to use to settle SWAP payments",
  92. }
  93. SwarmSyncEnabledFlag = cli.BoolTFlag{
  94. Name: "sync",
  95. Usage: "Swarm Syncing enabled (default true)",
  96. }
  97. EnsAPIFlag = cli.StringFlag{
  98. Name: "ens-api",
  99. Usage: "URL of the Ethereum API provider to use for ENS record lookups",
  100. Value: node.DefaultIPCEndpoint("geth"),
  101. }
  102. EnsAddrFlag = cli.StringFlag{
  103. Name: "ens-addr",
  104. Usage: "ENS contract address (default is detected as testnet or mainnet using --ens-api)",
  105. }
  106. SwarmApiFlag = cli.StringFlag{
  107. Name: "bzzapi",
  108. Usage: "Swarm HTTP endpoint",
  109. Value: "http://127.0.0.1:8500",
  110. }
  111. SwarmRecursiveUploadFlag = cli.BoolFlag{
  112. Name: "recursive",
  113. Usage: "Upload directories recursively",
  114. }
  115. SwarmWantManifestFlag = cli.BoolTFlag{
  116. Name: "manifest",
  117. Usage: "Automatic manifest upload",
  118. }
  119. SwarmUploadDefaultPath = cli.StringFlag{
  120. Name: "defaultpath",
  121. Usage: "path to file served for empty url path (none)",
  122. }
  123. SwarmUpFromStdinFlag = cli.BoolFlag{
  124. Name: "stdin",
  125. Usage: "reads data to be uploaded from stdin",
  126. }
  127. SwarmUploadMimeType = cli.StringFlag{
  128. Name: "mime",
  129. Usage: "force mime type",
  130. }
  131. CorsStringFlag = cli.StringFlag{
  132. Name: "corsdomain",
  133. Usage: "Domain on which to send Access-Control-Allow-Origin header (multiple domains can be supplied separated by a ',')",
  134. }
  135. // the following flags are deprecated and should be removed in the future
  136. DeprecatedEthAPIFlag = cli.StringFlag{
  137. Name: "ethapi",
  138. Usage: "DEPRECATED: please use --ens-api and --swap-api",
  139. }
  140. )
  141. var defaultNodeConfig = node.DefaultConfig
  142. // This init function sets defaults so cmd/swarm can run alongside geth.
  143. func init() {
  144. defaultNodeConfig.Name = clientIdentifier
  145. defaultNodeConfig.Version = params.VersionWithCommit(gitCommit)
  146. defaultNodeConfig.P2P.ListenAddr = ":30399"
  147. defaultNodeConfig.IPCPath = "bzzd.ipc"
  148. // Set flag defaults for --help display.
  149. utils.ListenPortFlag.Value = 30399
  150. }
  151. var app = utils.NewApp(gitCommit, "Ethereum Swarm")
  152. // This init function creates the cli.App.
  153. func init() {
  154. app.Action = bzzd
  155. app.HideVersion = true // we have a command to print the version
  156. app.Copyright = "Copyright 2013-2016 The go-ethereum Authors"
  157. app.Commands = []cli.Command{
  158. {
  159. Action: version,
  160. Name: "version",
  161. Usage: "Print version numbers",
  162. ArgsUsage: " ",
  163. Description: `
  164. The output of this command is supposed to be machine-readable.
  165. `,
  166. },
  167. {
  168. Action: upload,
  169. Name: "up",
  170. Usage: "upload a file or directory to swarm using the HTTP API",
  171. ArgsUsage: " <file>",
  172. Description: `
  173. "upload a file or directory to swarm using the HTTP API and prints the root hash",
  174. `,
  175. },
  176. {
  177. Action: list,
  178. Name: "ls",
  179. Usage: "list files and directories contained in a manifest",
  180. ArgsUsage: " <manifest> [<prefix>]",
  181. Description: `
  182. Lists files and directories contained in a manifest.
  183. `,
  184. },
  185. {
  186. Action: hash,
  187. Name: "hash",
  188. Usage: "print the swarm hash of a file or directory",
  189. ArgsUsage: " <file>",
  190. Description: `
  191. Prints the swarm hash of file or directory.
  192. `,
  193. },
  194. {
  195. Name: "manifest",
  196. Usage: "update a MANIFEST",
  197. ArgsUsage: "manifest COMMAND",
  198. Description: `
  199. Updates a MANIFEST by adding/removing/updating the hash of a path.
  200. `,
  201. Subcommands: []cli.Command{
  202. {
  203. Action: add,
  204. Name: "add",
  205. Usage: "add a new path to the manifest",
  206. ArgsUsage: "<MANIFEST> <path> <hash> [<content-type>]",
  207. Description: `
  208. Adds a new path to the manifest
  209. `,
  210. },
  211. {
  212. Action: update,
  213. Name: "update",
  214. Usage: "update the hash for an already existing path in the manifest",
  215. ArgsUsage: "<MANIFEST> <path> <newhash> [<newcontent-type>]",
  216. Description: `
  217. Update the hash for an already existing path in the manifest
  218. `,
  219. },
  220. {
  221. Action: remove,
  222. Name: "remove",
  223. Usage: "removes a path from the manifest",
  224. ArgsUsage: "<MANIFEST> <path>",
  225. Description: `
  226. Removes a path from the manifest
  227. `,
  228. },
  229. },
  230. },
  231. {
  232. Action: cleandb,
  233. Name: "cleandb",
  234. Usage: "Cleans database of corrupted entries",
  235. ArgsUsage: " ",
  236. Description: `
  237. Cleans database of corrupted entries.
  238. `,
  239. },
  240. }
  241. app.Flags = []cli.Flag{
  242. utils.IdentityFlag,
  243. utils.DataDirFlag,
  244. utils.BootnodesFlag,
  245. utils.KeyStoreDirFlag,
  246. utils.ListenPortFlag,
  247. utils.NoDiscoverFlag,
  248. utils.DiscoveryV5Flag,
  249. utils.NetrestrictFlag,
  250. utils.NodeKeyFileFlag,
  251. utils.NodeKeyHexFlag,
  252. utils.MaxPeersFlag,
  253. utils.NATFlag,
  254. utils.IPCDisabledFlag,
  255. utils.IPCPathFlag,
  256. utils.PasswordFileFlag,
  257. // bzzd-specific flags
  258. CorsStringFlag,
  259. EnsAPIFlag,
  260. EnsAddrFlag,
  261. SwarmConfigPathFlag,
  262. SwarmSwapEnabledFlag,
  263. SwarmSwapAPIFlag,
  264. SwarmSyncEnabledFlag,
  265. SwarmListenAddrFlag,
  266. SwarmPortFlag,
  267. SwarmAccountFlag,
  268. SwarmNetworkIdFlag,
  269. ChequebookAddrFlag,
  270. // upload flags
  271. SwarmApiFlag,
  272. SwarmRecursiveUploadFlag,
  273. SwarmWantManifestFlag,
  274. SwarmUploadDefaultPath,
  275. SwarmUpFromStdinFlag,
  276. SwarmUploadMimeType,
  277. //deprecated flags
  278. DeprecatedEthAPIFlag,
  279. }
  280. app.Flags = append(app.Flags, debug.Flags...)
  281. app.Before = func(ctx *cli.Context) error {
  282. runtime.GOMAXPROCS(runtime.NumCPU())
  283. return debug.Setup(ctx)
  284. }
  285. app.After = func(ctx *cli.Context) error {
  286. debug.Exit()
  287. return nil
  288. }
  289. }
  290. func main() {
  291. if err := app.Run(os.Args); err != nil {
  292. fmt.Fprintln(os.Stderr, err)
  293. os.Exit(1)
  294. }
  295. }
  296. func version(ctx *cli.Context) error {
  297. fmt.Println(strings.Title(clientIdentifier))
  298. fmt.Println("Version:", params.Version)
  299. if gitCommit != "" {
  300. fmt.Println("Git Commit:", gitCommit)
  301. }
  302. fmt.Println("Network Id:", ctx.GlobalInt(utils.NetworkIdFlag.Name))
  303. fmt.Println("Go Version:", runtime.Version())
  304. fmt.Println("OS:", runtime.GOOS)
  305. fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
  306. fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
  307. return nil
  308. }
  309. func bzzd(ctx *cli.Context) error {
  310. // exit if the deprecated --ethapi flag is set
  311. if ctx.GlobalString(DeprecatedEthAPIFlag.Name) != "" {
  312. utils.Fatalf("--ethapi is no longer a valid command line flag, please use --ens-api and/or --swap-api.")
  313. }
  314. cfg := defaultNodeConfig
  315. utils.SetNodeConfig(ctx, &cfg)
  316. stack, err := node.New(&cfg)
  317. if err != nil {
  318. utils.Fatalf("can't create node: %v", err)
  319. }
  320. registerBzzService(ctx, stack)
  321. utils.StartNode(stack)
  322. go func() {
  323. sigc := make(chan os.Signal, 1)
  324. signal.Notify(sigc, syscall.SIGTERM)
  325. defer signal.Stop(sigc)
  326. <-sigc
  327. log.Info("Got sigterm, shutting swarm down...")
  328. stack.Stop()
  329. }()
  330. networkId := ctx.GlobalUint64(SwarmNetworkIdFlag.Name)
  331. // Add bootnodes as initial peers.
  332. if ctx.GlobalIsSet(utils.BootnodesFlag.Name) {
  333. bootnodes := strings.Split(ctx.GlobalString(utils.BootnodesFlag.Name), ",")
  334. injectBootnodes(stack.Server(), bootnodes)
  335. } else {
  336. if networkId == 3 {
  337. injectBootnodes(stack.Server(), testbetBootNodes)
  338. }
  339. }
  340. stack.Wait()
  341. return nil
  342. }
  343. // detectEnsAddr determines the ENS contract address by getting both the
  344. // version and genesis hash using the client and matching them to either
  345. // mainnet or testnet addresses
  346. func detectEnsAddr(client *rpc.Client) (common.Address, error) {
  347. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  348. defer cancel()
  349. var version string
  350. if err := client.CallContext(ctx, &version, "net_version"); err != nil {
  351. return common.Address{}, err
  352. }
  353. block, err := ethclient.NewClient(client).BlockByNumber(ctx, big.NewInt(0))
  354. if err != nil {
  355. return common.Address{}, err
  356. }
  357. switch {
  358. case version == "1" && block.Hash() == params.MainnetGenesisHash:
  359. log.Info("using Mainnet ENS contract address", "addr", ens.MainNetAddress)
  360. return ens.MainNetAddress, nil
  361. case version == "3" && block.Hash() == params.TestnetGenesisHash:
  362. log.Info("using Testnet ENS contract address", "addr", ens.TestNetAddress)
  363. return ens.TestNetAddress, nil
  364. default:
  365. return common.Address{}, fmt.Errorf("unknown version and genesis hash: %s %s", version, block.Hash())
  366. }
  367. }
  368. func registerBzzService(ctx *cli.Context, stack *node.Node) {
  369. prvkey := getAccount(ctx, stack)
  370. chbookaddr := common.HexToAddress(ctx.GlobalString(ChequebookAddrFlag.Name))
  371. bzzdir := ctx.GlobalString(SwarmConfigPathFlag.Name)
  372. if bzzdir == "" {
  373. bzzdir = stack.InstanceDir()
  374. }
  375. bzzconfig, err := bzzapi.NewConfig(bzzdir, chbookaddr, prvkey, ctx.GlobalUint64(SwarmNetworkIdFlag.Name))
  376. if err != nil {
  377. utils.Fatalf("unable to configure swarm: %v", err)
  378. }
  379. bzzport := ctx.GlobalString(SwarmPortFlag.Name)
  380. if len(bzzport) > 0 {
  381. bzzconfig.Port = bzzport
  382. }
  383. if bzzaddr := ctx.GlobalString(SwarmListenAddrFlag.Name); bzzaddr != "" {
  384. bzzconfig.ListenAddr = bzzaddr
  385. }
  386. swapEnabled := ctx.GlobalBool(SwarmSwapEnabledFlag.Name)
  387. syncEnabled := ctx.GlobalBoolT(SwarmSyncEnabledFlag.Name)
  388. swapapi := ctx.GlobalString(SwarmSwapAPIFlag.Name)
  389. if swapEnabled && swapapi == "" {
  390. utils.Fatalf("SWAP is enabled but --swap-api is not set")
  391. }
  392. ensapi := ctx.GlobalString(EnsAPIFlag.Name)
  393. ensAddr := ctx.GlobalString(EnsAddrFlag.Name)
  394. cors := ctx.GlobalString(CorsStringFlag.Name)
  395. boot := func(ctx *node.ServiceContext) (node.Service, error) {
  396. var swapClient *ethclient.Client
  397. if swapapi != "" {
  398. log.Info("connecting to SWAP API", "url", swapapi)
  399. swapClient, err = ethclient.Dial(swapapi)
  400. if err != nil {
  401. return nil, fmt.Errorf("error connecting to SWAP API %s: %s", swapapi, err)
  402. }
  403. }
  404. var ensClient *ethclient.Client
  405. if ensapi != "" {
  406. log.Info("connecting to ENS API", "url", ensapi)
  407. client, err := rpc.Dial(ensapi)
  408. if err != nil {
  409. return nil, fmt.Errorf("error connecting to ENS API %s: %s", ensapi, err)
  410. }
  411. ensClient = ethclient.NewClient(client)
  412. if ensAddr != "" {
  413. bzzconfig.EnsRoot = common.HexToAddress(ensAddr)
  414. } else {
  415. ensAddr, err := detectEnsAddr(client)
  416. if err == nil {
  417. bzzconfig.EnsRoot = ensAddr
  418. } else {
  419. log.Warn(fmt.Sprintf("could not determine ENS contract address, using default %s", bzzconfig.EnsRoot), "err", err)
  420. }
  421. }
  422. }
  423. return swarm.NewSwarm(ctx, swapClient, ensClient, bzzconfig, swapEnabled, syncEnabled, cors)
  424. }
  425. if err := stack.Register(boot); err != nil {
  426. utils.Fatalf("Failed to register the Swarm service: %v", err)
  427. }
  428. }
  429. func getAccount(ctx *cli.Context, stack *node.Node) *ecdsa.PrivateKey {
  430. keyid := ctx.GlobalString(SwarmAccountFlag.Name)
  431. if keyid == "" {
  432. utils.Fatalf("Option %q is required", SwarmAccountFlag.Name)
  433. }
  434. // Try to load the arg as a hex key file.
  435. if key, err := crypto.LoadECDSA(keyid); err == nil {
  436. log.Info("Swarm account key loaded", "address", crypto.PubkeyToAddress(key.PublicKey))
  437. return key
  438. }
  439. // Otherwise try getting it from the keystore.
  440. am := stack.AccountManager()
  441. ks := am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  442. return decryptStoreAccount(ks, keyid, utils.MakePasswordList(ctx))
  443. }
  444. func decryptStoreAccount(ks *keystore.KeyStore, account string, passwords []string) *ecdsa.PrivateKey {
  445. var a accounts.Account
  446. var err error
  447. if common.IsHexAddress(account) {
  448. a, err = ks.Find(accounts.Account{Address: common.HexToAddress(account)})
  449. } else if ix, ixerr := strconv.Atoi(account); ixerr == nil && ix > 0 {
  450. if accounts := ks.Accounts(); len(accounts) > ix {
  451. a = accounts[ix]
  452. } else {
  453. err = fmt.Errorf("index %d higher than number of accounts %d", ix, len(accounts))
  454. }
  455. } else {
  456. utils.Fatalf("Can't find swarm account key %s", account)
  457. }
  458. if err != nil {
  459. utils.Fatalf("Can't find swarm account key: %v", err)
  460. }
  461. keyjson, err := ioutil.ReadFile(a.URL.Path)
  462. if err != nil {
  463. utils.Fatalf("Can't load swarm account key: %v", err)
  464. }
  465. for i := 0; i < 3; i++ {
  466. password := getPassPhrase(fmt.Sprintf("Unlocking swarm account %s [%d/3]", a.Address.Hex(), i+1), i, passwords)
  467. key, err := keystore.DecryptKey(keyjson, password)
  468. if err == nil {
  469. return key.PrivateKey
  470. }
  471. }
  472. utils.Fatalf("Can't decrypt swarm account key")
  473. return nil
  474. }
  475. // getPassPhrase retrieves the password associated with bzz account, either by fetching
  476. // from a list of pre-loaded passwords, or by requesting it interactively from user.
  477. func getPassPhrase(prompt string, i int, passwords []string) string {
  478. // non-interactive
  479. if len(passwords) > 0 {
  480. if i < len(passwords) {
  481. return passwords[i]
  482. }
  483. return passwords[len(passwords)-1]
  484. }
  485. // fallback to interactive mode
  486. if prompt != "" {
  487. fmt.Println(prompt)
  488. }
  489. password, err := console.Stdin.PromptPassword("Passphrase: ")
  490. if err != nil {
  491. utils.Fatalf("Failed to read passphrase: %v", err)
  492. }
  493. return password
  494. }
  495. func injectBootnodes(srv *p2p.Server, nodes []string) {
  496. for _, url := range nodes {
  497. n, err := discover.ParseNode(url)
  498. if err != nil {
  499. log.Error("Invalid swarm bootnode", "err", err)
  500. continue
  501. }
  502. srv.AddPeer(n)
  503. }
  504. }