main.go 27 KB

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