main.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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. "crypto/ecdsa"
  19. "fmt"
  20. "io/ioutil"
  21. "os"
  22. "os/signal"
  23. "runtime"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "syscall"
  28. "github.com/ethereum/go-ethereum/accounts"
  29. "github.com/ethereum/go-ethereum/accounts/keystore"
  30. "github.com/ethereum/go-ethereum/cmd/utils"
  31. "github.com/ethereum/go-ethereum/common"
  32. "github.com/ethereum/go-ethereum/console"
  33. "github.com/ethereum/go-ethereum/crypto"
  34. "github.com/ethereum/go-ethereum/internal/debug"
  35. "github.com/ethereum/go-ethereum/log"
  36. "github.com/ethereum/go-ethereum/node"
  37. "github.com/ethereum/go-ethereum/p2p"
  38. "github.com/ethereum/go-ethereum/p2p/discover"
  39. "github.com/ethereum/go-ethereum/params"
  40. "github.com/ethereum/go-ethereum/swarm"
  41. bzzapi "github.com/ethereum/go-ethereum/swarm/api"
  42. swarmmetrics "github.com/ethereum/go-ethereum/swarm/metrics"
  43. "gopkg.in/urfave/cli.v1"
  44. )
  45. const clientIdentifier = "swarm"
  46. const helpTemplate = `NAME:
  47. {{.HelpName}} - {{.Usage}}
  48. USAGE:
  49. {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Category}}
  50. CATEGORY:
  51. {{.Category}}{{end}}{{if .Description}}
  52. DESCRIPTION:
  53. {{.Description}}{{end}}{{if .VisibleFlags}}
  54. OPTIONS:
  55. {{range .VisibleFlags}}{{.}}
  56. {{end}}{{end}}
  57. `
  58. var (
  59. gitCommit string // Git SHA1 commit hash of the release (set via linker flags)
  60. testbetBootNodes = []string{
  61. "enode://ec8ae764f7cb0417bdfb009b9d0f18ab3818a3a4e8e7c67dd5f18971a93510a2e6f43cd0b69a27e439a9629457ea804104f37c85e41eed057d3faabbf7744cdf@13.74.157.139:30429",
  62. "enode://c2e1fceb3bf3be19dff71eec6cccf19f2dbf7567ee017d130240c670be8594bc9163353ca55dd8df7a4f161dd94b36d0615c17418b5a3cdcbb4e9d99dfa4de37@13.74.157.139:30430",
  63. "enode://fe29b82319b734ce1ec68b84657d57145fee237387e63273989d354486731e59f78858e452ef800a020559da22dcca759536e6aa5517c53930d29ce0b1029286@13.74.157.139:30431",
  64. "enode://1d7187e7bde45cf0bee489ce9852dd6d1a0d9aa67a33a6b8e6db8a4fbc6fcfa6f0f1a5419343671521b863b187d1c73bad3603bae66421d157ffef357669ddb8@13.74.157.139:30432",
  65. "enode://0e4cba800f7b1ee73673afa6a4acead4018f0149d2e3216be3f133318fd165b324cd71b81fbe1e80deac8dbf56e57a49db7be67f8b9bc81bd2b7ee496434fb5d@13.74.157.139:30433",
  66. }
  67. )
  68. var (
  69. ChequebookAddrFlag = cli.StringFlag{
  70. Name: "chequebook",
  71. Usage: "chequebook contract address",
  72. EnvVar: SWARM_ENV_CHEQUEBOOK_ADDR,
  73. }
  74. SwarmAccountFlag = cli.StringFlag{
  75. Name: "bzzaccount",
  76. Usage: "Swarm account key file",
  77. EnvVar: SWARM_ENV_ACCOUNT,
  78. }
  79. SwarmListenAddrFlag = cli.StringFlag{
  80. Name: "httpaddr",
  81. Usage: "Swarm HTTP API listening interface",
  82. EnvVar: SWARM_ENV_LISTEN_ADDR,
  83. }
  84. SwarmPortFlag = cli.StringFlag{
  85. Name: "bzzport",
  86. Usage: "Swarm local http api port",
  87. EnvVar: SWARM_ENV_PORT,
  88. }
  89. SwarmNetworkIdFlag = cli.IntFlag{
  90. Name: "bzznetworkid",
  91. Usage: "Network identifier (integer, default 3=swarm testnet)",
  92. EnvVar: SWARM_ENV_NETWORK_ID,
  93. }
  94. SwarmSwapEnabledFlag = cli.BoolFlag{
  95. Name: "swap",
  96. Usage: "Swarm SWAP enabled (default false)",
  97. EnvVar: SWARM_ENV_SWAP_ENABLE,
  98. }
  99. SwarmSwapAPIFlag = cli.StringFlag{
  100. Name: "swap-api",
  101. Usage: "URL of the Ethereum API provider to use to settle SWAP payments",
  102. EnvVar: SWARM_ENV_SWAP_API,
  103. }
  104. SwarmSyncDisabledFlag = cli.BoolTFlag{
  105. Name: "nosync",
  106. Usage: "Disable swarm syncing",
  107. EnvVar: SWARM_ENV_SYNC_DISABLE,
  108. }
  109. SwarmSyncUpdateDelay = cli.DurationFlag{
  110. Name: "sync-update-delay",
  111. Usage: "Duration for sync subscriptions update after no new peers are added (default 15s)",
  112. EnvVar: SWARM_ENV_SYNC_UPDATE_DELAY,
  113. }
  114. SwarmDeliverySkipCheckFlag = cli.BoolFlag{
  115. Name: "delivery-skip-check",
  116. Usage: "Skip chunk delivery check (default false)",
  117. EnvVar: SWARM_ENV_DELIVERY_SKIP_CHECK,
  118. }
  119. EnsAPIFlag = cli.StringSliceFlag{
  120. Name: "ens-api",
  121. Usage: "ENS API endpoint for a TLD and with contract address, can be repeated, format [tld:][contract-addr@]url",
  122. EnvVar: SWARM_ENV_ENS_API,
  123. }
  124. SwarmApiFlag = cli.StringFlag{
  125. Name: "bzzapi",
  126. Usage: "Swarm HTTP endpoint",
  127. Value: "http://127.0.0.1:8500",
  128. }
  129. SwarmRecursiveFlag = cli.BoolFlag{
  130. Name: "recursive",
  131. Usage: "Upload directories recursively",
  132. }
  133. SwarmWantManifestFlag = cli.BoolTFlag{
  134. Name: "manifest",
  135. Usage: "Automatic manifest upload (default true)",
  136. }
  137. SwarmUploadDefaultPath = cli.StringFlag{
  138. Name: "defaultpath",
  139. Usage: "path to file served for empty url path (none)",
  140. }
  141. SwarmUpFromStdinFlag = cli.BoolFlag{
  142. Name: "stdin",
  143. Usage: "reads data to be uploaded from stdin",
  144. }
  145. SwarmUploadMimeType = cli.StringFlag{
  146. Name: "mime",
  147. Usage: "Manually specify MIME type",
  148. }
  149. SwarmEncryptedFlag = cli.BoolFlag{
  150. Name: "encrypt",
  151. Usage: "use encrypted upload",
  152. }
  153. CorsStringFlag = cli.StringFlag{
  154. Name: "corsdomain",
  155. Usage: "Domain on which to send Access-Control-Allow-Origin header (multiple domains can be supplied separated by a ',')",
  156. EnvVar: SWARM_ENV_CORS,
  157. }
  158. SwarmStorePath = cli.StringFlag{
  159. Name: "store.path",
  160. Usage: "Path to leveldb chunk DB (default <$GETH_ENV_DIR>/swarm/bzz-<$BZZ_KEY>/chunks)",
  161. EnvVar: SWARM_ENV_STORE_PATH,
  162. }
  163. SwarmStoreCapacity = cli.Uint64Flag{
  164. Name: "store.size",
  165. Usage: "Number of chunks (5M is roughly 20-25GB) (default 5000000)",
  166. EnvVar: SWARM_ENV_STORE_CAPACITY,
  167. }
  168. SwarmStoreCacheCapacity = cli.UintFlag{
  169. Name: "store.cache.size",
  170. Usage: "Number of recent chunks cached in memory (default 5000)",
  171. EnvVar: SWARM_ENV_STORE_CACHE_CAPACITY,
  172. }
  173. )
  174. //declare a few constant error messages, useful for later error check comparisons in test
  175. var (
  176. SWARM_ERR_NO_BZZACCOUNT = "bzzaccount option is required but not set; check your config file, command line or environment variables"
  177. SWARM_ERR_SWAP_SET_NO_API = "SWAP is enabled but --swap-api is not set"
  178. )
  179. var defaultNodeConfig = node.DefaultConfig
  180. // This init function sets defaults so cmd/swarm can run alongside geth.
  181. func init() {
  182. defaultNodeConfig.Name = clientIdentifier
  183. defaultNodeConfig.Version = params.VersionWithCommit(gitCommit)
  184. defaultNodeConfig.P2P.ListenAddr = ":30399"
  185. defaultNodeConfig.IPCPath = "bzzd.ipc"
  186. // Set flag defaults for --help display.
  187. utils.ListenPortFlag.Value = 30399
  188. }
  189. var app = utils.NewApp(gitCommit, "Ethereum Swarm")
  190. // This init function creates the cli.App.
  191. func init() {
  192. app.Action = bzzd
  193. app.HideVersion = true // we have a command to print the version
  194. app.Copyright = "Copyright 2013-2016 The go-ethereum Authors"
  195. app.Commands = []cli.Command{
  196. {
  197. Action: version,
  198. CustomHelpTemplate: helpTemplate,
  199. Name: "version",
  200. Usage: "Print version numbers",
  201. Description: "The output of this command is supposed to be machine-readable",
  202. },
  203. {
  204. Action: upload,
  205. CustomHelpTemplate: helpTemplate,
  206. Name: "up",
  207. Usage: "uploads a file or directory to swarm using the HTTP API",
  208. ArgsUsage: "<file>",
  209. Flags: []cli.Flag{SwarmEncryptedFlag},
  210. Description: "uploads a file or directory to swarm using the HTTP API and prints the root hash",
  211. },
  212. {
  213. Action: list,
  214. CustomHelpTemplate: helpTemplate,
  215. Name: "ls",
  216. Usage: "list files and directories contained in a manifest",
  217. ArgsUsage: "<manifest> [<prefix>]",
  218. Description: "Lists files and directories contained in a manifest",
  219. },
  220. {
  221. Action: hash,
  222. CustomHelpTemplate: helpTemplate,
  223. Name: "hash",
  224. Usage: "print the swarm hash of a file or directory",
  225. ArgsUsage: "<file>",
  226. Description: "Prints the swarm hash of file or directory",
  227. },
  228. {
  229. Action: download,
  230. Name: "down",
  231. Flags: []cli.Flag{SwarmRecursiveFlag},
  232. Usage: "downloads a swarm manifest or a file inside a manifest",
  233. ArgsUsage: " <uri> [<dir>]",
  234. Description: `
  235. Downloads a swarm bzz uri to the given dir. When no dir is provided, working directory is assumed. --recursive flag is expected when downloading a manifest with multiple entries.
  236. `,
  237. },
  238. {
  239. Name: "manifest",
  240. CustomHelpTemplate: helpTemplate,
  241. Usage: "perform operations on swarm manifests",
  242. ArgsUsage: "COMMAND",
  243. Description: "Updates a MANIFEST by adding/removing/updating the hash of a path.\nCOMMAND could be: add, update, remove",
  244. Subcommands: []cli.Command{
  245. {
  246. Action: add,
  247. CustomHelpTemplate: helpTemplate,
  248. Name: "add",
  249. Usage: "add a new path to the manifest",
  250. ArgsUsage: "<MANIFEST> <path> <hash> [<content-type>]",
  251. Description: "Adds a new path to the manifest",
  252. },
  253. {
  254. Action: update,
  255. CustomHelpTemplate: helpTemplate,
  256. Name: "update",
  257. Usage: "update the hash for an already existing path in the manifest",
  258. ArgsUsage: "<MANIFEST> <path> <newhash> [<newcontent-type>]",
  259. Description: "Update the hash for an already existing path in the manifest",
  260. },
  261. {
  262. Action: remove,
  263. CustomHelpTemplate: helpTemplate,
  264. Name: "remove",
  265. Usage: "removes a path from the manifest",
  266. ArgsUsage: "<MANIFEST> <path>",
  267. Description: "Removes a path from the manifest",
  268. },
  269. },
  270. },
  271. {
  272. Name: "fs",
  273. CustomHelpTemplate: helpTemplate,
  274. Usage: "perform FUSE operations",
  275. ArgsUsage: "fs COMMAND",
  276. Description: "Performs FUSE operations by mounting/unmounting/listing mount points. This assumes you already have a Swarm node running locally. For all operation you must reference the correct path to bzzd.ipc in order to communicate with the node",
  277. Subcommands: []cli.Command{
  278. {
  279. Action: mount,
  280. CustomHelpTemplate: helpTemplate,
  281. Name: "mount",
  282. Flags: []cli.Flag{utils.IPCPathFlag},
  283. Usage: "mount a swarm hash to a mount point",
  284. ArgsUsage: "swarm fs mount --ipcpath <path to bzzd.ipc> <manifest hash> <mount point>",
  285. Description: "Mounts a Swarm manifest hash to a given mount point. This assumes you already have a Swarm node running locally. You must reference the correct path to your bzzd.ipc file",
  286. },
  287. {
  288. Action: unmount,
  289. CustomHelpTemplate: helpTemplate,
  290. Name: "unmount",
  291. Flags: []cli.Flag{utils.IPCPathFlag},
  292. Usage: "unmount a swarmfs mount",
  293. ArgsUsage: "swarm fs unmount --ipcpath <path to bzzd.ipc> <mount point>",
  294. Description: "Unmounts a swarmfs mount residing at <mount point>. This assumes you already have a Swarm node running locally. You must reference the correct path to your bzzd.ipc file",
  295. },
  296. {
  297. Action: listMounts,
  298. CustomHelpTemplate: helpTemplate,
  299. Name: "list",
  300. Flags: []cli.Flag{utils.IPCPathFlag},
  301. Usage: "list swarmfs mounts",
  302. ArgsUsage: "swarm fs list --ipcpath <path to bzzd.ipc>",
  303. Description: "Lists all mounted swarmfs volumes. This assumes you already have a Swarm node running locally. You must reference the correct path to your bzzd.ipc file",
  304. },
  305. },
  306. },
  307. {
  308. Name: "db",
  309. CustomHelpTemplate: helpTemplate,
  310. Usage: "manage the local chunk database",
  311. ArgsUsage: "db COMMAND",
  312. Description: "Manage the local chunk database",
  313. Subcommands: []cli.Command{
  314. {
  315. Action: dbExport,
  316. CustomHelpTemplate: helpTemplate,
  317. Name: "export",
  318. Usage: "export a local chunk database as a tar archive (use - to send to stdout)",
  319. ArgsUsage: "<chunkdb> <file>",
  320. Description: `
  321. Export a local chunk database as a tar archive (use - to send to stdout).
  322. swarm db export ~/.ethereum/swarm/bzz-KEY/chunks chunks.tar
  323. The export may be quite large, consider piping the output through the Unix
  324. pv(1) tool to get a progress bar:
  325. swarm db export ~/.ethereum/swarm/bzz-KEY/chunks - | pv > chunks.tar
  326. `,
  327. },
  328. {
  329. Action: dbImport,
  330. CustomHelpTemplate: helpTemplate,
  331. Name: "import",
  332. Usage: "import chunks from a tar archive into a local chunk database (use - to read from stdin)",
  333. ArgsUsage: "<chunkdb> <file>",
  334. Description: `
  335. Import chunks from a tar archive into a local chunk database (use - to read from stdin).
  336. swarm db import ~/.ethereum/swarm/bzz-KEY/chunks chunks.tar
  337. The import may be quite large, consider piping the input through the Unix
  338. pv(1) tool to get a progress bar:
  339. pv chunks.tar | swarm db import ~/.ethereum/swarm/bzz-KEY/chunks -
  340. `,
  341. },
  342. {
  343. Action: dbClean,
  344. CustomHelpTemplate: helpTemplate,
  345. Name: "clean",
  346. Usage: "remove corrupt entries from a local chunk database",
  347. ArgsUsage: "<chunkdb>",
  348. Description: "Remove corrupt entries from a local chunk database",
  349. },
  350. },
  351. },
  352. // See config.go
  353. DumpConfigCommand,
  354. }
  355. sort.Sort(cli.CommandsByName(app.Commands))
  356. app.Flags = []cli.Flag{
  357. utils.IdentityFlag,
  358. utils.DataDirFlag,
  359. utils.BootnodesFlag,
  360. utils.KeyStoreDirFlag,
  361. utils.ListenPortFlag,
  362. utils.NoDiscoverFlag,
  363. utils.DiscoveryV5Flag,
  364. utils.NetrestrictFlag,
  365. utils.NodeKeyFileFlag,
  366. utils.NodeKeyHexFlag,
  367. utils.MaxPeersFlag,
  368. utils.NATFlag,
  369. utils.IPCDisabledFlag,
  370. utils.IPCPathFlag,
  371. utils.PasswordFileFlag,
  372. // bzzd-specific flags
  373. CorsStringFlag,
  374. EnsAPIFlag,
  375. SwarmTomlConfigPathFlag,
  376. SwarmSwapEnabledFlag,
  377. SwarmSwapAPIFlag,
  378. SwarmSyncDisabledFlag,
  379. SwarmSyncUpdateDelay,
  380. SwarmDeliverySkipCheckFlag,
  381. SwarmListenAddrFlag,
  382. SwarmPortFlag,
  383. SwarmAccountFlag,
  384. SwarmNetworkIdFlag,
  385. ChequebookAddrFlag,
  386. // upload flags
  387. SwarmApiFlag,
  388. SwarmRecursiveFlag,
  389. SwarmWantManifestFlag,
  390. SwarmUploadDefaultPath,
  391. SwarmUpFromStdinFlag,
  392. SwarmUploadMimeType,
  393. // storage flags
  394. SwarmStorePath,
  395. SwarmStoreCapacity,
  396. SwarmStoreCacheCapacity,
  397. }
  398. rpcFlags := []cli.Flag{
  399. utils.WSEnabledFlag,
  400. utils.WSListenAddrFlag,
  401. utils.WSPortFlag,
  402. utils.WSApiFlag,
  403. utils.WSAllowedOriginsFlag,
  404. }
  405. app.Flags = append(app.Flags, rpcFlags...)
  406. app.Flags = append(app.Flags, debug.Flags...)
  407. app.Flags = append(app.Flags, swarmmetrics.Flags...)
  408. app.Before = func(ctx *cli.Context) error {
  409. runtime.GOMAXPROCS(runtime.NumCPU())
  410. if err := debug.Setup(ctx, ""); err != nil {
  411. return err
  412. }
  413. swarmmetrics.Setup(ctx)
  414. return nil
  415. }
  416. app.After = func(ctx *cli.Context) error {
  417. debug.Exit()
  418. return nil
  419. }
  420. }
  421. func main() {
  422. if err := app.Run(os.Args); err != nil {
  423. fmt.Fprintln(os.Stderr, err)
  424. os.Exit(1)
  425. }
  426. }
  427. func version(ctx *cli.Context) error {
  428. fmt.Println("Version:", SWARM_VERSION)
  429. if gitCommit != "" {
  430. fmt.Println("Git Commit:", gitCommit)
  431. }
  432. fmt.Println("Go Version:", runtime.Version())
  433. fmt.Println("OS:", runtime.GOOS)
  434. return nil
  435. }
  436. func bzzd(ctx *cli.Context) error {
  437. //build a valid bzzapi.Config from all available sources:
  438. //default config, file config, command line and env vars
  439. bzzconfig, err := buildConfig(ctx)
  440. if err != nil {
  441. utils.Fatalf("unable to configure swarm: %v", err)
  442. }
  443. cfg := defaultNodeConfig
  444. //pss operates on ws
  445. cfg.WSModules = append(cfg.WSModules, "pss")
  446. //geth only supports --datadir via command line
  447. //in order to be consistent within swarm, if we pass --datadir via environment variable
  448. //or via config file, we get the same directory for geth and swarm
  449. if _, err := os.Stat(bzzconfig.Path); err == nil {
  450. cfg.DataDir = bzzconfig.Path
  451. }
  452. //setup the ethereum node
  453. utils.SetNodeConfig(ctx, &cfg)
  454. stack, err := node.New(&cfg)
  455. if err != nil {
  456. utils.Fatalf("can't create node: %v", err)
  457. }
  458. //a few steps need to be done after the config phase is completed,
  459. //due to overriding behavior
  460. initSwarmNode(bzzconfig, stack, ctx)
  461. //register BZZ as node.Service in the ethereum node
  462. registerBzzService(bzzconfig, stack)
  463. //start the node
  464. utils.StartNode(stack)
  465. go func() {
  466. sigc := make(chan os.Signal, 1)
  467. signal.Notify(sigc, syscall.SIGTERM)
  468. defer signal.Stop(sigc)
  469. <-sigc
  470. log.Info("Got sigterm, shutting swarm down...")
  471. stack.Stop()
  472. }()
  473. // Add bootnodes as initial peers.
  474. if bzzconfig.BootNodes != "" {
  475. bootnodes := strings.Split(bzzconfig.BootNodes, ",")
  476. injectBootnodes(stack.Server(), bootnodes)
  477. } else {
  478. if bzzconfig.NetworkID == 3 {
  479. injectBootnodes(stack.Server(), testbetBootNodes)
  480. }
  481. }
  482. stack.Wait()
  483. return nil
  484. }
  485. func registerBzzService(bzzconfig *bzzapi.Config, stack *node.Node) {
  486. //define the swarm service boot function
  487. boot := func(_ *node.ServiceContext) (node.Service, error) {
  488. // In production, mockStore must be always nil.
  489. return swarm.NewSwarm(bzzconfig, nil)
  490. }
  491. //register within the ethereum node
  492. if err := stack.Register(boot); err != nil {
  493. utils.Fatalf("Failed to register the Swarm service: %v", err)
  494. }
  495. }
  496. func getAccount(bzzaccount string, ctx *cli.Context, stack *node.Node) *ecdsa.PrivateKey {
  497. //an account is mandatory
  498. if bzzaccount == "" {
  499. utils.Fatalf(SWARM_ERR_NO_BZZACCOUNT)
  500. }
  501. // Try to load the arg as a hex key file.
  502. if key, err := crypto.LoadECDSA(bzzaccount); err == nil {
  503. log.Info("Swarm account key loaded", "address", crypto.PubkeyToAddress(key.PublicKey))
  504. return key
  505. }
  506. // Otherwise try getting it from the keystore.
  507. am := stack.AccountManager()
  508. ks := am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  509. return decryptStoreAccount(ks, bzzaccount, utils.MakePasswordList(ctx))
  510. }
  511. func decryptStoreAccount(ks *keystore.KeyStore, account string, passwords []string) *ecdsa.PrivateKey {
  512. var a accounts.Account
  513. var err error
  514. if common.IsHexAddress(account) {
  515. a, err = ks.Find(accounts.Account{Address: common.HexToAddress(account)})
  516. } else if ix, ixerr := strconv.Atoi(account); ixerr == nil && ix > 0 {
  517. if accounts := ks.Accounts(); len(accounts) > ix {
  518. a = accounts[ix]
  519. } else {
  520. err = fmt.Errorf("index %d higher than number of accounts %d", ix, len(accounts))
  521. }
  522. } else {
  523. utils.Fatalf("Can't find swarm account key %s", account)
  524. }
  525. if err != nil {
  526. utils.Fatalf("Can't find swarm account key: %v - Is the provided bzzaccount(%s) from the right datadir/Path?", err, account)
  527. }
  528. keyjson, err := ioutil.ReadFile(a.URL.Path)
  529. if err != nil {
  530. utils.Fatalf("Can't load swarm account key: %v", err)
  531. }
  532. for i := 0; i < 3; i++ {
  533. password := getPassPhrase(fmt.Sprintf("Unlocking swarm account %s [%d/3]", a.Address.Hex(), i+1), i, passwords)
  534. key, err := keystore.DecryptKey(keyjson, password)
  535. if err == nil {
  536. return key.PrivateKey
  537. }
  538. }
  539. utils.Fatalf("Can't decrypt swarm account key")
  540. return nil
  541. }
  542. // getPassPhrase retrieves the password associated with bzz account, either by fetching
  543. // from a list of pre-loaded passwords, or by requesting it interactively from user.
  544. func getPassPhrase(prompt string, i int, passwords []string) string {
  545. // non-interactive
  546. if len(passwords) > 0 {
  547. if i < len(passwords) {
  548. return passwords[i]
  549. }
  550. return passwords[len(passwords)-1]
  551. }
  552. // fallback to interactive mode
  553. if prompt != "" {
  554. fmt.Println(prompt)
  555. }
  556. password, err := console.Stdin.PromptPassword("Passphrase: ")
  557. if err != nil {
  558. utils.Fatalf("Failed to read passphrase: %v", err)
  559. }
  560. return password
  561. }
  562. func injectBootnodes(srv *p2p.Server, nodes []string) {
  563. for _, url := range nodes {
  564. n, err := discover.ParseNode(url)
  565. if err != nil {
  566. log.Error("Invalid swarm bootnode", "err", err)
  567. continue
  568. }
  569. srv.AddPeer(n)
  570. }
  571. }