main.go 20 KB

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