main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. "strconv"
  25. "strings"
  26. "syscall"
  27. "github.com/ethereum/go-ethereum/accounts"
  28. "github.com/ethereum/go-ethereum/accounts/keystore"
  29. "github.com/ethereum/go-ethereum/cmd/utils"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/console"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/ethclient"
  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. "gopkg.in/urfave/cli.v1"
  43. )
  44. const clientIdentifier = "swarm"
  45. var (
  46. gitCommit string // Git SHA1 commit hash of the release (set via linker flags)
  47. testbetBootNodes = []string{
  48. "enode://ec8ae764f7cb0417bdfb009b9d0f18ab3818a3a4e8e7c67dd5f18971a93510a2e6f43cd0b69a27e439a9629457ea804104f37c85e41eed057d3faabbf7744cdf@13.74.157.139:30429",
  49. "enode://c2e1fceb3bf3be19dff71eec6cccf19f2dbf7567ee017d130240c670be8594bc9163353ca55dd8df7a4f161dd94b36d0615c17418b5a3cdcbb4e9d99dfa4de37@13.74.157.139:30430",
  50. "enode://fe29b82319b734ce1ec68b84657d57145fee237387e63273989d354486731e59f78858e452ef800a020559da22dcca759536e6aa5517c53930d29ce0b1029286@13.74.157.139:30431",
  51. "enode://1d7187e7bde45cf0bee489ce9852dd6d1a0d9aa67a33a6b8e6db8a4fbc6fcfa6f0f1a5419343671521b863b187d1c73bad3603bae66421d157ffef357669ddb8@13.74.157.139:30432",
  52. "enode://0e4cba800f7b1ee73673afa6a4acead4018f0149d2e3216be3f133318fd165b324cd71b81fbe1e80deac8dbf56e57a49db7be67f8b9bc81bd2b7ee496434fb5d@13.74.157.139:30433",
  53. }
  54. )
  55. var (
  56. ChequebookAddrFlag = cli.StringFlag{
  57. Name: "chequebook",
  58. Usage: "chequebook contract address",
  59. }
  60. SwarmAccountFlag = cli.StringFlag{
  61. Name: "bzzaccount",
  62. Usage: "Swarm account key file",
  63. }
  64. SwarmPortFlag = cli.StringFlag{
  65. Name: "bzzport",
  66. Usage: "Swarm local http api port",
  67. }
  68. SwarmNetworkIdFlag = cli.IntFlag{
  69. Name: "bzznetworkid",
  70. Usage: "Network identifier (integer, default 3=swarm testnet)",
  71. }
  72. SwarmConfigPathFlag = cli.StringFlag{
  73. Name: "bzzconfig",
  74. Usage: "Swarm config file path (datadir/bzz)",
  75. }
  76. SwarmSwapEnabledFlag = cli.BoolFlag{
  77. Name: "swap",
  78. Usage: "Swarm SWAP enabled (default false)",
  79. }
  80. SwarmSyncEnabledFlag = cli.BoolTFlag{
  81. Name: "sync",
  82. Usage: "Swarm Syncing enabled (default true)",
  83. }
  84. EthAPIFlag = cli.StringFlag{
  85. Name: "ethapi",
  86. Usage: "URL of the Ethereum API provider",
  87. Value: node.DefaultIPCEndpoint("geth"),
  88. }
  89. SwarmApiFlag = cli.StringFlag{
  90. Name: "bzzapi",
  91. Usage: "Swarm HTTP endpoint",
  92. Value: "http://127.0.0.1:8500",
  93. }
  94. SwarmRecursiveUploadFlag = cli.BoolFlag{
  95. Name: "recursive",
  96. Usage: "Upload directories recursively",
  97. }
  98. SwarmWantManifestFlag = cli.BoolTFlag{
  99. Name: "manifest",
  100. Usage: "Automatic manifest upload",
  101. }
  102. SwarmUploadDefaultPath = cli.StringFlag{
  103. Name: "defaultpath",
  104. Usage: "path to file served for empty url path (none)",
  105. }
  106. SwarmUpFromStdinFlag = cli.BoolFlag{
  107. Name: "stdin",
  108. Usage: "reads data to be uploaded from stdin",
  109. }
  110. SwarmUploadMimeType = cli.StringFlag{
  111. Name: "mime",
  112. Usage: "force mime type",
  113. }
  114. CorsStringFlag = cli.StringFlag{
  115. Name: "corsdomain",
  116. Usage: "Domain on which to send Access-Control-Allow-Origin header (multiple domains can be supplied separated by a ',')",
  117. }
  118. )
  119. var defaultNodeConfig = node.DefaultConfig
  120. // This init function sets defaults so cmd/swarm can run alongside geth.
  121. func init() {
  122. defaultNodeConfig.Name = clientIdentifier
  123. defaultNodeConfig.Version = params.VersionWithCommit(gitCommit)
  124. defaultNodeConfig.P2P.ListenAddr = ":30399"
  125. defaultNodeConfig.IPCPath = "bzzd.ipc"
  126. // Set flag defaults for --help display.
  127. utils.ListenPortFlag.Value = 30399
  128. }
  129. var app = utils.NewApp(gitCommit, "Ethereum Swarm")
  130. // This init function creates the cli.App.
  131. func init() {
  132. app.Action = bzzd
  133. app.HideVersion = true // we have a command to print the version
  134. app.Copyright = "Copyright 2013-2016 The go-ethereum Authors"
  135. app.Commands = []cli.Command{
  136. {
  137. Action: version,
  138. Name: "version",
  139. Usage: "Print version numbers",
  140. ArgsUsage: " ",
  141. Description: `
  142. The output of this command is supposed to be machine-readable.
  143. `,
  144. },
  145. {
  146. Action: upload,
  147. Name: "up",
  148. Usage: "upload a file or directory to swarm using the HTTP API",
  149. ArgsUsage: " <file>",
  150. Description: `
  151. "upload a file or directory to swarm using the HTTP API and prints the root hash",
  152. `,
  153. },
  154. {
  155. Action: list,
  156. Name: "ls",
  157. Usage: "list files and directories contained in a manifest",
  158. ArgsUsage: " <manifest> [<prefix>]",
  159. Description: `
  160. Lists files and directories contained in a manifest.
  161. `,
  162. },
  163. {
  164. Action: hash,
  165. Name: "hash",
  166. Usage: "print the swarm hash of a file or directory",
  167. ArgsUsage: " <file>",
  168. Description: `
  169. Prints the swarm hash of file or directory.
  170. `,
  171. },
  172. {
  173. Name: "manifest",
  174. Usage: "update a MANIFEST",
  175. ArgsUsage: "manifest COMMAND",
  176. Description: `
  177. Updates a MANIFEST by adding/removing/updating the hash of a path.
  178. `,
  179. Subcommands: []cli.Command{
  180. {
  181. Action: add,
  182. Name: "add",
  183. Usage: "add a new path to the manifest",
  184. ArgsUsage: "<MANIFEST> <path> <hash> [<content-type>]",
  185. Description: `
  186. Adds a new path to the manifest
  187. `,
  188. },
  189. {
  190. Action: update,
  191. Name: "update",
  192. Usage: "update the hash for an already existing path in the manifest",
  193. ArgsUsage: "<MANIFEST> <path> <newhash> [<newcontent-type>]",
  194. Description: `
  195. Update the hash for an already existing path in the manifest
  196. `,
  197. },
  198. {
  199. Action: remove,
  200. Name: "remove",
  201. Usage: "removes a path from the manifest",
  202. ArgsUsage: "<MANIFEST> <path>",
  203. Description: `
  204. Removes a path from the manifest
  205. `,
  206. },
  207. },
  208. },
  209. {
  210. Action: cleandb,
  211. Name: "cleandb",
  212. Usage: "Cleans database of corrupted entries",
  213. ArgsUsage: " ",
  214. Description: `
  215. Cleans database of corrupted entries.
  216. `,
  217. },
  218. }
  219. app.Flags = []cli.Flag{
  220. utils.IdentityFlag,
  221. utils.DataDirFlag,
  222. utils.BootnodesFlag,
  223. utils.KeyStoreDirFlag,
  224. utils.ListenPortFlag,
  225. utils.NoDiscoverFlag,
  226. utils.DiscoveryV5Flag,
  227. utils.NetrestrictFlag,
  228. utils.NodeKeyFileFlag,
  229. utils.NodeKeyHexFlag,
  230. utils.MaxPeersFlag,
  231. utils.NATFlag,
  232. utils.IPCDisabledFlag,
  233. utils.IPCPathFlag,
  234. utils.PasswordFileFlag,
  235. // bzzd-specific flags
  236. CorsStringFlag,
  237. EthAPIFlag,
  238. SwarmConfigPathFlag,
  239. SwarmSwapEnabledFlag,
  240. SwarmSyncEnabledFlag,
  241. SwarmPortFlag,
  242. SwarmAccountFlag,
  243. SwarmNetworkIdFlag,
  244. ChequebookAddrFlag,
  245. // upload flags
  246. SwarmApiFlag,
  247. SwarmRecursiveUploadFlag,
  248. SwarmWantManifestFlag,
  249. SwarmUploadDefaultPath,
  250. SwarmUpFromStdinFlag,
  251. SwarmUploadMimeType,
  252. }
  253. app.Flags = append(app.Flags, debug.Flags...)
  254. app.Before = func(ctx *cli.Context) error {
  255. runtime.GOMAXPROCS(runtime.NumCPU())
  256. return debug.Setup(ctx)
  257. }
  258. app.After = func(ctx *cli.Context) error {
  259. debug.Exit()
  260. return nil
  261. }
  262. }
  263. func main() {
  264. if err := app.Run(os.Args); err != nil {
  265. fmt.Fprintln(os.Stderr, err)
  266. os.Exit(1)
  267. }
  268. }
  269. func version(ctx *cli.Context) error {
  270. fmt.Println(strings.Title(clientIdentifier))
  271. fmt.Println("Version:", params.Version)
  272. if gitCommit != "" {
  273. fmt.Println("Git Commit:", gitCommit)
  274. }
  275. fmt.Println("Network Id:", ctx.GlobalInt(utils.NetworkIdFlag.Name))
  276. fmt.Println("Go Version:", runtime.Version())
  277. fmt.Println("OS:", runtime.GOOS)
  278. fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
  279. fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
  280. return nil
  281. }
  282. func bzzd(ctx *cli.Context) error {
  283. cfg := defaultNodeConfig
  284. utils.SetNodeConfig(ctx, &cfg)
  285. stack, err := node.New(&cfg)
  286. if err != nil {
  287. utils.Fatalf("can't create node: %v", err)
  288. }
  289. registerBzzService(ctx, stack)
  290. utils.StartNode(stack)
  291. go func() {
  292. sigc := make(chan os.Signal, 1)
  293. signal.Notify(sigc, syscall.SIGTERM)
  294. defer signal.Stop(sigc)
  295. <-sigc
  296. log.Info("Got sigterm, shutting swarm down...")
  297. stack.Stop()
  298. }()
  299. networkId := ctx.GlobalUint64(SwarmNetworkIdFlag.Name)
  300. // Add bootnodes as initial peers.
  301. if ctx.GlobalIsSet(utils.BootnodesFlag.Name) {
  302. bootnodes := strings.Split(ctx.GlobalString(utils.BootnodesFlag.Name), ",")
  303. injectBootnodes(stack.Server(), bootnodes)
  304. } else {
  305. if networkId == 3 {
  306. injectBootnodes(stack.Server(), testbetBootNodes)
  307. }
  308. }
  309. stack.Wait()
  310. return nil
  311. }
  312. func registerBzzService(ctx *cli.Context, stack *node.Node) {
  313. prvkey := getAccount(ctx, stack)
  314. chbookaddr := common.HexToAddress(ctx.GlobalString(ChequebookAddrFlag.Name))
  315. bzzdir := ctx.GlobalString(SwarmConfigPathFlag.Name)
  316. if bzzdir == "" {
  317. bzzdir = stack.InstanceDir()
  318. }
  319. bzzconfig, err := bzzapi.NewConfig(bzzdir, chbookaddr, prvkey, ctx.GlobalUint64(SwarmNetworkIdFlag.Name))
  320. if err != nil {
  321. utils.Fatalf("unable to configure swarm: %v", err)
  322. }
  323. bzzport := ctx.GlobalString(SwarmPortFlag.Name)
  324. if len(bzzport) > 0 {
  325. bzzconfig.Port = bzzport
  326. }
  327. swapEnabled := ctx.GlobalBool(SwarmSwapEnabledFlag.Name)
  328. syncEnabled := ctx.GlobalBoolT(SwarmSyncEnabledFlag.Name)
  329. ethapi := ctx.GlobalString(EthAPIFlag.Name)
  330. cors := ctx.GlobalString(CorsStringFlag.Name)
  331. boot := func(ctx *node.ServiceContext) (node.Service, error) {
  332. var client *ethclient.Client
  333. if len(ethapi) > 0 {
  334. client, err = ethclient.Dial(ethapi)
  335. if err != nil {
  336. utils.Fatalf("Can't connect: %v", err)
  337. }
  338. }
  339. return swarm.NewSwarm(ctx, client, bzzconfig, swapEnabled, syncEnabled, cors)
  340. }
  341. if err := stack.Register(boot); err != nil {
  342. utils.Fatalf("Failed to register the Swarm service: %v", err)
  343. }
  344. }
  345. func getAccount(ctx *cli.Context, stack *node.Node) *ecdsa.PrivateKey {
  346. keyid := ctx.GlobalString(SwarmAccountFlag.Name)
  347. if keyid == "" {
  348. utils.Fatalf("Option %q is required", SwarmAccountFlag.Name)
  349. }
  350. // Try to load the arg as a hex key file.
  351. if key, err := crypto.LoadECDSA(keyid); err == nil {
  352. log.Info("Swarm account key loaded", "address", crypto.PubkeyToAddress(key.PublicKey))
  353. return key
  354. }
  355. // Otherwise try getting it from the keystore.
  356. am := stack.AccountManager()
  357. ks := am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  358. return decryptStoreAccount(ks, keyid, utils.MakePasswordList(ctx))
  359. }
  360. func decryptStoreAccount(ks *keystore.KeyStore, account string, passwords []string) *ecdsa.PrivateKey {
  361. var a accounts.Account
  362. var err error
  363. if common.IsHexAddress(account) {
  364. a, err = ks.Find(accounts.Account{Address: common.HexToAddress(account)})
  365. } else if ix, ixerr := strconv.Atoi(account); ixerr == nil && ix > 0 {
  366. if accounts := ks.Accounts(); len(accounts) > ix {
  367. a = accounts[ix]
  368. } else {
  369. err = fmt.Errorf("index %d higher than number of accounts %d", ix, len(accounts))
  370. }
  371. } else {
  372. utils.Fatalf("Can't find swarm account key %s", account)
  373. }
  374. if err != nil {
  375. utils.Fatalf("Can't find swarm account key: %v", err)
  376. }
  377. keyjson, err := ioutil.ReadFile(a.URL.Path)
  378. if err != nil {
  379. utils.Fatalf("Can't load swarm account key: %v", err)
  380. }
  381. for i := 0; i < 3; i++ {
  382. password := getPassPhrase(fmt.Sprintf("Unlocking swarm account %s [%d/3]", a.Address.Hex(), i+1), i, passwords)
  383. key, err := keystore.DecryptKey(keyjson, password)
  384. if err == nil {
  385. return key.PrivateKey
  386. }
  387. }
  388. utils.Fatalf("Can't decrypt swarm account key")
  389. return nil
  390. }
  391. // getPassPhrase retrieves the password associated with bzz account, either by fetching
  392. // from a list of pre-loaded passwords, or by requesting it interactively from user.
  393. func getPassPhrase(prompt string, i int, passwords []string) string {
  394. // non-interactive
  395. if len(passwords) > 0 {
  396. if i < len(passwords) {
  397. return passwords[i]
  398. }
  399. return passwords[len(passwords)-1]
  400. }
  401. // fallback to interactive mode
  402. if prompt != "" {
  403. fmt.Println(prompt)
  404. }
  405. password, err := console.Stdin.PromptPassword("Passphrase: ")
  406. if err != nil {
  407. utils.Fatalf("Failed to read passphrase: %v", err)
  408. }
  409. return password
  410. }
  411. func injectBootnodes(srv *p2p.Server, nodes []string) {
  412. for _, url := range nodes {
  413. n, err := discover.ParseNode(url)
  414. if err != nil {
  415. log.Error("Invalid swarm bootnode", "err", err)
  416. continue
  417. }
  418. srv.AddPeer(n)
  419. }
  420. }