main.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. // Copyright 2018 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. // signer is a utility that can be used so sign transactions and
  17. // arbitrary data.
  18. package main
  19. import (
  20. "bufio"
  21. "context"
  22. "crypto/rand"
  23. "crypto/sha256"
  24. "encoding/hex"
  25. "encoding/json"
  26. "fmt"
  27. "io"
  28. "io/ioutil"
  29. "os"
  30. "os/signal"
  31. "os/user"
  32. "path/filepath"
  33. "runtime"
  34. "strings"
  35. "github.com/ethereum/go-ethereum/accounts/keystore"
  36. "github.com/ethereum/go-ethereum/cmd/utils"
  37. "github.com/ethereum/go-ethereum/common"
  38. "github.com/ethereum/go-ethereum/console"
  39. "github.com/ethereum/go-ethereum/crypto"
  40. "github.com/ethereum/go-ethereum/log"
  41. "github.com/ethereum/go-ethereum/node"
  42. "github.com/ethereum/go-ethereum/rpc"
  43. "github.com/ethereum/go-ethereum/signer/core"
  44. "github.com/ethereum/go-ethereum/signer/rules"
  45. "github.com/ethereum/go-ethereum/signer/storage"
  46. "gopkg.in/urfave/cli.v1"
  47. )
  48. const legalWarning = `
  49. WARNING!
  50. Clef is alpha software, and not yet publically released. This software has _not_ been audited, and there
  51. are no guarantees about the workings of this software. It may contain severe flaws. You should not use this software
  52. unless you agree to take full responsibility for doing so, and know what you are doing.
  53. TLDR; THIS IS NOT PRODUCTION-READY SOFTWARE!
  54. `
  55. var (
  56. logLevelFlag = cli.IntFlag{
  57. Name: "loglevel",
  58. Value: 4,
  59. Usage: "log level to emit to the screen",
  60. }
  61. advancedMode = cli.BoolFlag{
  62. Name: "advanced",
  63. Usage: "If enabled, issues warnings instead of rejections for suspicious requests. Default off",
  64. }
  65. keystoreFlag = cli.StringFlag{
  66. Name: "keystore",
  67. Value: filepath.Join(node.DefaultDataDir(), "keystore"),
  68. Usage: "Directory for the keystore",
  69. }
  70. configdirFlag = cli.StringFlag{
  71. Name: "configdir",
  72. Value: DefaultConfigDir(),
  73. Usage: "Directory for Clef configuration",
  74. }
  75. rpcPortFlag = cli.IntFlag{
  76. Name: "rpcport",
  77. Usage: "HTTP-RPC server listening port",
  78. Value: node.DefaultHTTPPort + 5,
  79. }
  80. signerSecretFlag = cli.StringFlag{
  81. Name: "signersecret",
  82. Usage: "A file containing the (encrypted) master seed to encrypt Clef data, e.g. keystore credentials and ruleset hash",
  83. }
  84. dBFlag = cli.StringFlag{
  85. Name: "4bytedb",
  86. Usage: "File containing 4byte-identifiers",
  87. Value: "./4byte.json",
  88. }
  89. customDBFlag = cli.StringFlag{
  90. Name: "4bytedb-custom",
  91. Usage: "File used for writing new 4byte-identifiers submitted via API",
  92. Value: "./4byte-custom.json",
  93. }
  94. auditLogFlag = cli.StringFlag{
  95. Name: "auditlog",
  96. Usage: "File used to emit audit logs. Set to \"\" to disable",
  97. Value: "audit.log",
  98. }
  99. ruleFlag = cli.StringFlag{
  100. Name: "rules",
  101. Usage: "Enable rule-engine",
  102. Value: "rules.json",
  103. }
  104. stdiouiFlag = cli.BoolFlag{
  105. Name: "stdio-ui",
  106. Usage: "Use STDIN/STDOUT as a channel for an external UI. " +
  107. "This means that an STDIN/STDOUT is used for RPC-communication with a e.g. a graphical user " +
  108. "interface, and can be used when Clef is started by an external process.",
  109. }
  110. testFlag = cli.BoolFlag{
  111. Name: "stdio-ui-test",
  112. Usage: "Mechanism to test interface between Clef and UI. Requires 'stdio-ui'.",
  113. }
  114. app = cli.NewApp()
  115. initCommand = cli.Command{
  116. Action: utils.MigrateFlags(initializeSecrets),
  117. Name: "init",
  118. Usage: "Initialize the signer, generate secret storage",
  119. ArgsUsage: "",
  120. Flags: []cli.Flag{
  121. logLevelFlag,
  122. configdirFlag,
  123. },
  124. Description: `
  125. The init command generates a master seed which Clef can use to store credentials and data needed for
  126. the rule-engine to work.`,
  127. }
  128. attestCommand = cli.Command{
  129. Action: utils.MigrateFlags(attestFile),
  130. Name: "attest",
  131. Usage: "Attest that a js-file is to be used",
  132. ArgsUsage: "<sha256sum>",
  133. Flags: []cli.Flag{
  134. logLevelFlag,
  135. configdirFlag,
  136. signerSecretFlag,
  137. },
  138. Description: `
  139. The attest command stores the sha256 of the rule.js-file that you want to use for automatic processing of
  140. incoming requests.
  141. Whenever you make an edit to the rule file, you need to use attestation to tell
  142. Clef that the file is 'safe' to execute.`,
  143. }
  144. setCredentialCommand = cli.Command{
  145. Action: utils.MigrateFlags(setCredential),
  146. Name: "setpw",
  147. Usage: "Store a credential for a keystore file",
  148. ArgsUsage: "<address>",
  149. Flags: []cli.Flag{
  150. logLevelFlag,
  151. configdirFlag,
  152. signerSecretFlag,
  153. },
  154. Description: `
  155. The setpw command stores a password for a given address (keyfile). If you enter a blank passphrase, it will
  156. remove any stored credential for that address (keyfile)
  157. `,
  158. }
  159. )
  160. func init() {
  161. app.Name = "Clef"
  162. app.Usage = "Manage Ethereum account operations"
  163. app.Flags = []cli.Flag{
  164. logLevelFlag,
  165. keystoreFlag,
  166. configdirFlag,
  167. utils.NetworkIdFlag,
  168. utils.LightKDFFlag,
  169. utils.NoUSBFlag,
  170. utils.RPCListenAddrFlag,
  171. utils.RPCVirtualHostsFlag,
  172. utils.IPCDisabledFlag,
  173. utils.IPCPathFlag,
  174. utils.RPCEnabledFlag,
  175. rpcPortFlag,
  176. signerSecretFlag,
  177. dBFlag,
  178. customDBFlag,
  179. auditLogFlag,
  180. ruleFlag,
  181. stdiouiFlag,
  182. testFlag,
  183. advancedMode,
  184. }
  185. app.Action = signer
  186. app.Commands = []cli.Command{initCommand, attestCommand, setCredentialCommand}
  187. }
  188. func main() {
  189. if err := app.Run(os.Args); err != nil {
  190. fmt.Fprintln(os.Stderr, err)
  191. os.Exit(1)
  192. }
  193. }
  194. func initializeSecrets(c *cli.Context) error {
  195. if err := initialize(c); err != nil {
  196. return err
  197. }
  198. configDir := c.GlobalString(configdirFlag.Name)
  199. masterSeed := make([]byte, 256)
  200. num, err := io.ReadFull(rand.Reader, masterSeed)
  201. if err != nil {
  202. return err
  203. }
  204. if num != len(masterSeed) {
  205. return fmt.Errorf("failed to read enough random")
  206. }
  207. n, p := keystore.StandardScryptN, keystore.StandardScryptP
  208. if c.GlobalBool(utils.LightKDFFlag.Name) {
  209. n, p = keystore.LightScryptN, keystore.LightScryptP
  210. }
  211. text := "The master seed of clef is locked with a password. Please give a password. Do not forget this password."
  212. var password string
  213. for {
  214. password = getPassPhrase(text, true)
  215. if err := core.ValidatePasswordFormat(password); err != nil {
  216. fmt.Printf("invalid password: %v\n", err)
  217. } else {
  218. break
  219. }
  220. }
  221. cipherSeed, err := encryptSeed(masterSeed, []byte(password), n, p)
  222. if err != nil {
  223. return fmt.Errorf("failed to encrypt master seed: %v", err)
  224. }
  225. err = os.Mkdir(configDir, 0700)
  226. if err != nil && !os.IsExist(err) {
  227. return err
  228. }
  229. location := filepath.Join(configDir, "masterseed.json")
  230. if _, err := os.Stat(location); err == nil {
  231. return fmt.Errorf("file %v already exists, will not overwrite", location)
  232. }
  233. err = ioutil.WriteFile(location, cipherSeed, 0400)
  234. if err != nil {
  235. return err
  236. }
  237. fmt.Printf("A master seed has been generated into %s\n", location)
  238. fmt.Printf(`
  239. This is required to be able to store credentials, such as :
  240. * Passwords for keystores (used by rule engine)
  241. * Storage for javascript rules
  242. * Hash of rule-file
  243. You should treat that file with utmost secrecy, and make a backup of it.
  244. NOTE: This file does not contain your accounts. Those need to be backed up separately!
  245. `)
  246. return nil
  247. }
  248. func attestFile(ctx *cli.Context) error {
  249. if len(ctx.Args()) < 1 {
  250. utils.Fatalf("This command requires an argument.")
  251. }
  252. if err := initialize(ctx); err != nil {
  253. return err
  254. }
  255. stretchedKey, err := readMasterKey(ctx, nil)
  256. if err != nil {
  257. utils.Fatalf(err.Error())
  258. }
  259. configDir := ctx.GlobalString(configdirFlag.Name)
  260. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  261. confKey := crypto.Keccak256([]byte("config"), stretchedKey)
  262. // Initialize the encrypted storages
  263. configStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confKey)
  264. val := ctx.Args().First()
  265. configStorage.Put("ruleset_sha256", val)
  266. log.Info("Ruleset attestation updated", "sha256", val)
  267. return nil
  268. }
  269. func setCredential(ctx *cli.Context) error {
  270. if len(ctx.Args()) < 1 {
  271. utils.Fatalf("This command requires an address to be passed as an argument.")
  272. }
  273. if err := initialize(ctx); err != nil {
  274. return err
  275. }
  276. address := ctx.Args().First()
  277. password := getPassPhrase("Enter a passphrase to store with this address.", true)
  278. stretchedKey, err := readMasterKey(ctx, nil)
  279. if err != nil {
  280. utils.Fatalf(err.Error())
  281. }
  282. configDir := ctx.GlobalString(configdirFlag.Name)
  283. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  284. pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
  285. // Initialize the encrypted storages
  286. pwStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
  287. pwStorage.Put(address, password)
  288. log.Info("Credential store updated", "key", address)
  289. return nil
  290. }
  291. func initialize(c *cli.Context) error {
  292. // Set up the logger to print everything
  293. logOutput := os.Stdout
  294. if c.GlobalBool(stdiouiFlag.Name) {
  295. logOutput = os.Stderr
  296. // If using the stdioui, we can't do the 'confirm'-flow
  297. fmt.Fprintf(logOutput, legalWarning)
  298. } else {
  299. if !confirm(legalWarning) {
  300. return fmt.Errorf("aborted by user")
  301. }
  302. }
  303. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(c.Int(logLevelFlag.Name)), log.StreamHandler(logOutput, log.TerminalFormat(true))))
  304. return nil
  305. }
  306. func signer(c *cli.Context) error {
  307. if err := initialize(c); err != nil {
  308. return err
  309. }
  310. var (
  311. ui core.SignerUI
  312. )
  313. if c.GlobalBool(stdiouiFlag.Name) {
  314. log.Info("Using stdin/stdout as UI-channel")
  315. ui = core.NewStdIOUI()
  316. } else {
  317. log.Info("Using CLI as UI-channel")
  318. ui = core.NewCommandlineUI()
  319. }
  320. fourByteDb := c.GlobalString(dBFlag.Name)
  321. fourByteLocal := c.GlobalString(customDBFlag.Name)
  322. db, err := core.NewAbiDBFromFiles(fourByteDb, fourByteLocal)
  323. if err != nil {
  324. utils.Fatalf(err.Error())
  325. }
  326. log.Info("Loaded 4byte db", "signatures", db.Size(), "file", fourByteDb, "local", fourByteLocal)
  327. var (
  328. api core.ExternalAPI
  329. )
  330. configDir := c.GlobalString(configdirFlag.Name)
  331. if stretchedKey, err := readMasterKey(c, ui); err != nil {
  332. log.Info("No master seed provided, rules disabled", "error", err)
  333. } else {
  334. if err != nil {
  335. utils.Fatalf(err.Error())
  336. }
  337. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  338. // Generate domain specific keys
  339. pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
  340. jskey := crypto.Keccak256([]byte("jsstorage"), stretchedKey)
  341. confkey := crypto.Keccak256([]byte("config"), stretchedKey)
  342. // Initialize the encrypted storages
  343. pwStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
  344. jsStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "jsstorage.json"), jskey)
  345. configStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confkey)
  346. //Do we have a rule-file?
  347. ruleJS, err := ioutil.ReadFile(c.GlobalString(ruleFlag.Name))
  348. if err != nil {
  349. log.Info("Could not load rulefile, rules not enabled", "file", "rulefile")
  350. } else {
  351. hasher := sha256.New()
  352. hasher.Write(ruleJS)
  353. shasum := hasher.Sum(nil)
  354. storedShasum := configStorage.Get("ruleset_sha256")
  355. if storedShasum != hex.EncodeToString(shasum) {
  356. log.Info("Could not validate ruleset hash, rules not enabled", "got", hex.EncodeToString(shasum), "expected", storedShasum)
  357. } else {
  358. // Initialize rules
  359. ruleEngine, err := rules.NewRuleEvaluator(ui, jsStorage, pwStorage)
  360. if err != nil {
  361. utils.Fatalf(err.Error())
  362. }
  363. ruleEngine.Init(string(ruleJS))
  364. ui = ruleEngine
  365. log.Info("Rule engine configured", "file", c.String(ruleFlag.Name))
  366. }
  367. }
  368. }
  369. apiImpl := core.NewSignerAPI(
  370. c.GlobalInt64(utils.NetworkIdFlag.Name),
  371. c.GlobalString(keystoreFlag.Name),
  372. c.GlobalBool(utils.NoUSBFlag.Name),
  373. ui, db,
  374. c.GlobalBool(utils.LightKDFFlag.Name),
  375. c.GlobalBool(advancedMode.Name))
  376. api = apiImpl
  377. // Audit logging
  378. if logfile := c.GlobalString(auditLogFlag.Name); logfile != "" {
  379. api, err = core.NewAuditLogger(logfile, api)
  380. if err != nil {
  381. utils.Fatalf(err.Error())
  382. }
  383. log.Info("Audit logs configured", "file", logfile)
  384. }
  385. // register signer API with server
  386. var (
  387. extapiURL = "n/a"
  388. ipcapiURL = "n/a"
  389. )
  390. rpcAPI := []rpc.API{
  391. {
  392. Namespace: "account",
  393. Public: true,
  394. Service: api,
  395. Version: "1.0"},
  396. }
  397. if c.GlobalBool(utils.RPCEnabledFlag.Name) {
  398. vhosts := splitAndTrim(c.GlobalString(utils.RPCVirtualHostsFlag.Name))
  399. cors := splitAndTrim(c.GlobalString(utils.RPCCORSDomainFlag.Name))
  400. // start http server
  401. httpEndpoint := fmt.Sprintf("%s:%d", c.GlobalString(utils.RPCListenAddrFlag.Name), c.Int(rpcPortFlag.Name))
  402. listener, _, err := rpc.StartHTTPEndpoint(httpEndpoint, rpcAPI, []string{"account"}, cors, vhosts, rpc.DefaultHTTPTimeouts)
  403. if err != nil {
  404. utils.Fatalf("Could not start RPC api: %v", err)
  405. }
  406. extapiURL = fmt.Sprintf("http://%s", httpEndpoint)
  407. log.Info("HTTP endpoint opened", "url", extapiURL)
  408. defer func() {
  409. listener.Close()
  410. log.Info("HTTP endpoint closed", "url", httpEndpoint)
  411. }()
  412. }
  413. if !c.GlobalBool(utils.IPCDisabledFlag.Name) {
  414. if c.IsSet(utils.IPCPathFlag.Name) {
  415. ipcapiURL = c.GlobalString(utils.IPCPathFlag.Name)
  416. } else {
  417. ipcapiURL = filepath.Join(configDir, "clef.ipc")
  418. }
  419. listener, _, err := rpc.StartIPCEndpoint(ipcapiURL, rpcAPI)
  420. if err != nil {
  421. utils.Fatalf("Could not start IPC api: %v", err)
  422. }
  423. log.Info("IPC endpoint opened", "url", ipcapiURL)
  424. defer func() {
  425. listener.Close()
  426. log.Info("IPC endpoint closed", "url", ipcapiURL)
  427. }()
  428. }
  429. if c.GlobalBool(testFlag.Name) {
  430. log.Info("Performing UI test")
  431. go testExternalUI(apiImpl)
  432. }
  433. ui.OnSignerStartup(core.StartupInfo{
  434. Info: map[string]interface{}{
  435. "extapi_version": core.ExternalAPIVersion,
  436. "intapi_version": core.InternalAPIVersion,
  437. "extapi_http": extapiURL,
  438. "extapi_ipc": ipcapiURL,
  439. },
  440. })
  441. abortChan := make(chan os.Signal)
  442. signal.Notify(abortChan, os.Interrupt)
  443. sig := <-abortChan
  444. log.Info("Exiting...", "signal", sig)
  445. return nil
  446. }
  447. // splitAndTrim splits input separated by a comma
  448. // and trims excessive white space from the substrings.
  449. func splitAndTrim(input string) []string {
  450. result := strings.Split(input, ",")
  451. for i, r := range result {
  452. result[i] = strings.TrimSpace(r)
  453. }
  454. return result
  455. }
  456. // DefaultConfigDir is the default config directory to use for the vaults and other
  457. // persistence requirements.
  458. func DefaultConfigDir() string {
  459. // Try to place the data folder in the user's home dir
  460. home := homeDir()
  461. if home != "" {
  462. if runtime.GOOS == "darwin" {
  463. return filepath.Join(home, "Library", "Signer")
  464. } else if runtime.GOOS == "windows" {
  465. return filepath.Join(home, "AppData", "Roaming", "Signer")
  466. } else {
  467. return filepath.Join(home, ".clef")
  468. }
  469. }
  470. // As we cannot guess a stable location, return empty and handle later
  471. return ""
  472. }
  473. func homeDir() string {
  474. if home := os.Getenv("HOME"); home != "" {
  475. return home
  476. }
  477. if usr, err := user.Current(); err == nil {
  478. return usr.HomeDir
  479. }
  480. return ""
  481. }
  482. func readMasterKey(ctx *cli.Context, ui core.SignerUI) ([]byte, error) {
  483. var (
  484. file string
  485. configDir = ctx.GlobalString(configdirFlag.Name)
  486. )
  487. if ctx.GlobalIsSet(signerSecretFlag.Name) {
  488. file = ctx.GlobalString(signerSecretFlag.Name)
  489. } else {
  490. file = filepath.Join(configDir, "masterseed.json")
  491. }
  492. if err := checkFile(file); err != nil {
  493. return nil, err
  494. }
  495. cipherKey, err := ioutil.ReadFile(file)
  496. if err != nil {
  497. return nil, err
  498. }
  499. var password string
  500. // If ui is not nil, get the password from ui.
  501. if ui != nil {
  502. resp, err := ui.OnInputRequired(core.UserInputRequest{
  503. Title: "Master Password",
  504. Prompt: "Please enter the password to decrypt the master seed",
  505. IsPassword: true})
  506. if err != nil {
  507. return nil, err
  508. }
  509. password = resp.Text
  510. } else {
  511. password = getPassPhrase("Decrypt master seed of clef", false)
  512. }
  513. masterSeed, err := decryptSeed(cipherKey, password)
  514. if err != nil {
  515. return nil, fmt.Errorf("failed to decrypt the master seed of clef")
  516. }
  517. if len(masterSeed) < 256 {
  518. return nil, fmt.Errorf("master seed of insufficient length, expected >255 bytes, got %d", len(masterSeed))
  519. }
  520. // Create vault location
  521. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), masterSeed)[:10]))
  522. err = os.Mkdir(vaultLocation, 0700)
  523. if err != nil && !os.IsExist(err) {
  524. return nil, err
  525. }
  526. return masterSeed, nil
  527. }
  528. // checkFile is a convenience function to check if a file
  529. // * exists
  530. // * is mode 0400
  531. func checkFile(filename string) error {
  532. info, err := os.Stat(filename)
  533. if err != nil {
  534. return fmt.Errorf("failed stat on %s: %v", filename, err)
  535. }
  536. // Check the unix permission bits
  537. if info.Mode().Perm()&0377 != 0 {
  538. return fmt.Errorf("file (%v) has insecure file permissions (%v)", filename, info.Mode().String())
  539. }
  540. return nil
  541. }
  542. // confirm displays a text and asks for user confirmation
  543. func confirm(text string) bool {
  544. fmt.Printf(text)
  545. fmt.Printf("\nEnter 'ok' to proceed:\n>")
  546. text, err := bufio.NewReader(os.Stdin).ReadString('\n')
  547. if err != nil {
  548. log.Crit("Failed to read user input", "err", err)
  549. }
  550. if text := strings.TrimSpace(text); text == "ok" {
  551. return true
  552. }
  553. return false
  554. }
  555. func testExternalUI(api *core.SignerAPI) {
  556. ctx := context.WithValue(context.Background(), "remote", "clef binary")
  557. ctx = context.WithValue(ctx, "scheme", "in-proc")
  558. ctx = context.WithValue(ctx, "local", "main")
  559. errs := make([]string, 0)
  560. api.UI.ShowInfo("Testing 'ShowInfo'")
  561. api.UI.ShowError("Testing 'ShowError'")
  562. checkErr := func(method string, err error) {
  563. if err != nil && err != core.ErrRequestDenied {
  564. errs = append(errs, fmt.Sprintf("%v: %v", method, err.Error()))
  565. }
  566. }
  567. var err error
  568. _, err = api.SignTransaction(ctx, core.SendTxArgs{From: common.MixedcaseAddress{}}, nil)
  569. checkErr("SignTransaction", err)
  570. _, err = api.Sign(ctx, common.MixedcaseAddress{}, common.Hex2Bytes("01020304"))
  571. checkErr("Sign", err)
  572. _, err = api.List(ctx)
  573. checkErr("List", err)
  574. _, err = api.New(ctx)
  575. checkErr("New", err)
  576. _, err = api.Export(ctx, common.Address{})
  577. checkErr("Export", err)
  578. _, err = api.Import(ctx, json.RawMessage{})
  579. checkErr("Import", err)
  580. api.UI.ShowInfo("Tests completed")
  581. if len(errs) > 0 {
  582. log.Error("Got errors")
  583. for _, e := range errs {
  584. log.Error(e)
  585. }
  586. } else {
  587. log.Info("No errors")
  588. }
  589. }
  590. // getPassPhrase retrieves the password associated with clef, either fetched
  591. // from a list of preloaded passphrases, or requested interactively from the user.
  592. // TODO: there are many `getPassPhrase` functions, it will be better to abstract them into one.
  593. func getPassPhrase(prompt string, confirmation bool) string {
  594. fmt.Println(prompt)
  595. password, err := console.Stdin.PromptPassword("Passphrase: ")
  596. if err != nil {
  597. utils.Fatalf("Failed to read passphrase: %v", err)
  598. }
  599. if confirmation {
  600. confirm, err := console.Stdin.PromptPassword("Repeat passphrase: ")
  601. if err != nil {
  602. utils.Fatalf("Failed to read passphrase confirmation: %v", err)
  603. }
  604. if password != confirm {
  605. utils.Fatalf("Passphrases do not match")
  606. }
  607. }
  608. return password
  609. }
  610. type encryptedSeedStorage struct {
  611. Description string `json:"description"`
  612. Version int `json:"version"`
  613. Params keystore.CryptoJSON `json:"params"`
  614. }
  615. // encryptSeed uses a similar scheme as the keystore uses, but with a different wrapping,
  616. // to encrypt the master seed
  617. func encryptSeed(seed []byte, auth []byte, scryptN, scryptP int) ([]byte, error) {
  618. cryptoStruct, err := keystore.EncryptDataV3(seed, auth, scryptN, scryptP)
  619. if err != nil {
  620. return nil, err
  621. }
  622. return json.Marshal(&encryptedSeedStorage{"Clef seed", 1, cryptoStruct})
  623. }
  624. // decryptSeed decrypts the master seed
  625. func decryptSeed(keyjson []byte, auth string) ([]byte, error) {
  626. var encSeed encryptedSeedStorage
  627. if err := json.Unmarshal(keyjson, &encSeed); err != nil {
  628. return nil, err
  629. }
  630. if encSeed.Version != 1 {
  631. log.Warn(fmt.Sprintf("unsupported encryption format of seed: %d, operation will likely fail", encSeed.Version))
  632. }
  633. seed, err := keystore.DecryptDataV3(encSeed.Params, auth)
  634. if err != nil {
  635. return nil, err
  636. }
  637. return seed, err
  638. }
  639. /**
  640. //Create Account
  641. curl -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_new","params":["test"],"id":67}' localhost:8550
  642. // List accounts
  643. curl -i -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_list","params":[""],"id":67}' http://localhost:8550/
  644. // Make Transaction
  645. // safeSend(0x12)
  646. // 4401a6e40000000000000000000000000000000000000000000000000000000000000012
  647. // supplied abi
  648. curl -i -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_signTransaction","params":[{"from":"0x82A2A876D39022B3019932D30Cd9c97ad5616813","gas":"0x333","gasPrice":"0x123","nonce":"0x0","to":"0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value":"0x10", "data":"0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"},"test"],"id":67}' http://localhost:8550/
  649. // Not supplied
  650. curl -i -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_signTransaction","params":[{"from":"0x82A2A876D39022B3019932D30Cd9c97ad5616813","gas":"0x333","gasPrice":"0x123","nonce":"0x0","to":"0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value":"0x10", "data":"0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"}],"id":67}' http://localhost:8550/
  651. // Sign data
  652. curl -i -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_sign","params":["0x694267f14675d7e1b9494fd8d72fefe1755710fa","bazonk gaz baz"],"id":67}' http://localhost:8550/
  653. **/