main.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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/swarm"
  40. bzzapi "github.com/ethereum/go-ethereum/swarm/api"
  41. swarmmetrics "github.com/ethereum/go-ethereum/swarm/metrics"
  42. "github.com/ethereum/go-ethereum/swarm/tracing"
  43. sv "github.com/ethereum/go-ethereum/swarm/version"
  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. SwarmLightNodeEnabled = cli.BoolFlag{
  116. Name: "lightnode",
  117. Usage: "Enable Swarm LightNode (default false)",
  118. EnvVar: SWARM_ENV_LIGHT_NODE_ENABLE,
  119. }
  120. SwarmDeliverySkipCheckFlag = cli.BoolFlag{
  121. Name: "delivery-skip-check",
  122. Usage: "Skip chunk delivery check (default false)",
  123. EnvVar: SWARM_ENV_DELIVERY_SKIP_CHECK,
  124. }
  125. EnsAPIFlag = cli.StringSliceFlag{
  126. Name: "ens-api",
  127. Usage: "ENS API endpoint for a TLD and with contract address, can be repeated, format [tld:][contract-addr@]url",
  128. EnvVar: SWARM_ENV_ENS_API,
  129. }
  130. SwarmApiFlag = cli.StringFlag{
  131. Name: "bzzapi",
  132. Usage: "Swarm HTTP endpoint",
  133. Value: "http://127.0.0.1:8500",
  134. }
  135. SwarmRecursiveFlag = cli.BoolFlag{
  136. Name: "recursive",
  137. Usage: "Upload directories recursively",
  138. }
  139. SwarmWantManifestFlag = cli.BoolTFlag{
  140. Name: "manifest",
  141. Usage: "Automatic manifest upload (default true)",
  142. }
  143. SwarmUploadDefaultPath = cli.StringFlag{
  144. Name: "defaultpath",
  145. Usage: "path to file served for empty url path (none)",
  146. }
  147. SwarmUpFromStdinFlag = cli.BoolFlag{
  148. Name: "stdin",
  149. Usage: "reads data to be uploaded from stdin",
  150. }
  151. SwarmUploadMimeType = cli.StringFlag{
  152. Name: "mime",
  153. Usage: "Manually specify MIME type",
  154. }
  155. SwarmEncryptedFlag = cli.BoolFlag{
  156. Name: "encrypt",
  157. Usage: "use encrypted upload",
  158. }
  159. CorsStringFlag = cli.StringFlag{
  160. Name: "corsdomain",
  161. Usage: "Domain on which to send Access-Control-Allow-Origin header (multiple domains can be supplied separated by a ',')",
  162. EnvVar: SWARM_ENV_CORS,
  163. }
  164. SwarmStorePath = cli.StringFlag{
  165. Name: "store.path",
  166. Usage: "Path to leveldb chunk DB (default <$GETH_ENV_DIR>/swarm/bzz-<$BZZ_KEY>/chunks)",
  167. EnvVar: SWARM_ENV_STORE_PATH,
  168. }
  169. SwarmStoreCapacity = cli.Uint64Flag{
  170. Name: "store.size",
  171. Usage: "Number of chunks (5M is roughly 20-25GB) (default 5000000)",
  172. EnvVar: SWARM_ENV_STORE_CAPACITY,
  173. }
  174. SwarmStoreCacheCapacity = cli.UintFlag{
  175. Name: "store.cache.size",
  176. Usage: "Number of recent chunks cached in memory (default 5000)",
  177. EnvVar: SWARM_ENV_STORE_CACHE_CAPACITY,
  178. }
  179. SwarmResourceMultihashFlag = cli.BoolFlag{
  180. Name: "multihash",
  181. Usage: "Determines how to interpret data for a resource update. If not present, data will be interpreted as raw, literal data that will be included in the resource",
  182. }
  183. SwarmResourceNameFlag = cli.StringFlag{
  184. Name: "name",
  185. Usage: "User-defined name for the new resource",
  186. }
  187. SwarmResourceDataOnCreateFlag = cli.StringFlag{
  188. Name: "data",
  189. Usage: "Initializes the resource with the given hex-encoded data. Data must be prefixed by 0x",
  190. }
  191. )
  192. //declare a few constant error messages, useful for later error check comparisons in test
  193. var (
  194. SWARM_ERR_NO_BZZACCOUNT = "bzzaccount option is required but not set; check your config file, command line or environment variables"
  195. SWARM_ERR_SWAP_SET_NO_API = "SWAP is enabled but --swap-api is not set"
  196. )
  197. // this help command gets added to any subcommand that does not define it explicitly
  198. var defaultSubcommandHelp = cli.Command{
  199. Action: func(ctx *cli.Context) { cli.ShowCommandHelpAndExit(ctx, "", 1) },
  200. CustomHelpTemplate: helpTemplate,
  201. Name: "help",
  202. Usage: "shows this help",
  203. Hidden: true,
  204. }
  205. var defaultNodeConfig = node.DefaultConfig
  206. // This init function sets defaults so cmd/swarm can run alongside geth.
  207. func init() {
  208. defaultNodeConfig.Name = clientIdentifier
  209. defaultNodeConfig.Version = sv.VersionWithCommit(gitCommit)
  210. defaultNodeConfig.P2P.ListenAddr = ":30399"
  211. defaultNodeConfig.IPCPath = "bzzd.ipc"
  212. // Set flag defaults for --help display.
  213. utils.ListenPortFlag.Value = 30399
  214. }
  215. var app = utils.NewApp(gitCommit, "Ethereum Swarm")
  216. // This init function creates the cli.App.
  217. func init() {
  218. app.Action = bzzd
  219. app.HideVersion = true // we have a command to print the version
  220. app.Copyright = "Copyright 2013-2016 The go-ethereum Authors"
  221. app.Commands = []cli.Command{
  222. {
  223. Action: version,
  224. CustomHelpTemplate: helpTemplate,
  225. Name: "version",
  226. Usage: "Print version numbers",
  227. Description: "The output of this command is supposed to be machine-readable",
  228. },
  229. {
  230. Action: upload,
  231. CustomHelpTemplate: helpTemplate,
  232. Name: "up",
  233. Usage: "uploads a file or directory to swarm using the HTTP API",
  234. ArgsUsage: "<file>",
  235. Flags: []cli.Flag{SwarmEncryptedFlag},
  236. Description: "uploads a file or directory to swarm using the HTTP API and prints the root hash",
  237. },
  238. {
  239. CustomHelpTemplate: helpTemplate,
  240. Name: "resource",
  241. Usage: "(Advanced) Create and update Mutable Resources",
  242. ArgsUsage: "<create|update|info>",
  243. Description: "Works with Mutable Resource Updates",
  244. Subcommands: []cli.Command{
  245. {
  246. Action: resourceCreate,
  247. CustomHelpTemplate: helpTemplate,
  248. Name: "create",
  249. Usage: "creates a new Mutable Resource",
  250. ArgsUsage: "<frequency>",
  251. Description: "creates a new Mutable Resource",
  252. Flags: []cli.Flag{SwarmResourceNameFlag, SwarmResourceDataOnCreateFlag, SwarmResourceMultihashFlag},
  253. },
  254. {
  255. Action: resourceUpdate,
  256. CustomHelpTemplate: helpTemplate,
  257. Name: "update",
  258. Usage: "updates the content of an existing Mutable Resource",
  259. ArgsUsage: "<Manifest Address or ENS domain> <0x Hex data>",
  260. Description: "updates the content of an existing Mutable Resource",
  261. Flags: []cli.Flag{SwarmResourceMultihashFlag},
  262. },
  263. {
  264. Action: resourceInfo,
  265. CustomHelpTemplate: helpTemplate,
  266. Name: "info",
  267. Usage: "obtains information about an existing Mutable Resource",
  268. ArgsUsage: "<Manifest Address or ENS domain>",
  269. Description: "obtains information about an existing Mutable Resource",
  270. },
  271. },
  272. },
  273. {
  274. Action: list,
  275. CustomHelpTemplate: helpTemplate,
  276. Name: "ls",
  277. Usage: "list files and directories contained in a manifest",
  278. ArgsUsage: "<manifest> [<prefix>]",
  279. Description: "Lists files and directories contained in a manifest",
  280. },
  281. {
  282. Action: hash,
  283. CustomHelpTemplate: helpTemplate,
  284. Name: "hash",
  285. Usage: "print the swarm hash of a file or directory",
  286. ArgsUsage: "<file>",
  287. Description: "Prints the swarm hash of file or directory",
  288. },
  289. {
  290. Action: download,
  291. Name: "down",
  292. Flags: []cli.Flag{SwarmRecursiveFlag},
  293. Usage: "downloads a swarm manifest or a file inside a manifest",
  294. ArgsUsage: " <uri> [<dir>]",
  295. Description: `
  296. 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.
  297. `,
  298. },
  299. {
  300. Name: "manifest",
  301. CustomHelpTemplate: helpTemplate,
  302. Usage: "perform operations on swarm manifests",
  303. ArgsUsage: "COMMAND",
  304. Description: "Updates a MANIFEST by adding/removing/updating the hash of a path.\nCOMMAND could be: add, update, remove",
  305. Subcommands: []cli.Command{
  306. {
  307. Action: manifestAdd,
  308. CustomHelpTemplate: helpTemplate,
  309. Name: "add",
  310. Usage: "add a new path to the manifest",
  311. ArgsUsage: "<MANIFEST> <path> <hash>",
  312. Description: "Adds a new path to the manifest",
  313. },
  314. {
  315. Action: manifestUpdate,
  316. CustomHelpTemplate: helpTemplate,
  317. Name: "update",
  318. Usage: "update the hash for an already existing path in the manifest",
  319. ArgsUsage: "<MANIFEST> <path> <newhash>",
  320. Description: "Update the hash for an already existing path in the manifest",
  321. },
  322. {
  323. Action: manifestRemove,
  324. CustomHelpTemplate: helpTemplate,
  325. Name: "remove",
  326. Usage: "removes a path from the manifest",
  327. ArgsUsage: "<MANIFEST> <path>",
  328. Description: "Removes a path from the manifest",
  329. },
  330. },
  331. },
  332. {
  333. Name: "fs",
  334. CustomHelpTemplate: helpTemplate,
  335. Usage: "perform FUSE operations",
  336. ArgsUsage: "fs COMMAND",
  337. 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",
  338. Subcommands: []cli.Command{
  339. {
  340. Action: mount,
  341. CustomHelpTemplate: helpTemplate,
  342. Name: "mount",
  343. Flags: []cli.Flag{utils.IPCPathFlag},
  344. Usage: "mount a swarm hash to a mount point",
  345. ArgsUsage: "swarm fs mount --ipcpath <path to bzzd.ipc> <manifest hash> <mount point>",
  346. 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",
  347. },
  348. {
  349. Action: unmount,
  350. CustomHelpTemplate: helpTemplate,
  351. Name: "unmount",
  352. Flags: []cli.Flag{utils.IPCPathFlag},
  353. Usage: "unmount a swarmfs mount",
  354. ArgsUsage: "swarm fs unmount --ipcpath <path to bzzd.ipc> <mount point>",
  355. 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",
  356. },
  357. {
  358. Action: listMounts,
  359. CustomHelpTemplate: helpTemplate,
  360. Name: "list",
  361. Flags: []cli.Flag{utils.IPCPathFlag},
  362. Usage: "list swarmfs mounts",
  363. ArgsUsage: "swarm fs list --ipcpath <path to bzzd.ipc>",
  364. 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",
  365. },
  366. },
  367. },
  368. {
  369. Name: "db",
  370. CustomHelpTemplate: helpTemplate,
  371. Usage: "manage the local chunk database",
  372. ArgsUsage: "db COMMAND",
  373. Description: "Manage the local chunk database",
  374. Subcommands: []cli.Command{
  375. {
  376. Action: dbExport,
  377. CustomHelpTemplate: helpTemplate,
  378. Name: "export",
  379. Usage: "export a local chunk database as a tar archive (use - to send to stdout)",
  380. ArgsUsage: "<chunkdb> <file>",
  381. Description: `
  382. Export a local chunk database as a tar archive (use - to send to stdout).
  383. swarm db export ~/.ethereum/swarm/bzz-KEY/chunks chunks.tar
  384. The export may be quite large, consider piping the output through the Unix
  385. pv(1) tool to get a progress bar:
  386. swarm db export ~/.ethereum/swarm/bzz-KEY/chunks - | pv > chunks.tar
  387. `,
  388. },
  389. {
  390. Action: dbImport,
  391. CustomHelpTemplate: helpTemplate,
  392. Name: "import",
  393. Usage: "import chunks from a tar archive into a local chunk database (use - to read from stdin)",
  394. ArgsUsage: "<chunkdb> <file>",
  395. Description: `
  396. Import chunks from a tar archive into a local chunk database (use - to read from stdin).
  397. swarm db import ~/.ethereum/swarm/bzz-KEY/chunks chunks.tar
  398. The import may be quite large, consider piping the input through the Unix
  399. pv(1) tool to get a progress bar:
  400. pv chunks.tar | swarm db import ~/.ethereum/swarm/bzz-KEY/chunks -
  401. `,
  402. },
  403. {
  404. Action: dbClean,
  405. CustomHelpTemplate: helpTemplate,
  406. Name: "clean",
  407. Usage: "remove corrupt entries from a local chunk database",
  408. ArgsUsage: "<chunkdb>",
  409. Description: "Remove corrupt entries from a local chunk database",
  410. },
  411. },
  412. },
  413. // See config.go
  414. DumpConfigCommand,
  415. }
  416. // append a hidden help subcommand to all commands that have subcommands
  417. // if a help command was already defined above, that one will take precedence.
  418. addDefaultHelpSubcommands(app.Commands)
  419. sort.Sort(cli.CommandsByName(app.Commands))
  420. app.Flags = []cli.Flag{
  421. utils.IdentityFlag,
  422. utils.DataDirFlag,
  423. utils.BootnodesFlag,
  424. utils.KeyStoreDirFlag,
  425. utils.ListenPortFlag,
  426. utils.NoDiscoverFlag,
  427. utils.DiscoveryV5Flag,
  428. utils.NetrestrictFlag,
  429. utils.NodeKeyFileFlag,
  430. utils.NodeKeyHexFlag,
  431. utils.MaxPeersFlag,
  432. utils.NATFlag,
  433. utils.IPCDisabledFlag,
  434. utils.IPCPathFlag,
  435. utils.PasswordFileFlag,
  436. // bzzd-specific flags
  437. CorsStringFlag,
  438. EnsAPIFlag,
  439. SwarmTomlConfigPathFlag,
  440. SwarmSwapEnabledFlag,
  441. SwarmSwapAPIFlag,
  442. SwarmSyncDisabledFlag,
  443. SwarmSyncUpdateDelay,
  444. SwarmLightNodeEnabled,
  445. SwarmDeliverySkipCheckFlag,
  446. SwarmListenAddrFlag,
  447. SwarmPortFlag,
  448. SwarmAccountFlag,
  449. SwarmNetworkIdFlag,
  450. ChequebookAddrFlag,
  451. // upload flags
  452. SwarmApiFlag,
  453. SwarmRecursiveFlag,
  454. SwarmWantManifestFlag,
  455. SwarmUploadDefaultPath,
  456. SwarmUpFromStdinFlag,
  457. SwarmUploadMimeType,
  458. // storage flags
  459. SwarmStorePath,
  460. SwarmStoreCapacity,
  461. SwarmStoreCacheCapacity,
  462. }
  463. rpcFlags := []cli.Flag{
  464. utils.WSEnabledFlag,
  465. utils.WSListenAddrFlag,
  466. utils.WSPortFlag,
  467. utils.WSApiFlag,
  468. utils.WSAllowedOriginsFlag,
  469. }
  470. app.Flags = append(app.Flags, rpcFlags...)
  471. app.Flags = append(app.Flags, debug.Flags...)
  472. app.Flags = append(app.Flags, swarmmetrics.Flags...)
  473. app.Flags = append(app.Flags, tracing.Flags...)
  474. app.Before = func(ctx *cli.Context) error {
  475. runtime.GOMAXPROCS(runtime.NumCPU())
  476. if err := debug.Setup(ctx, ""); err != nil {
  477. return err
  478. }
  479. swarmmetrics.Setup(ctx)
  480. tracing.Setup(ctx)
  481. return nil
  482. }
  483. app.After = func(ctx *cli.Context) error {
  484. debug.Exit()
  485. return nil
  486. }
  487. }
  488. func main() {
  489. if err := app.Run(os.Args); err != nil {
  490. fmt.Fprintln(os.Stderr, err)
  491. os.Exit(1)
  492. }
  493. }
  494. func version(ctx *cli.Context) error {
  495. fmt.Println(strings.Title(clientIdentifier))
  496. fmt.Println("Version:", sv.VersionWithMeta)
  497. if gitCommit != "" {
  498. fmt.Println("Git Commit:", gitCommit)
  499. }
  500. fmt.Println("Go Version:", runtime.Version())
  501. fmt.Println("OS:", runtime.GOOS)
  502. return nil
  503. }
  504. func bzzd(ctx *cli.Context) error {
  505. //build a valid bzzapi.Config from all available sources:
  506. //default config, file config, command line and env vars
  507. bzzconfig, err := buildConfig(ctx)
  508. if err != nil {
  509. utils.Fatalf("unable to configure swarm: %v", err)
  510. }
  511. cfg := defaultNodeConfig
  512. //pss operates on ws
  513. cfg.WSModules = append(cfg.WSModules, "pss")
  514. //geth only supports --datadir via command line
  515. //in order to be consistent within swarm, if we pass --datadir via environment variable
  516. //or via config file, we get the same directory for geth and swarm
  517. if _, err := os.Stat(bzzconfig.Path); err == nil {
  518. cfg.DataDir = bzzconfig.Path
  519. }
  520. //setup the ethereum node
  521. utils.SetNodeConfig(ctx, &cfg)
  522. stack, err := node.New(&cfg)
  523. if err != nil {
  524. utils.Fatalf("can't create node: %v", err)
  525. }
  526. //a few steps need to be done after the config phase is completed,
  527. //due to overriding behavior
  528. initSwarmNode(bzzconfig, stack, ctx)
  529. //register BZZ as node.Service in the ethereum node
  530. registerBzzService(bzzconfig, stack)
  531. //start the node
  532. utils.StartNode(stack)
  533. go func() {
  534. sigc := make(chan os.Signal, 1)
  535. signal.Notify(sigc, syscall.SIGTERM)
  536. defer signal.Stop(sigc)
  537. <-sigc
  538. log.Info("Got sigterm, shutting swarm down...")
  539. stack.Stop()
  540. }()
  541. // Add bootnodes as initial peers.
  542. if bzzconfig.BootNodes != "" {
  543. bootnodes := strings.Split(bzzconfig.BootNodes, ",")
  544. injectBootnodes(stack.Server(), bootnodes)
  545. } else {
  546. if bzzconfig.NetworkID == 3 {
  547. injectBootnodes(stack.Server(), testbetBootNodes)
  548. }
  549. }
  550. stack.Wait()
  551. return nil
  552. }
  553. func registerBzzService(bzzconfig *bzzapi.Config, stack *node.Node) {
  554. //define the swarm service boot function
  555. boot := func(_ *node.ServiceContext) (node.Service, error) {
  556. // In production, mockStore must be always nil.
  557. return swarm.NewSwarm(bzzconfig, nil)
  558. }
  559. //register within the ethereum node
  560. if err := stack.Register(boot); err != nil {
  561. utils.Fatalf("Failed to register the Swarm service: %v", err)
  562. }
  563. }
  564. func getAccount(bzzaccount string, ctx *cli.Context, stack *node.Node) *ecdsa.PrivateKey {
  565. //an account is mandatory
  566. if bzzaccount == "" {
  567. utils.Fatalf(SWARM_ERR_NO_BZZACCOUNT)
  568. }
  569. // Try to load the arg as a hex key file.
  570. if key, err := crypto.LoadECDSA(bzzaccount); err == nil {
  571. log.Info("Swarm account key loaded", "address", crypto.PubkeyToAddress(key.PublicKey))
  572. return key
  573. }
  574. // Otherwise try getting it from the keystore.
  575. am := stack.AccountManager()
  576. ks := am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  577. return decryptStoreAccount(ks, bzzaccount, utils.MakePasswordList(ctx))
  578. }
  579. // getPrivKey returns the private key of the specified bzzaccount
  580. // Used only by client commands, such as `resource`
  581. func getPrivKey(ctx *cli.Context) *ecdsa.PrivateKey {
  582. // booting up the swarm node just as we do in bzzd action
  583. bzzconfig, err := buildConfig(ctx)
  584. if err != nil {
  585. utils.Fatalf("unable to configure swarm: %v", err)
  586. }
  587. cfg := defaultNodeConfig
  588. if _, err := os.Stat(bzzconfig.Path); err == nil {
  589. cfg.DataDir = bzzconfig.Path
  590. }
  591. utils.SetNodeConfig(ctx, &cfg)
  592. stack, err := node.New(&cfg)
  593. if err != nil {
  594. utils.Fatalf("can't create node: %v", err)
  595. }
  596. return getAccount(bzzconfig.BzzAccount, ctx, stack)
  597. }
  598. func decryptStoreAccount(ks *keystore.KeyStore, account string, passwords []string) *ecdsa.PrivateKey {
  599. var a accounts.Account
  600. var err error
  601. if common.IsHexAddress(account) {
  602. a, err = ks.Find(accounts.Account{Address: common.HexToAddress(account)})
  603. } else if ix, ixerr := strconv.Atoi(account); ixerr == nil && ix > 0 {
  604. if accounts := ks.Accounts(); len(accounts) > ix {
  605. a = accounts[ix]
  606. } else {
  607. err = fmt.Errorf("index %d higher than number of accounts %d", ix, len(accounts))
  608. }
  609. } else {
  610. utils.Fatalf("Can't find swarm account key %s", account)
  611. }
  612. if err != nil {
  613. utils.Fatalf("Can't find swarm account key: %v - Is the provided bzzaccount(%s) from the right datadir/Path?", err, account)
  614. }
  615. keyjson, err := ioutil.ReadFile(a.URL.Path)
  616. if err != nil {
  617. utils.Fatalf("Can't load swarm account key: %v", err)
  618. }
  619. for i := 0; i < 3; i++ {
  620. password := getPassPhrase(fmt.Sprintf("Unlocking swarm account %s [%d/3]", a.Address.Hex(), i+1), i, passwords)
  621. key, err := keystore.DecryptKey(keyjson, password)
  622. if err == nil {
  623. return key.PrivateKey
  624. }
  625. }
  626. utils.Fatalf("Can't decrypt swarm account key")
  627. return nil
  628. }
  629. // getPassPhrase retrieves the password associated with bzz account, either by fetching
  630. // from a list of pre-loaded passwords, or by requesting it interactively from user.
  631. func getPassPhrase(prompt string, i int, passwords []string) string {
  632. // non-interactive
  633. if len(passwords) > 0 {
  634. if i < len(passwords) {
  635. return passwords[i]
  636. }
  637. return passwords[len(passwords)-1]
  638. }
  639. // fallback to interactive mode
  640. if prompt != "" {
  641. fmt.Println(prompt)
  642. }
  643. password, err := console.Stdin.PromptPassword("Passphrase: ")
  644. if err != nil {
  645. utils.Fatalf("Failed to read passphrase: %v", err)
  646. }
  647. return password
  648. }
  649. func injectBootnodes(srv *p2p.Server, nodes []string) {
  650. for _, url := range nodes {
  651. n, err := discover.ParseNode(url)
  652. if err != nil {
  653. log.Error("Invalid swarm bootnode", "err", err)
  654. continue
  655. }
  656. srv.AddPeer(n)
  657. }
  658. }
  659. // addDefaultHelpSubcommand scans through defined CLI commands and adds
  660. // a basic help subcommand to each
  661. // if a help command is already defined, it will take precedence over the default.
  662. func addDefaultHelpSubcommands(commands []cli.Command) {
  663. for i := range commands {
  664. cmd := &commands[i]
  665. if cmd.Subcommands != nil {
  666. cmd.Subcommands = append(cmd.Subcommands, defaultSubcommandHelp)
  667. addDefaultHelpSubcommands(cmd.Subcommands)
  668. }
  669. }
  670. }