main.go 23 KB

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