main.go 38 KB

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