main.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. package main
  17. import (
  18. "bufio"
  19. "context"
  20. "crypto/rand"
  21. "crypto/sha256"
  22. "encoding/hex"
  23. "encoding/json"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "math/big"
  28. "os"
  29. "os/signal"
  30. "os/user"
  31. "path/filepath"
  32. "runtime"
  33. "strings"
  34. "time"
  35. "github.com/ethereum/go-ethereum/accounts"
  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/common/hexutil"
  40. "github.com/ethereum/go-ethereum/core/types"
  41. "github.com/ethereum/go-ethereum/crypto"
  42. "github.com/ethereum/go-ethereum/internal/ethapi"
  43. "github.com/ethereum/go-ethereum/log"
  44. "github.com/ethereum/go-ethereum/node"
  45. "github.com/ethereum/go-ethereum/params"
  46. "github.com/ethereum/go-ethereum/rlp"
  47. "github.com/ethereum/go-ethereum/rpc"
  48. "github.com/ethereum/go-ethereum/signer/core"
  49. "github.com/ethereum/go-ethereum/signer/fourbyte"
  50. "github.com/ethereum/go-ethereum/signer/rules"
  51. "github.com/ethereum/go-ethereum/signer/storage"
  52. colorable "github.com/mattn/go-colorable"
  53. "github.com/mattn/go-isatty"
  54. "gopkg.in/urfave/cli.v1"
  55. )
  56. const legalWarning = `
  57. WARNING!
  58. Clef is an account management tool. It may, like any software, contain bugs.
  59. Please take care to
  60. - backup your keystore files,
  61. - verify that the keystore(s) can be opened with your password.
  62. Clef is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
  63. without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  64. PURPOSE. See the GNU General Public License for more details.
  65. `
  66. var (
  67. logLevelFlag = cli.IntFlag{
  68. Name: "loglevel",
  69. Value: 4,
  70. Usage: "log level to emit to the screen",
  71. }
  72. advancedMode = cli.BoolFlag{
  73. Name: "advanced",
  74. Usage: "If enabled, issues warnings instead of rejections for suspicious requests. Default off",
  75. }
  76. acceptFlag = cli.BoolFlag{
  77. Name: "suppress-bootwarn",
  78. Usage: "If set, does not show the warning during boot",
  79. }
  80. keystoreFlag = cli.StringFlag{
  81. Name: "keystore",
  82. Value: filepath.Join(node.DefaultDataDir(), "keystore"),
  83. Usage: "Directory for the keystore",
  84. }
  85. configdirFlag = cli.StringFlag{
  86. Name: "configdir",
  87. Value: DefaultConfigDir(),
  88. Usage: "Directory for Clef configuration",
  89. }
  90. chainIdFlag = cli.Int64Flag{
  91. Name: "chainid",
  92. Value: params.MainnetChainConfig.ChainID.Int64(),
  93. Usage: "Chain id to use for signing (1=mainnet, 3=Ropsten, 4=Rinkeby, 5=Goerli)",
  94. }
  95. rpcPortFlag = cli.IntFlag{
  96. Name: "rpcport",
  97. Usage: "HTTP-RPC server listening port",
  98. Value: node.DefaultHTTPPort + 5,
  99. }
  100. signerSecretFlag = cli.StringFlag{
  101. Name: "signersecret",
  102. Usage: "A file containing the (encrypted) master seed to encrypt Clef data, e.g. keystore credentials and ruleset hash",
  103. }
  104. customDBFlag = cli.StringFlag{
  105. Name: "4bytedb-custom",
  106. Usage: "File used for writing new 4byte-identifiers submitted via API",
  107. Value: "./4byte-custom.json",
  108. }
  109. auditLogFlag = cli.StringFlag{
  110. Name: "auditlog",
  111. Usage: "File used to emit audit logs. Set to \"\" to disable",
  112. Value: "audit.log",
  113. }
  114. ruleFlag = cli.StringFlag{
  115. Name: "rules",
  116. Usage: "Path to the rule file to auto-authorize requests with",
  117. }
  118. stdiouiFlag = cli.BoolFlag{
  119. Name: "stdio-ui",
  120. Usage: "Use STDIN/STDOUT as a channel for an external UI. " +
  121. "This means that an STDIN/STDOUT is used for RPC-communication with a e.g. a graphical user " +
  122. "interface, and can be used when Clef is started by an external process.",
  123. }
  124. testFlag = cli.BoolFlag{
  125. Name: "stdio-ui-test",
  126. Usage: "Mechanism to test interface between Clef and UI. Requires 'stdio-ui'.",
  127. }
  128. app = cli.NewApp()
  129. initCommand = cli.Command{
  130. Action: utils.MigrateFlags(initializeSecrets),
  131. Name: "init",
  132. Usage: "Initialize the signer, generate secret storage",
  133. ArgsUsage: "",
  134. Flags: []cli.Flag{
  135. logLevelFlag,
  136. configdirFlag,
  137. },
  138. Description: `
  139. The init command generates a master seed which Clef can use to store credentials and data needed for
  140. the rule-engine to work.`,
  141. }
  142. attestCommand = cli.Command{
  143. Action: utils.MigrateFlags(attestFile),
  144. Name: "attest",
  145. Usage: "Attest that a js-file is to be used",
  146. ArgsUsage: "<sha256sum>",
  147. Flags: []cli.Flag{
  148. logLevelFlag,
  149. configdirFlag,
  150. signerSecretFlag,
  151. },
  152. Description: `
  153. The attest command stores the sha256 of the rule.js-file that you want to use for automatic processing of
  154. incoming requests.
  155. Whenever you make an edit to the rule file, you need to use attestation to tell
  156. Clef that the file is 'safe' to execute.`,
  157. }
  158. setCredentialCommand = cli.Command{
  159. Action: utils.MigrateFlags(setCredential),
  160. Name: "setpw",
  161. Usage: "Store a credential for a keystore file",
  162. ArgsUsage: "<address>",
  163. Flags: []cli.Flag{
  164. logLevelFlag,
  165. configdirFlag,
  166. signerSecretFlag,
  167. },
  168. Description: `
  169. The setpw command stores a password for a given address (keyfile).
  170. `}
  171. delCredentialCommand = cli.Command{
  172. Action: utils.MigrateFlags(removeCredential),
  173. Name: "delpw",
  174. Usage: "Remove a credential for a keystore file",
  175. ArgsUsage: "<address>",
  176. Flags: []cli.Flag{
  177. logLevelFlag,
  178. configdirFlag,
  179. signerSecretFlag,
  180. },
  181. Description: `
  182. The delpw command removes a password for a given address (keyfile).
  183. `}
  184. newAccountCommand = cli.Command{
  185. Action: utils.MigrateFlags(newAccount),
  186. Name: "newaccount",
  187. Usage: "Create a new account",
  188. ArgsUsage: "",
  189. Flags: []cli.Flag{
  190. logLevelFlag,
  191. keystoreFlag,
  192. utils.LightKDFFlag,
  193. acceptFlag,
  194. },
  195. Description: `
  196. The newaccount command creates a new keystore-backed account. It is a convenience-method
  197. which can be used in lieu of an external UI.`,
  198. }
  199. gendocCommand = cli.Command{
  200. Action: GenDoc,
  201. Name: "gendoc",
  202. Usage: "Generate documentation about json-rpc format",
  203. Description: `
  204. The gendoc generates example structures of the json-rpc communication types.
  205. `}
  206. )
  207. func init() {
  208. app.Name = "Clef"
  209. app.Usage = "Manage Ethereum account operations"
  210. app.Flags = []cli.Flag{
  211. logLevelFlag,
  212. keystoreFlag,
  213. configdirFlag,
  214. chainIdFlag,
  215. utils.LightKDFFlag,
  216. utils.NoUSBFlag,
  217. utils.SmartCardDaemonPathFlag,
  218. utils.HTTPListenAddrFlag,
  219. utils.HTTPVirtualHostsFlag,
  220. utils.IPCDisabledFlag,
  221. utils.IPCPathFlag,
  222. utils.HTTPEnabledFlag,
  223. rpcPortFlag,
  224. signerSecretFlag,
  225. customDBFlag,
  226. auditLogFlag,
  227. ruleFlag,
  228. stdiouiFlag,
  229. testFlag,
  230. advancedMode,
  231. acceptFlag,
  232. }
  233. app.Action = signer
  234. app.Commands = []cli.Command{initCommand,
  235. attestCommand,
  236. setCredentialCommand,
  237. delCredentialCommand,
  238. newAccountCommand,
  239. gendocCommand}
  240. cli.CommandHelpTemplate = utils.OriginCommandHelpTemplate
  241. }
  242. func main() {
  243. if err := app.Run(os.Args); err != nil {
  244. fmt.Fprintln(os.Stderr, err)
  245. os.Exit(1)
  246. }
  247. }
  248. func initializeSecrets(c *cli.Context) error {
  249. // Get past the legal message
  250. if err := initialize(c); err != nil {
  251. return err
  252. }
  253. // Ensure the master key does not yet exist, we're not willing to overwrite
  254. configDir := c.GlobalString(configdirFlag.Name)
  255. if err := os.Mkdir(configDir, 0700); err != nil && !os.IsExist(err) {
  256. return err
  257. }
  258. location := filepath.Join(configDir, "masterseed.json")
  259. if _, err := os.Stat(location); err == nil {
  260. return fmt.Errorf("master key %v already exists, will not overwrite", location)
  261. }
  262. // Key file does not exist yet, generate a new one and encrypt it
  263. masterSeed := make([]byte, 256)
  264. num, err := io.ReadFull(rand.Reader, masterSeed)
  265. if err != nil {
  266. return err
  267. }
  268. if num != len(masterSeed) {
  269. return fmt.Errorf("failed to read enough random")
  270. }
  271. n, p := keystore.StandardScryptN, keystore.StandardScryptP
  272. if c.GlobalBool(utils.LightKDFFlag.Name) {
  273. n, p = keystore.LightScryptN, keystore.LightScryptP
  274. }
  275. text := "The master seed of clef will be locked with a password.\nPlease specify a password. Do not forget this password!"
  276. var password string
  277. for {
  278. password = utils.GetPassPhrase(text, true)
  279. if err := core.ValidatePasswordFormat(password); err != nil {
  280. fmt.Printf("invalid password: %v\n", err)
  281. } else {
  282. fmt.Println()
  283. break
  284. }
  285. }
  286. cipherSeed, err := encryptSeed(masterSeed, []byte(password), n, p)
  287. if err != nil {
  288. return fmt.Errorf("failed to encrypt master seed: %v", err)
  289. }
  290. // Double check the master key path to ensure nothing wrote there in between
  291. if err = os.Mkdir(configDir, 0700); err != nil && !os.IsExist(err) {
  292. return err
  293. }
  294. if _, err := os.Stat(location); err == nil {
  295. return fmt.Errorf("master key %v already exists, will not overwrite", location)
  296. }
  297. // Write the file and print the usual warning message
  298. if err = ioutil.WriteFile(location, cipherSeed, 0400); err != nil {
  299. return err
  300. }
  301. fmt.Printf("A master seed has been generated into %s\n", location)
  302. fmt.Printf(`
  303. This is required to be able to store credentials, such as:
  304. * Passwords for keystores (used by rule engine)
  305. * Storage for JavaScript auto-signing rules
  306. * Hash of JavaScript rule-file
  307. You should treat 'masterseed.json' with utmost secrecy and make a backup of it!
  308. * The password is necessary but not enough, you need to back up the master seed too!
  309. * The master seed does not contain your accounts, those need to be backed up separately!
  310. `)
  311. return nil
  312. }
  313. func attestFile(ctx *cli.Context) error {
  314. if len(ctx.Args()) < 1 {
  315. utils.Fatalf("This command requires an argument.")
  316. }
  317. if err := initialize(ctx); err != nil {
  318. return err
  319. }
  320. stretchedKey, err := readMasterKey(ctx, nil)
  321. if err != nil {
  322. utils.Fatalf(err.Error())
  323. }
  324. configDir := ctx.GlobalString(configdirFlag.Name)
  325. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  326. confKey := crypto.Keccak256([]byte("config"), stretchedKey)
  327. // Initialize the encrypted storages
  328. configStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confKey)
  329. val := ctx.Args().First()
  330. configStorage.Put("ruleset_sha256", val)
  331. log.Info("Ruleset attestation updated", "sha256", val)
  332. return nil
  333. }
  334. func setCredential(ctx *cli.Context) error {
  335. if len(ctx.Args()) < 1 {
  336. utils.Fatalf("This command requires an address to be passed as an argument")
  337. }
  338. if err := initialize(ctx); err != nil {
  339. return err
  340. }
  341. addr := ctx.Args().First()
  342. if !common.IsHexAddress(addr) {
  343. utils.Fatalf("Invalid address specified: %s", addr)
  344. }
  345. address := common.HexToAddress(addr)
  346. password := utils.GetPassPhrase("Please enter a password to store for this address:", true)
  347. fmt.Println()
  348. stretchedKey, err := readMasterKey(ctx, nil)
  349. if err != nil {
  350. utils.Fatalf(err.Error())
  351. }
  352. configDir := ctx.GlobalString(configdirFlag.Name)
  353. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  354. pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
  355. pwStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
  356. pwStorage.Put(address.Hex(), password)
  357. log.Info("Credential store updated", "set", address)
  358. return nil
  359. }
  360. func removeCredential(ctx *cli.Context) error {
  361. if len(ctx.Args()) < 1 {
  362. utils.Fatalf("This command requires an address to be passed as an argument")
  363. }
  364. if err := initialize(ctx); err != nil {
  365. return err
  366. }
  367. addr := ctx.Args().First()
  368. if !common.IsHexAddress(addr) {
  369. utils.Fatalf("Invalid address specified: %s", addr)
  370. }
  371. address := common.HexToAddress(addr)
  372. stretchedKey, err := readMasterKey(ctx, nil)
  373. if err != nil {
  374. utils.Fatalf(err.Error())
  375. }
  376. configDir := ctx.GlobalString(configdirFlag.Name)
  377. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  378. pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
  379. pwStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
  380. pwStorage.Del(address.Hex())
  381. log.Info("Credential store updated", "unset", address)
  382. return nil
  383. }
  384. func newAccount(c *cli.Context) error {
  385. if err := initialize(c); err != nil {
  386. return err
  387. }
  388. // The newaccount is meant for users using the CLI, since 'real' external
  389. // UIs can use the UI-api instead. So we'll just use the native CLI UI here.
  390. var (
  391. ui = core.NewCommandlineUI()
  392. pwStorage storage.Storage = &storage.NoStorage{}
  393. ksLoc = c.GlobalString(keystoreFlag.Name)
  394. lightKdf = c.GlobalBool(utils.LightKDFFlag.Name)
  395. )
  396. log.Info("Starting clef", "keystore", ksLoc, "light-kdf", lightKdf)
  397. am := core.StartClefAccountManager(ksLoc, true, lightKdf, "")
  398. // This gives is us access to the external API
  399. apiImpl := core.NewSignerAPI(am, 0, true, ui, nil, false, pwStorage)
  400. // This gives us access to the internal API
  401. internalApi := core.NewUIServerAPI(apiImpl)
  402. addr, err := internalApi.New(context.Background())
  403. if err == nil {
  404. fmt.Printf("Generated account %v\n", addr.String())
  405. }
  406. return err
  407. }
  408. func initialize(c *cli.Context) error {
  409. // Set up the logger to print everything
  410. logOutput := os.Stdout
  411. if c.GlobalBool(stdiouiFlag.Name) {
  412. logOutput = os.Stderr
  413. // If using the stdioui, we can't do the 'confirm'-flow
  414. if !c.GlobalBool(acceptFlag.Name) {
  415. fmt.Fprint(logOutput, legalWarning)
  416. }
  417. } else if !c.GlobalBool(acceptFlag.Name) {
  418. if !confirm(legalWarning) {
  419. return fmt.Errorf("aborted by user")
  420. }
  421. fmt.Println()
  422. }
  423. usecolor := (isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb"
  424. output := io.Writer(logOutput)
  425. if usecolor {
  426. output = colorable.NewColorable(logOutput)
  427. }
  428. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(c.Int(logLevelFlag.Name)), log.StreamHandler(output, log.TerminalFormat(usecolor))))
  429. return nil
  430. }
  431. // ipcEndpoint resolves an IPC endpoint based on a configured value, taking into
  432. // account the set data folders as well as the designated platform we're currently
  433. // running on.
  434. func ipcEndpoint(ipcPath, datadir string) string {
  435. // On windows we can only use plain top-level pipes
  436. if runtime.GOOS == "windows" {
  437. if strings.HasPrefix(ipcPath, `\\.\pipe\`) {
  438. return ipcPath
  439. }
  440. return `\\.\pipe\` + ipcPath
  441. }
  442. // Resolve names into the data directory full paths otherwise
  443. if filepath.Base(ipcPath) == ipcPath {
  444. if datadir == "" {
  445. return filepath.Join(os.TempDir(), ipcPath)
  446. }
  447. return filepath.Join(datadir, ipcPath)
  448. }
  449. return ipcPath
  450. }
  451. func signer(c *cli.Context) error {
  452. // If we have some unrecognized command, bail out
  453. if args := c.Args(); len(args) > 0 {
  454. return fmt.Errorf("invalid command: %q", args[0])
  455. }
  456. if err := initialize(c); err != nil {
  457. return err
  458. }
  459. var (
  460. ui core.UIClientAPI
  461. )
  462. if c.GlobalBool(stdiouiFlag.Name) {
  463. log.Info("Using stdin/stdout as UI-channel")
  464. ui = core.NewStdIOUI()
  465. } else {
  466. log.Info("Using CLI as UI-channel")
  467. ui = core.NewCommandlineUI()
  468. }
  469. // 4bytedb data
  470. fourByteLocal := c.GlobalString(customDBFlag.Name)
  471. db, err := fourbyte.NewWithFile(fourByteLocal)
  472. if err != nil {
  473. utils.Fatalf(err.Error())
  474. }
  475. embeds, locals := db.Size()
  476. log.Info("Loaded 4byte database", "embeds", embeds, "locals", locals, "local", fourByteLocal)
  477. var (
  478. api core.ExternalAPI
  479. pwStorage storage.Storage = &storage.NoStorage{}
  480. )
  481. configDir := c.GlobalString(configdirFlag.Name)
  482. if stretchedKey, err := readMasterKey(c, ui); err != nil {
  483. log.Warn("Failed to open master, rules disabled", "err", err)
  484. } else {
  485. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
  486. // Generate domain specific keys
  487. pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
  488. jskey := crypto.Keccak256([]byte("jsstorage"), stretchedKey)
  489. confkey := crypto.Keccak256([]byte("config"), stretchedKey)
  490. // Initialize the encrypted storages
  491. pwStorage = storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
  492. jsStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "jsstorage.json"), jskey)
  493. configStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confkey)
  494. // Do we have a rule-file?
  495. if ruleFile := c.GlobalString(ruleFlag.Name); ruleFile != "" {
  496. ruleJS, err := ioutil.ReadFile(ruleFile)
  497. if err != nil {
  498. log.Warn("Could not load rules, disabling", "file", ruleFile, "err", err)
  499. } else {
  500. shasum := sha256.Sum256(ruleJS)
  501. foundShaSum := hex.EncodeToString(shasum[:])
  502. storedShasum, _ := configStorage.Get("ruleset_sha256")
  503. if storedShasum != foundShaSum {
  504. log.Warn("Rule hash not attested, disabling", "hash", foundShaSum, "attested", storedShasum)
  505. } else {
  506. // Initialize rules
  507. ruleEngine, err := rules.NewRuleEvaluator(ui, jsStorage)
  508. if err != nil {
  509. utils.Fatalf(err.Error())
  510. }
  511. ruleEngine.Init(string(ruleJS))
  512. ui = ruleEngine
  513. log.Info("Rule engine configured", "file", c.String(ruleFlag.Name))
  514. }
  515. }
  516. }
  517. }
  518. var (
  519. chainId = c.GlobalInt64(chainIdFlag.Name)
  520. ksLoc = c.GlobalString(keystoreFlag.Name)
  521. lightKdf = c.GlobalBool(utils.LightKDFFlag.Name)
  522. advanced = c.GlobalBool(advancedMode.Name)
  523. nousb = c.GlobalBool(utils.NoUSBFlag.Name)
  524. scpath = c.GlobalString(utils.SmartCardDaemonPathFlag.Name)
  525. )
  526. log.Info("Starting signer", "chainid", chainId, "keystore", ksLoc,
  527. "light-kdf", lightKdf, "advanced", advanced)
  528. am := core.StartClefAccountManager(ksLoc, nousb, lightKdf, scpath)
  529. apiImpl := core.NewSignerAPI(am, chainId, nousb, ui, db, advanced, pwStorage)
  530. // Establish the bidirectional communication, by creating a new UI backend and registering
  531. // it with the UI.
  532. ui.RegisterUIServer(core.NewUIServerAPI(apiImpl))
  533. api = apiImpl
  534. // Audit logging
  535. if logfile := c.GlobalString(auditLogFlag.Name); logfile != "" {
  536. api, err = core.NewAuditLogger(logfile, api)
  537. if err != nil {
  538. utils.Fatalf(err.Error())
  539. }
  540. log.Info("Audit logs configured", "file", logfile)
  541. }
  542. // register signer API with server
  543. var (
  544. extapiURL = "n/a"
  545. ipcapiURL = "n/a"
  546. )
  547. rpcAPI := []rpc.API{
  548. {
  549. Namespace: "account",
  550. Public: true,
  551. Service: api,
  552. Version: "1.0"},
  553. }
  554. if c.GlobalBool(utils.HTTPEnabledFlag.Name) {
  555. vhosts := splitAndTrim(c.GlobalString(utils.HTTPVirtualHostsFlag.Name))
  556. cors := splitAndTrim(c.GlobalString(utils.HTTPCORSDomainFlag.Name))
  557. srv := rpc.NewServer()
  558. err := node.RegisterApisFromWhitelist(rpcAPI, []string{"account"}, srv, false)
  559. if err != nil {
  560. utils.Fatalf("Could not register API: %w", err)
  561. }
  562. handler := node.NewHTTPHandlerStack(srv, cors, vhosts)
  563. // start http server
  564. httpEndpoint := fmt.Sprintf("%s:%d", c.GlobalString(utils.HTTPListenAddrFlag.Name), c.Int(rpcPortFlag.Name))
  565. httpServer, addr, err := node.StartHTTPEndpoint(httpEndpoint, rpc.DefaultHTTPTimeouts, handler)
  566. if err != nil {
  567. utils.Fatalf("Could not start RPC api: %v", err)
  568. }
  569. extapiURL = fmt.Sprintf("http://%v/", addr)
  570. log.Info("HTTP endpoint opened", "url", extapiURL)
  571. defer func() {
  572. // Don't bother imposing a timeout here.
  573. httpServer.Shutdown(context.Background())
  574. log.Info("HTTP endpoint closed", "url", extapiURL)
  575. }()
  576. }
  577. if !c.GlobalBool(utils.IPCDisabledFlag.Name) {
  578. givenPath := c.GlobalString(utils.IPCPathFlag.Name)
  579. ipcapiURL = ipcEndpoint(filepath.Join(givenPath, "clef.ipc"), configDir)
  580. listener, _, err := rpc.StartIPCEndpoint(ipcapiURL, rpcAPI)
  581. if err != nil {
  582. utils.Fatalf("Could not start IPC api: %v", err)
  583. }
  584. log.Info("IPC endpoint opened", "url", ipcapiURL)
  585. defer func() {
  586. listener.Close()
  587. log.Info("IPC endpoint closed", "url", ipcapiURL)
  588. }()
  589. }
  590. if c.GlobalBool(testFlag.Name) {
  591. log.Info("Performing UI test")
  592. go testExternalUI(apiImpl)
  593. }
  594. ui.OnSignerStartup(core.StartupInfo{
  595. Info: map[string]interface{}{
  596. "intapi_version": core.InternalAPIVersion,
  597. "extapi_version": core.ExternalAPIVersion,
  598. "extapi_http": extapiURL,
  599. "extapi_ipc": ipcapiURL,
  600. },
  601. })
  602. abortChan := make(chan os.Signal, 1)
  603. signal.Notify(abortChan, os.Interrupt)
  604. sig := <-abortChan
  605. log.Info("Exiting...", "signal", sig)
  606. return nil
  607. }
  608. // splitAndTrim splits input separated by a comma
  609. // and trims excessive white space from the substrings.
  610. func splitAndTrim(input string) []string {
  611. result := strings.Split(input, ",")
  612. for i, r := range result {
  613. result[i] = strings.TrimSpace(r)
  614. }
  615. return result
  616. }
  617. // DefaultConfigDir is the default config directory to use for the vaults and other
  618. // persistence requirements.
  619. func DefaultConfigDir() string {
  620. // Try to place the data folder in the user's home dir
  621. home := homeDir()
  622. if home != "" {
  623. if runtime.GOOS == "darwin" {
  624. return filepath.Join(home, "Library", "Signer")
  625. } else if runtime.GOOS == "windows" {
  626. appdata := os.Getenv("APPDATA")
  627. if appdata != "" {
  628. return filepath.Join(appdata, "Signer")
  629. } else {
  630. return filepath.Join(home, "AppData", "Roaming", "Signer")
  631. }
  632. } else {
  633. return filepath.Join(home, ".clef")
  634. }
  635. }
  636. // As we cannot guess a stable location, return empty and handle later
  637. return ""
  638. }
  639. func homeDir() string {
  640. if home := os.Getenv("HOME"); home != "" {
  641. return home
  642. }
  643. if usr, err := user.Current(); err == nil {
  644. return usr.HomeDir
  645. }
  646. return ""
  647. }
  648. func readMasterKey(ctx *cli.Context, ui core.UIClientAPI) ([]byte, error) {
  649. var (
  650. file string
  651. configDir = ctx.GlobalString(configdirFlag.Name)
  652. )
  653. if ctx.GlobalIsSet(signerSecretFlag.Name) {
  654. file = ctx.GlobalString(signerSecretFlag.Name)
  655. } else {
  656. file = filepath.Join(configDir, "masterseed.json")
  657. }
  658. if err := checkFile(file); err != nil {
  659. return nil, err
  660. }
  661. cipherKey, err := ioutil.ReadFile(file)
  662. if err != nil {
  663. return nil, err
  664. }
  665. var password string
  666. // If ui is not nil, get the password from ui.
  667. if ui != nil {
  668. resp, err := ui.OnInputRequired(core.UserInputRequest{
  669. Title: "Master Password",
  670. Prompt: "Please enter the password to decrypt the master seed",
  671. IsPassword: true})
  672. if err != nil {
  673. return nil, err
  674. }
  675. password = resp.Text
  676. } else {
  677. password = utils.GetPassPhrase("Decrypt master seed of clef", false)
  678. }
  679. masterSeed, err := decryptSeed(cipherKey, password)
  680. if err != nil {
  681. return nil, fmt.Errorf("failed to decrypt the master seed of clef")
  682. }
  683. if len(masterSeed) < 256 {
  684. return nil, fmt.Errorf("master seed of insufficient length, expected >255 bytes, got %d", len(masterSeed))
  685. }
  686. // Create vault location
  687. vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), masterSeed)[:10]))
  688. err = os.Mkdir(vaultLocation, 0700)
  689. if err != nil && !os.IsExist(err) {
  690. return nil, err
  691. }
  692. return masterSeed, nil
  693. }
  694. // checkFile is a convenience function to check if a file
  695. // * exists
  696. // * is mode 0400
  697. func checkFile(filename string) error {
  698. info, err := os.Stat(filename)
  699. if err != nil {
  700. return fmt.Errorf("failed stat on %s: %v", filename, err)
  701. }
  702. // Check the unix permission bits
  703. if info.Mode().Perm()&0377 != 0 {
  704. return fmt.Errorf("file (%v) has insecure file permissions (%v)", filename, info.Mode().String())
  705. }
  706. return nil
  707. }
  708. // confirm displays a text and asks for user confirmation
  709. func confirm(text string) bool {
  710. fmt.Print(text)
  711. fmt.Printf("\nEnter 'ok' to proceed:\n> ")
  712. text, err := bufio.NewReader(os.Stdin).ReadString('\n')
  713. if err != nil {
  714. log.Crit("Failed to read user input", "err", err)
  715. }
  716. if text := strings.TrimSpace(text); text == "ok" {
  717. return true
  718. }
  719. return false
  720. }
  721. func testExternalUI(api *core.SignerAPI) {
  722. ctx := context.WithValue(context.Background(), "remote", "clef binary")
  723. ctx = context.WithValue(ctx, "scheme", "in-proc")
  724. ctx = context.WithValue(ctx, "local", "main")
  725. errs := make([]string, 0)
  726. a := common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef")
  727. addErr := func(errStr string) {
  728. log.Info("Test error", "err", errStr)
  729. errs = append(errs, errStr)
  730. }
  731. queryUser := func(q string) string {
  732. resp, err := api.UI.OnInputRequired(core.UserInputRequest{
  733. Title: "Testing",
  734. Prompt: q,
  735. })
  736. if err != nil {
  737. addErr(err.Error())
  738. }
  739. return resp.Text
  740. }
  741. expectResponse := func(testcase, question, expect string) {
  742. if got := queryUser(question); got != expect {
  743. addErr(fmt.Sprintf("%s: got %v, expected %v", testcase, got, expect))
  744. }
  745. }
  746. expectApprove := func(testcase string, err error) {
  747. if err == nil || err == accounts.ErrUnknownAccount {
  748. return
  749. }
  750. addErr(fmt.Sprintf("%v: expected no error, got %v", testcase, err.Error()))
  751. }
  752. expectDeny := func(testcase string, err error) {
  753. if err == nil || err != core.ErrRequestDenied {
  754. addErr(fmt.Sprintf("%v: expected ErrRequestDenied, got %v", testcase, err))
  755. }
  756. }
  757. var delay = 1 * time.Second
  758. // Test display of info and error
  759. {
  760. api.UI.ShowInfo("If you see this message, enter 'yes' to next question")
  761. time.Sleep(delay)
  762. expectResponse("showinfo", "Did you see the message? [yes/no]", "yes")
  763. api.UI.ShowError("If you see this message, enter 'yes' to the next question")
  764. time.Sleep(delay)
  765. expectResponse("showerror", "Did you see the message? [yes/no]", "yes")
  766. }
  767. { // Sign data test - clique header
  768. api.UI.ShowInfo("Please approve the next request for signing a clique header")
  769. time.Sleep(delay)
  770. cliqueHeader := types.Header{
  771. ParentHash: common.HexToHash("0000H45H"),
  772. UncleHash: common.HexToHash("0000H45H"),
  773. Coinbase: common.HexToAddress("0000H45H"),
  774. Root: common.HexToHash("0000H00H"),
  775. TxHash: common.HexToHash("0000H45H"),
  776. ReceiptHash: common.HexToHash("0000H45H"),
  777. Difficulty: big.NewInt(1337),
  778. Number: big.NewInt(1337),
  779. GasLimit: 1338,
  780. GasUsed: 1338,
  781. Time: 1338,
  782. Extra: []byte("Extra data Extra data Extra data Extra data Extra data Extra data Extra data Extra data"),
  783. MixDigest: common.HexToHash("0x0000H45H"),
  784. }
  785. cliqueRlp, err := rlp.EncodeToBytes(cliqueHeader)
  786. if err != nil {
  787. utils.Fatalf("Should not error: %v", err)
  788. }
  789. addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
  790. _, err = api.SignData(ctx, accounts.MimetypeClique, *addr, hexutil.Encode(cliqueRlp))
  791. expectApprove("signdata - clique header", err)
  792. }
  793. { // Sign data test - typed data
  794. api.UI.ShowInfo("Please approve the next request for signing EIP-712 typed data")
  795. time.Sleep(delay)
  796. addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
  797. data := `{"types":{"EIP712Domain":[{"name":"name","type":"string"},{"name":"version","type":"string"},{"name":"chainId","type":"uint256"},{"name":"verifyingContract","type":"address"}],"Person":[{"name":"name","type":"string"},{"name":"test","type":"uint8"},{"name":"wallet","type":"address"}],"Mail":[{"name":"from","type":"Person"},{"name":"to","type":"Person"},{"name":"contents","type":"string"}]},"primaryType":"Mail","domain":{"name":"Ether Mail","version":"1","chainId":"1","verifyingContract":"0xCCCcccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"},"message":{"from":{"name":"Cow","test":"3","wallet":"0xcD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"},"to":{"name":"Bob","wallet":"0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB","test":"2"},"contents":"Hello, Bob!"}}`
  798. //_, err := api.SignData(ctx, accounts.MimetypeTypedData, *addr, hexutil.Encode([]byte(data)))
  799. var typedData core.TypedData
  800. json.Unmarshal([]byte(data), &typedData)
  801. _, err := api.SignTypedData(ctx, *addr, typedData)
  802. expectApprove("sign 712 typed data", err)
  803. }
  804. { // Sign data test - plain text
  805. api.UI.ShowInfo("Please approve the next request for signing text")
  806. time.Sleep(delay)
  807. addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
  808. _, err := api.SignData(ctx, accounts.MimetypeTextPlain, *addr, hexutil.Encode([]byte("hello world")))
  809. expectApprove("signdata - text", err)
  810. }
  811. { // Sign data test - plain text reject
  812. api.UI.ShowInfo("Please deny the next request for signing text")
  813. time.Sleep(delay)
  814. addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
  815. _, err := api.SignData(ctx, accounts.MimetypeTextPlain, *addr, hexutil.Encode([]byte("hello world")))
  816. expectDeny("signdata - text", err)
  817. }
  818. { // Sign transaction
  819. api.UI.ShowInfo("Please reject next transaction")
  820. time.Sleep(delay)
  821. data := hexutil.Bytes([]byte{})
  822. to := common.NewMixedcaseAddress(a)
  823. tx := core.SendTxArgs{
  824. Data: &data,
  825. Nonce: 0x1,
  826. Value: hexutil.Big(*big.NewInt(6)),
  827. From: common.NewMixedcaseAddress(a),
  828. To: &to,
  829. GasPrice: hexutil.Big(*big.NewInt(5)),
  830. Gas: 1000,
  831. Input: nil,
  832. }
  833. _, err := api.SignTransaction(ctx, tx, nil)
  834. expectDeny("signtransaction [1]", err)
  835. expectResponse("signtransaction [2]", "Did you see any warnings for the last transaction? (yes/no)", "no")
  836. }
  837. { // Listing
  838. api.UI.ShowInfo("Please reject listing-request")
  839. time.Sleep(delay)
  840. _, err := api.List(ctx)
  841. expectDeny("list", err)
  842. }
  843. { // Import
  844. api.UI.ShowInfo("Please reject new account-request")
  845. time.Sleep(delay)
  846. _, err := api.New(ctx)
  847. expectDeny("newaccount", err)
  848. }
  849. { // Metadata
  850. api.UI.ShowInfo("Please check if you see the Origin in next listing (approve or deny)")
  851. time.Sleep(delay)
  852. api.List(context.WithValue(ctx, "Origin", "origin.com"))
  853. expectResponse("metadata - origin", "Did you see origin (origin.com)? [yes/no] ", "yes")
  854. }
  855. for _, e := range errs {
  856. log.Error(e)
  857. }
  858. result := fmt.Sprintf("Tests completed. %d errors:\n%s\n", len(errs), strings.Join(errs, "\n"))
  859. api.UI.ShowInfo(result)
  860. }
  861. type encryptedSeedStorage struct {
  862. Description string `json:"description"`
  863. Version int `json:"version"`
  864. Params keystore.CryptoJSON `json:"params"`
  865. }
  866. // encryptSeed uses a similar scheme as the keystore uses, but with a different wrapping,
  867. // to encrypt the master seed
  868. func encryptSeed(seed []byte, auth []byte, scryptN, scryptP int) ([]byte, error) {
  869. cryptoStruct, err := keystore.EncryptDataV3(seed, auth, scryptN, scryptP)
  870. if err != nil {
  871. return nil, err
  872. }
  873. return json.Marshal(&encryptedSeedStorage{"Clef seed", 1, cryptoStruct})
  874. }
  875. // decryptSeed decrypts the master seed
  876. func decryptSeed(keyjson []byte, auth string) ([]byte, error) {
  877. var encSeed encryptedSeedStorage
  878. if err := json.Unmarshal(keyjson, &encSeed); err != nil {
  879. return nil, err
  880. }
  881. if encSeed.Version != 1 {
  882. log.Warn(fmt.Sprintf("unsupported encryption format of seed: %d, operation will likely fail", encSeed.Version))
  883. }
  884. seed, err := keystore.DecryptDataV3(encSeed.Params, auth)
  885. if err != nil {
  886. return nil, err
  887. }
  888. return seed, err
  889. }
  890. // GenDoc outputs examples of all structures used in json-rpc communication
  891. func GenDoc(ctx *cli.Context) {
  892. var (
  893. a = common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef")
  894. b = common.HexToAddress("0x1111111122222222222233333333334444444444")
  895. meta = core.Metadata{
  896. Scheme: "http",
  897. Local: "localhost:8545",
  898. Origin: "www.malicious.ru",
  899. Remote: "localhost:9999",
  900. UserAgent: "Firefox 3.2",
  901. }
  902. output []string
  903. add = func(name, desc string, v interface{}) {
  904. if data, err := json.MarshalIndent(v, "", " "); err == nil {
  905. output = append(output, fmt.Sprintf("### %s\n\n%s\n\nExample:\n```json\n%s\n```", name, desc, data))
  906. } else {
  907. log.Error("Error generating output", "err", err)
  908. }
  909. }
  910. )
  911. { // Sign plain text request
  912. desc := "SignDataRequest contains information about a pending request to sign some data. " +
  913. "The data to be signed can be of various types, defined by content-type. Clef has done most " +
  914. "of the work in canonicalizing and making sense of the data, and it's up to the UI to present" +
  915. "the user with the contents of the `message`"
  916. sighash, msg := accounts.TextAndHash([]byte("hello world"))
  917. messages := []*core.NameValueType{{Name: "message", Value: msg, Typ: accounts.MimetypeTextPlain}}
  918. add("SignDataRequest", desc, &core.SignDataRequest{
  919. Address: common.NewMixedcaseAddress(a),
  920. Meta: meta,
  921. ContentType: accounts.MimetypeTextPlain,
  922. Rawdata: []byte(msg),
  923. Messages: messages,
  924. Hash: sighash})
  925. }
  926. { // Sign plain text response
  927. add("SignDataResponse - approve", "Response to SignDataRequest",
  928. &core.SignDataResponse{Approved: true})
  929. add("SignDataResponse - deny", "Response to SignDataRequest",
  930. &core.SignDataResponse{})
  931. }
  932. { // Sign transaction request
  933. desc := "SignTxRequest contains information about a pending request to sign a transaction. " +
  934. "Aside from the transaction itself, there is also a `call_info`-struct. That struct contains " +
  935. "messages of various types, that the user should be informed of." +
  936. "\n\n" +
  937. "As in any request, it's important to consider that the `meta` info also contains untrusted data." +
  938. "\n\n" +
  939. "The `transaction` (on input into clef) can have either `data` or `input` -- if both are set, " +
  940. "they must be identical, otherwise an error is generated. " +
  941. "However, Clef will always use `data` when passing this struct on (if Clef does otherwise, please file a ticket)"
  942. data := hexutil.Bytes([]byte{0x01, 0x02, 0x03, 0x04})
  943. add("SignTxRequest", desc, &core.SignTxRequest{
  944. Meta: meta,
  945. Callinfo: []core.ValidationInfo{
  946. {Typ: "Warning", Message: "Something looks odd, show this message as a warning"},
  947. {Typ: "Info", Message: "User should see this as well"},
  948. },
  949. Transaction: core.SendTxArgs{
  950. Data: &data,
  951. Nonce: 0x1,
  952. Value: hexutil.Big(*big.NewInt(6)),
  953. From: common.NewMixedcaseAddress(a),
  954. To: nil,
  955. GasPrice: hexutil.Big(*big.NewInt(5)),
  956. Gas: 1000,
  957. Input: nil,
  958. }})
  959. }
  960. { // Sign tx response
  961. data := hexutil.Bytes([]byte{0x04, 0x03, 0x02, 0x01})
  962. add("SignTxResponse - approve", "Response to request to sign a transaction. This response needs to contain the `transaction`"+
  963. ", because the UI is free to make modifications to the transaction.",
  964. &core.SignTxResponse{Approved: true,
  965. Transaction: core.SendTxArgs{
  966. Data: &data,
  967. Nonce: 0x4,
  968. Value: hexutil.Big(*big.NewInt(6)),
  969. From: common.NewMixedcaseAddress(a),
  970. To: nil,
  971. GasPrice: hexutil.Big(*big.NewInt(5)),
  972. Gas: 1000,
  973. Input: nil,
  974. }})
  975. add("SignTxResponse - deny", "Response to SignTxRequest. When denying a request, there's no need to "+
  976. "provide the transaction in return",
  977. &core.SignTxResponse{})
  978. }
  979. { // WHen a signed tx is ready to go out
  980. desc := "SignTransactionResult is used in the call `clef` -> `OnApprovedTx(result)`" +
  981. "\n\n" +
  982. "This occurs _after_ successful completion of the entire signing procedure, but right before the signed " +
  983. "transaction is passed to the external caller. This method (and data) can be used by the UI to signal " +
  984. "to the user that the transaction was signed, but it is primarily useful for ruleset implementations." +
  985. "\n\n" +
  986. "A ruleset that implements a rate limitation needs to know what transactions are sent out to the external " +
  987. "interface. By hooking into this methods, the ruleset can maintain track of that count." +
  988. "\n\n" +
  989. "**OBS:** Note that if an attacker can restore your `clef` data to a previous point in time" +
  990. " (e.g through a backup), the attacker can reset such windows, even if he/she is unable to decrypt the content. " +
  991. "\n\n" +
  992. "The `OnApproved` method cannot be responded to, it's purely informative"
  993. rlpdata := common.FromHex("0xf85d640101948a8eafb1cf62bfbeb1741769dae1a9dd47996192018026a0716bd90515acb1e68e5ac5867aa11a1e65399c3349d479f5fb698554ebc6f293a04e8a4ebfff434e971e0ef12c5bf3a881b06fd04fc3f8b8a7291fb67a26a1d4ed")
  994. var tx types.Transaction
  995. rlp.DecodeBytes(rlpdata, &tx)
  996. add("OnApproved - SignTransactionResult", desc, &ethapi.SignTransactionResult{Raw: rlpdata, Tx: &tx})
  997. }
  998. { // User input
  999. add("UserInputRequest", "Sent when clef needs the user to provide data. If 'password' is true, the input field should be treated accordingly (echo-free)",
  1000. &core.UserInputRequest{IsPassword: true, Title: "The title here", Prompt: "The question to ask the user"})
  1001. add("UserInputResponse", "Response to UserInputRequest",
  1002. &core.UserInputResponse{Text: "The textual response from user"})
  1003. }
  1004. { // List request
  1005. add("ListRequest", "Sent when a request has been made to list addresses. The UI is provided with the "+
  1006. "full `account`s, including local directory names. Note: this information is not passed back to the external caller, "+
  1007. "who only sees the `address`es. ",
  1008. &core.ListRequest{
  1009. Meta: meta,
  1010. Accounts: []accounts.Account{
  1011. {Address: a, URL: accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/a"}},
  1012. {Address: b, URL: accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/b"}}},
  1013. })
  1014. add("ListResponse", "Response to list request. The response contains a list of all addresses to show to the caller. "+
  1015. "Note: the UI is free to respond with any address the caller, regardless of whether it exists or not",
  1016. &core.ListResponse{
  1017. Accounts: []accounts.Account{
  1018. {
  1019. Address: common.HexToAddress("0xcowbeef000000cowbeef00000000000000000c0w"),
  1020. URL: accounts.URL{Path: ".. ignored .."},
  1021. },
  1022. {
  1023. Address: common.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff"),
  1024. },
  1025. }})
  1026. }
  1027. fmt.Println(`## UI Client interface
  1028. These data types are defined in the channel between clef and the UI`)
  1029. for _, elem := range output {
  1030. fmt.Println(elem)
  1031. }
  1032. }