main.go 11 KB

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