main.go 12 KB

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