main.go 13 KB

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