main.go 16 KB

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