main.go 43 KB

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