main.go 23 KB

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