main.go 39 KB

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