main.go 11 KB

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