api.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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 core
  17. import (
  18. "context"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "io/ioutil"
  23. "math/big"
  24. "reflect"
  25. "github.com/ethereum/go-ethereum/accounts"
  26. "github.com/ethereum/go-ethereum/accounts/keystore"
  27. "github.com/ethereum/go-ethereum/accounts/usbwallet"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/hexutil"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. "github.com/ethereum/go-ethereum/internal/ethapi"
  32. "github.com/ethereum/go-ethereum/log"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. )
  35. const (
  36. // numberOfAccountsToDerive For hardware wallets, the number of accounts to derive
  37. numberOfAccountsToDerive = 10
  38. // ExternalAPIVersion -- see extapi_changelog.md
  39. ExternalAPIVersion = "4.0.0"
  40. // InternalAPIVersion -- see intapi_changelog.md
  41. InternalAPIVersion = "3.0.0"
  42. )
  43. // ExternalAPI defines the external API through which signing requests are made.
  44. type ExternalAPI interface {
  45. // List available accounts
  46. List(ctx context.Context) ([]common.Address, error)
  47. // New request to create a new account
  48. New(ctx context.Context) (accounts.Account, error)
  49. // SignTransaction request to sign the specified transaction
  50. SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error)
  51. // Sign - request to sign the given data (plus prefix)
  52. Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error)
  53. // Export - request to export an account
  54. Export(ctx context.Context, addr common.Address) (json.RawMessage, error)
  55. // Import - request to import an account
  56. // Should be moved to Internal API, in next phase when we have
  57. // bi-directional communication
  58. //Import(ctx context.Context, keyJSON json.RawMessage) (Account, error)
  59. Version(ctx context.Context) (string, error)
  60. }
  61. // SignerUI specifies what method a UI needs to implement to be able to be used as a UI for the signer
  62. type SignerUI interface {
  63. // ApproveTx prompt the user for confirmation to request to sign Transaction
  64. ApproveTx(request *SignTxRequest) (SignTxResponse, error)
  65. // ApproveSignData prompt the user for confirmation to request to sign data
  66. ApproveSignData(request *SignDataRequest) (SignDataResponse, error)
  67. // ApproveExport prompt the user for confirmation to export encrypted Account json
  68. ApproveExport(request *ExportRequest) (ExportResponse, error)
  69. // ApproveImport prompt the user for confirmation to import Account json
  70. ApproveImport(request *ImportRequest) (ImportResponse, error)
  71. // ApproveListing prompt the user for confirmation to list accounts
  72. // the list of accounts to list can be modified by the UI
  73. ApproveListing(request *ListRequest) (ListResponse, error)
  74. // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
  75. ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error)
  76. // ShowError displays error message to user
  77. ShowError(message string)
  78. // ShowInfo displays info message to user
  79. ShowInfo(message string)
  80. // OnApprovedTx notifies the UI about a transaction having been successfully signed.
  81. // This method can be used by a UI to keep track of e.g. how much has been sent to a particular recipient.
  82. OnApprovedTx(tx ethapi.SignTransactionResult)
  83. // OnSignerStartup is invoked when the signer boots, and tells the UI info about external API location and version
  84. // information
  85. OnSignerStartup(info StartupInfo)
  86. // OnInputRequired is invoked when clef requires user input, for example master password or
  87. // pin-code for unlocking hardware wallets
  88. OnInputRequired(info UserInputRequest) (UserInputResponse, error)
  89. }
  90. // SignerAPI defines the actual implementation of ExternalAPI
  91. type SignerAPI struct {
  92. chainID *big.Int
  93. am *accounts.Manager
  94. UI SignerUI
  95. validator *Validator
  96. rejectMode bool
  97. }
  98. // Metadata about a request
  99. type Metadata struct {
  100. Remote string `json:"remote"`
  101. Local string `json:"local"`
  102. Scheme string `json:"scheme"`
  103. UserAgent string `json:"User-Agent"`
  104. Origin string `json:"Origin"`
  105. }
  106. // MetadataFromContext extracts Metadata from a given context.Context
  107. func MetadataFromContext(ctx context.Context) Metadata {
  108. m := Metadata{"NA", "NA", "NA", "", ""} // batman
  109. if v := ctx.Value("remote"); v != nil {
  110. m.Remote = v.(string)
  111. }
  112. if v := ctx.Value("scheme"); v != nil {
  113. m.Scheme = v.(string)
  114. }
  115. if v := ctx.Value("local"); v != nil {
  116. m.Local = v.(string)
  117. }
  118. if v := ctx.Value("Origin"); v != nil {
  119. m.Origin = v.(string)
  120. }
  121. if v := ctx.Value("User-Agent"); v != nil {
  122. m.UserAgent = v.(string)
  123. }
  124. return m
  125. }
  126. // String implements Stringer interface
  127. func (m Metadata) String() string {
  128. s, err := json.Marshal(m)
  129. if err == nil {
  130. return string(s)
  131. }
  132. return err.Error()
  133. }
  134. // types for the requests/response types between signer and UI
  135. type (
  136. // SignTxRequest contains info about a Transaction to sign
  137. SignTxRequest struct {
  138. Transaction SendTxArgs `json:"transaction"`
  139. Callinfo []ValidationInfo `json:"call_info"`
  140. Meta Metadata `json:"meta"`
  141. }
  142. // SignTxResponse result from SignTxRequest
  143. SignTxResponse struct {
  144. //The UI may make changes to the TX
  145. Transaction SendTxArgs `json:"transaction"`
  146. Approved bool `json:"approved"`
  147. Password string `json:"password"`
  148. }
  149. // ExportRequest info about query to export accounts
  150. ExportRequest struct {
  151. Address common.Address `json:"address"`
  152. Meta Metadata `json:"meta"`
  153. }
  154. // ExportResponse response to export-request
  155. ExportResponse struct {
  156. Approved bool `json:"approved"`
  157. }
  158. // ImportRequest info about request to import an Account
  159. ImportRequest struct {
  160. Meta Metadata `json:"meta"`
  161. }
  162. ImportResponse struct {
  163. Approved bool `json:"approved"`
  164. OldPassword string `json:"old_password"`
  165. NewPassword string `json:"new_password"`
  166. }
  167. SignDataRequest struct {
  168. Address common.MixedcaseAddress `json:"address"`
  169. Rawdata hexutil.Bytes `json:"raw_data"`
  170. Message string `json:"message"`
  171. Hash hexutil.Bytes `json:"hash"`
  172. Meta Metadata `json:"meta"`
  173. }
  174. SignDataResponse struct {
  175. Approved bool `json:"approved"`
  176. Password string
  177. }
  178. NewAccountRequest struct {
  179. Meta Metadata `json:"meta"`
  180. }
  181. NewAccountResponse struct {
  182. Approved bool `json:"approved"`
  183. Password string `json:"password"`
  184. }
  185. ListRequest struct {
  186. Accounts []Account `json:"accounts"`
  187. Meta Metadata `json:"meta"`
  188. }
  189. ListResponse struct {
  190. Accounts []Account `json:"accounts"`
  191. }
  192. Message struct {
  193. Text string `json:"text"`
  194. }
  195. PasswordRequest struct {
  196. Prompt string `json:"prompt"`
  197. }
  198. PasswordResponse struct {
  199. Password string `json:"password"`
  200. }
  201. StartupInfo struct {
  202. Info map[string]interface{} `json:"info"`
  203. }
  204. UserInputRequest struct {
  205. Prompt string `json:"prompt"`
  206. Title string `json:"title"`
  207. IsPassword bool `json:"isPassword"`
  208. }
  209. UserInputResponse struct {
  210. Text string `json:"text"`
  211. }
  212. )
  213. var ErrRequestDenied = errors.New("Request denied")
  214. // NewSignerAPI creates a new API that can be used for Account management.
  215. // ksLocation specifies the directory where to store the password protected private
  216. // key that is generated when a new Account is created.
  217. // noUSB disables USB support that is required to support hardware devices such as
  218. // ledger and trezor.
  219. func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abidb *AbiDb, lightKDF bool, advancedMode bool) *SignerAPI {
  220. var (
  221. backends []accounts.Backend
  222. n, p = keystore.StandardScryptN, keystore.StandardScryptP
  223. )
  224. if lightKDF {
  225. n, p = keystore.LightScryptN, keystore.LightScryptP
  226. }
  227. // support password based accounts
  228. if len(ksLocation) > 0 {
  229. backends = append(backends, keystore.NewKeyStore(ksLocation, n, p))
  230. }
  231. if advancedMode {
  232. log.Info("Clef is in advanced mode: will warn instead of reject")
  233. }
  234. if !noUSB {
  235. // Start a USB hub for Ledger hardware wallets
  236. if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
  237. log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
  238. } else {
  239. backends = append(backends, ledgerhub)
  240. log.Debug("Ledger support enabled")
  241. }
  242. // Start a USB hub for Trezor hardware wallets
  243. if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
  244. log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
  245. } else {
  246. backends = append(backends, trezorhub)
  247. log.Debug("Trezor support enabled")
  248. }
  249. }
  250. signer := &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb), !advancedMode}
  251. if !noUSB {
  252. signer.startUSBListener()
  253. }
  254. return signer
  255. }
  256. func (api *SignerAPI) openTrezor(url accounts.URL) {
  257. resp, err := api.UI.OnInputRequired(UserInputRequest{
  258. Prompt: "Pin required to open Trezor wallet\n" +
  259. "Look at the device for number positions\n\n" +
  260. "7 | 8 | 9\n" +
  261. "--+---+--\n" +
  262. "4 | 5 | 6\n" +
  263. "--+---+--\n" +
  264. "1 | 2 | 3\n\n",
  265. IsPassword: true,
  266. Title: "Trezor unlock",
  267. })
  268. if err != nil {
  269. log.Warn("failed getting trezor pin", "err", err)
  270. return
  271. }
  272. // We're using the URL instead of the pointer to the
  273. // Wallet -- perhaps it is not actually present anymore
  274. w, err := api.am.Wallet(url.String())
  275. if err != nil {
  276. log.Warn("wallet unavailable", "url", url)
  277. return
  278. }
  279. err = w.Open(resp.Text)
  280. if err != nil {
  281. log.Warn("failed to open wallet", "wallet", url, "err", err)
  282. return
  283. }
  284. }
  285. // startUSBListener starts a listener for USB events, for hardware wallet interaction
  286. func (api *SignerAPI) startUSBListener() {
  287. events := make(chan accounts.WalletEvent, 16)
  288. am := api.am
  289. am.Subscribe(events)
  290. go func() {
  291. // Open any wallets already attached
  292. for _, wallet := range am.Wallets() {
  293. if err := wallet.Open(""); err != nil {
  294. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  295. if err == usbwallet.ErrTrezorPINNeeded {
  296. go api.openTrezor(wallet.URL())
  297. }
  298. }
  299. }
  300. // Listen for wallet event till termination
  301. for event := range events {
  302. switch event.Kind {
  303. case accounts.WalletArrived:
  304. if err := event.Wallet.Open(""); err != nil {
  305. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  306. if err == usbwallet.ErrTrezorPINNeeded {
  307. go api.openTrezor(event.Wallet.URL())
  308. }
  309. }
  310. case accounts.WalletOpened:
  311. status, _ := event.Wallet.Status()
  312. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  313. derivationPath := accounts.DefaultBaseDerivationPath
  314. if event.Wallet.URL().Scheme == "ledger" {
  315. derivationPath = accounts.DefaultLedgerBaseDerivationPath
  316. }
  317. var nextPath = derivationPath
  318. // Derive first N accounts, hardcoded for now
  319. for i := 0; i < numberOfAccountsToDerive; i++ {
  320. acc, err := event.Wallet.Derive(nextPath, true)
  321. if err != nil {
  322. log.Warn("account derivation failed", "error", err)
  323. } else {
  324. log.Info("derived account", "address", acc.Address)
  325. }
  326. nextPath[len(nextPath)-1]++
  327. }
  328. case accounts.WalletDropped:
  329. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  330. event.Wallet.Close()
  331. }
  332. }
  333. }()
  334. }
  335. // List returns the set of wallet this signer manages. Each wallet can contain
  336. // multiple accounts.
  337. func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
  338. var accs []Account
  339. for _, wallet := range api.am.Wallets() {
  340. for _, acc := range wallet.Accounts() {
  341. acc := Account{Typ: "Account", URL: wallet.URL(), Address: acc.Address}
  342. accs = append(accs, acc)
  343. }
  344. }
  345. result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
  346. if err != nil {
  347. return nil, err
  348. }
  349. if result.Accounts == nil {
  350. return nil, ErrRequestDenied
  351. }
  352. addresses := make([]common.Address, 0)
  353. for _, acc := range result.Accounts {
  354. addresses = append(addresses, acc.Address)
  355. }
  356. return addresses, nil
  357. }
  358. // New creates a new password protected Account. The private key is protected with
  359. // the given password. Users are responsible to backup the private key that is stored
  360. // in the keystore location thas was specified when this API was created.
  361. func (api *SignerAPI) New(ctx context.Context) (accounts.Account, error) {
  362. be := api.am.Backends(keystore.KeyStoreType)
  363. if len(be) == 0 {
  364. return accounts.Account{}, errors.New("password based accounts not supported")
  365. }
  366. var (
  367. resp NewAccountResponse
  368. err error
  369. )
  370. // Three retries to get a valid password
  371. for i := 0; i < 3; i++ {
  372. resp, err = api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)})
  373. if err != nil {
  374. return accounts.Account{}, err
  375. }
  376. if !resp.Approved {
  377. return accounts.Account{}, ErrRequestDenied
  378. }
  379. if pwErr := ValidatePasswordFormat(resp.Password); pwErr != nil {
  380. api.UI.ShowError(fmt.Sprintf("Account creation attempt #%d failed due to password requirements: %v", (i + 1), pwErr))
  381. } else {
  382. // No error
  383. return be[0].(*keystore.KeyStore).NewAccount(resp.Password)
  384. }
  385. }
  386. // Otherwise fail, with generic error message
  387. return accounts.Account{}, errors.New("account creation failed")
  388. }
  389. // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
  390. // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
  391. // UI-modifications to requests
  392. func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
  393. modified := false
  394. if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
  395. log.Info("Sender-account changed by UI", "was", f0, "is", f1)
  396. modified = true
  397. }
  398. if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
  399. log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
  400. modified = true
  401. }
  402. if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
  403. modified = true
  404. log.Info("Gas changed by UI", "was", g0, "is", g1)
  405. }
  406. if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 {
  407. modified = true
  408. log.Info("GasPrice changed by UI", "was", g0, "is", g1)
  409. }
  410. if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
  411. modified = true
  412. log.Info("Value changed by UI", "was", v0, "is", v1)
  413. }
  414. if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
  415. d0s := ""
  416. d1s := ""
  417. if d0 != nil {
  418. d0s = hexutil.Encode(*d0)
  419. }
  420. if d1 != nil {
  421. d1s = hexutil.Encode(*d1)
  422. }
  423. if d1s != d0s {
  424. modified = true
  425. log.Info("Data changed by UI", "was", d0s, "is", d1s)
  426. }
  427. }
  428. if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
  429. modified = true
  430. log.Info("Nonce changed by UI", "was", n0, "is", n1)
  431. }
  432. return modified
  433. }
  434. // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
  435. func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
  436. var (
  437. err error
  438. result SignTxResponse
  439. )
  440. msgs, err := api.validator.ValidateTransaction(&args, methodSelector)
  441. if err != nil {
  442. return nil, err
  443. }
  444. // If we are in 'rejectMode', then reject rather than show the user warnings
  445. if api.rejectMode {
  446. if err := msgs.getWarnings(); err != nil {
  447. return nil, err
  448. }
  449. }
  450. req := SignTxRequest{
  451. Transaction: args,
  452. Meta: MetadataFromContext(ctx),
  453. Callinfo: msgs.Messages,
  454. }
  455. // Process approval
  456. result, err = api.UI.ApproveTx(&req)
  457. if err != nil {
  458. return nil, err
  459. }
  460. if !result.Approved {
  461. return nil, ErrRequestDenied
  462. }
  463. // Log changes made by the UI to the signing-request
  464. logDiff(&req, &result)
  465. var (
  466. acc accounts.Account
  467. wallet accounts.Wallet
  468. )
  469. acc = accounts.Account{Address: result.Transaction.From.Address()}
  470. wallet, err = api.am.Find(acc)
  471. if err != nil {
  472. return nil, err
  473. }
  474. // Convert fields into a real transaction
  475. var unsignedTx = result.Transaction.toTransaction()
  476. // The one to sign is the one that was returned from the UI
  477. signedTx, err := wallet.SignTxWithPassphrase(acc, result.Password, unsignedTx, api.chainID)
  478. if err != nil {
  479. api.UI.ShowError(err.Error())
  480. return nil, err
  481. }
  482. rlpdata, err := rlp.EncodeToBytes(signedTx)
  483. response := ethapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx}
  484. // Finally, send the signed tx to the UI
  485. api.UI.OnApprovedTx(response)
  486. // ...and to the external caller
  487. return &response, nil
  488. }
  489. // Sign calculates an Ethereum ECDSA signature for:
  490. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
  491. //
  492. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  493. // where the V value will be 27 or 28 for legacy reasons.
  494. //
  495. // The key used to calculate the signature is decrypted with the given password.
  496. //
  497. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
  498. func (api *SignerAPI) Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error) {
  499. sighash, msg := SignHash(data)
  500. // We make the request prior to looking up if we actually have the account, to prevent
  501. // account-enumeration via the API
  502. req := &SignDataRequest{Address: addr, Rawdata: data, Message: msg, Hash: sighash, Meta: MetadataFromContext(ctx)}
  503. res, err := api.UI.ApproveSignData(req)
  504. if err != nil {
  505. return nil, err
  506. }
  507. if !res.Approved {
  508. return nil, ErrRequestDenied
  509. }
  510. // Look up the wallet containing the requested signer
  511. account := accounts.Account{Address: addr.Address()}
  512. wallet, err := api.am.Find(account)
  513. if err != nil {
  514. return nil, err
  515. }
  516. // Assemble sign the data with the wallet
  517. signature, err := wallet.SignTextWithPassphrase(account, res.Password, data)
  518. if err != nil {
  519. api.UI.ShowError(err.Error())
  520. return nil, err
  521. }
  522. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  523. return signature, nil
  524. }
  525. // SignHash is a helper function that calculates a hash for the given message that can be
  526. // safely used to calculate a signature from.
  527. //
  528. // The hash is calculated as
  529. // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
  530. //
  531. // This gives context to the signed message and prevents signing of transactions.
  532. func SignHash(data []byte) ([]byte, string) {
  533. msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
  534. return crypto.Keccak256([]byte(msg)), msg
  535. }
  536. // Export returns encrypted private key associated with the given address in web3 keystore format.
  537. func (api *SignerAPI) Export(ctx context.Context, addr common.Address) (json.RawMessage, error) {
  538. res, err := api.UI.ApproveExport(&ExportRequest{Address: addr, Meta: MetadataFromContext(ctx)})
  539. if err != nil {
  540. return nil, err
  541. }
  542. if !res.Approved {
  543. return nil, ErrRequestDenied
  544. }
  545. // Look up the wallet containing the requested signer
  546. wallet, err := api.am.Find(accounts.Account{Address: addr})
  547. if err != nil {
  548. return nil, err
  549. }
  550. if wallet.URL().Scheme != keystore.KeyStoreScheme {
  551. return nil, fmt.Errorf("Account is not a keystore-account")
  552. }
  553. return ioutil.ReadFile(wallet.URL().Path)
  554. }
  555. // Import tries to import the given keyJSON in the local keystore. The keyJSON data is expected to be
  556. // in web3 keystore format. It will decrypt the keyJSON with the given passphrase and on successful
  557. // decryption it will encrypt the key with the given newPassphrase and store it in the keystore.
  558. // OBS! This method is removed from the public API. It should not be exposed on the external API
  559. // for a couple of reasons:
  560. // 1. Even though it is encrypted, it should still be seen as sensitive data
  561. // 2. It can be used to DoS clef, by using malicious data with e.g. extreme large
  562. // values for the kdfparams.
  563. func (api *SignerAPI) Import(ctx context.Context, keyJSON json.RawMessage) (Account, error) {
  564. be := api.am.Backends(keystore.KeyStoreType)
  565. if len(be) == 0 {
  566. return Account{}, errors.New("password based accounts not supported")
  567. }
  568. res, err := api.UI.ApproveImport(&ImportRequest{Meta: MetadataFromContext(ctx)})
  569. if err != nil {
  570. return Account{}, err
  571. }
  572. if !res.Approved {
  573. return Account{}, ErrRequestDenied
  574. }
  575. acc, err := be[0].(*keystore.KeyStore).Import(keyJSON, res.OldPassword, res.NewPassword)
  576. if err != nil {
  577. api.UI.ShowError(err.Error())
  578. return Account{}, err
  579. }
  580. return Account{Typ: "Account", URL: acc.URL, Address: acc.Address}, nil
  581. }
  582. // Returns the external api version. This method does not require user acceptance. Available methods are
  583. // available via enumeration anyway, and this info does not contain user-specific data
  584. func (api *SignerAPI) Version(ctx context.Context) (string, error) {
  585. return ExternalAPIVersion, nil
  586. }