main.go 39 KB

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