api.go 20 KB

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