api.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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. // OnInputRequired 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. PasswordRequest struct {
  189. Prompt string `json:"prompt"`
  190. }
  191. PasswordResponse struct {
  192. Password string `json:"password"`
  193. }
  194. StartupInfo struct {
  195. Info map[string]interface{} `json:"info"`
  196. }
  197. UserInputRequest struct {
  198. Prompt string `json:"prompt"`
  199. Title string `json:"title"`
  200. IsPassword bool `json:"isPassword"`
  201. }
  202. UserInputResponse struct {
  203. Text string `json:"text"`
  204. }
  205. )
  206. var ErrRequestDenied = errors.New("Request denied")
  207. // NewSignerAPI creates a new API that can be used for Account management.
  208. // ksLocation specifies the directory where to store the password protected private
  209. // key that is generated when a new Account is created.
  210. // noUSB disables USB support that is required to support hardware devices such as
  211. // ledger and trezor.
  212. func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abidb *AbiDb, lightKDF bool, advancedMode bool) *SignerAPI {
  213. var (
  214. backends []accounts.Backend
  215. n, p = keystore.StandardScryptN, keystore.StandardScryptP
  216. )
  217. if lightKDF {
  218. n, p = keystore.LightScryptN, keystore.LightScryptP
  219. }
  220. // support password based accounts
  221. if len(ksLocation) > 0 {
  222. backends = append(backends, keystore.NewKeyStore(ksLocation, n, p))
  223. }
  224. if advancedMode {
  225. log.Info("Clef is in advanced mode: will warn instead of reject")
  226. }
  227. if !noUSB {
  228. // Start a USB hub for Ledger hardware wallets
  229. if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
  230. log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
  231. } else {
  232. backends = append(backends, ledgerhub)
  233. log.Debug("Ledger support enabled")
  234. }
  235. // Start a USB hub for Trezor hardware wallets
  236. if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
  237. log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
  238. } else {
  239. backends = append(backends, trezorhub)
  240. log.Debug("Trezor support enabled")
  241. }
  242. }
  243. signer := &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb), !advancedMode}
  244. if !noUSB {
  245. signer.startUSBListener()
  246. }
  247. return signer
  248. }
  249. func (api *SignerAPI) openTrezor(url accounts.URL) {
  250. resp, err := api.UI.OnInputRequired(UserInputRequest{
  251. Prompt: "Pin required to open Trezor wallet\n" +
  252. "Look at the device for number positions\n\n" +
  253. "7 | 8 | 9\n" +
  254. "--+---+--\n" +
  255. "4 | 5 | 6\n" +
  256. "--+---+--\n" +
  257. "1 | 2 | 3\n\n",
  258. IsPassword: true,
  259. Title: "Trezor unlock",
  260. })
  261. if err != nil {
  262. log.Warn("failed getting trezor pin", "err", err)
  263. return
  264. }
  265. // We're using the URL instead of the pointer to the
  266. // Wallet -- perhaps it is not actually present anymore
  267. w, err := api.am.Wallet(url.String())
  268. if err != nil {
  269. log.Warn("wallet unavailable", "url", url)
  270. return
  271. }
  272. err = w.Open(resp.Text)
  273. if err != nil {
  274. log.Warn("failed to open wallet", "wallet", url, "err", err)
  275. return
  276. }
  277. }
  278. // startUSBListener starts a listener for USB events, for hardware wallet interaction
  279. func (api *SignerAPI) startUSBListener() {
  280. events := make(chan accounts.WalletEvent, 16)
  281. am := api.am
  282. am.Subscribe(events)
  283. go func() {
  284. // Open any wallets already attached
  285. for _, wallet := range am.Wallets() {
  286. if err := wallet.Open(""); err != nil {
  287. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  288. if err == usbwallet.ErrTrezorPINNeeded {
  289. go api.openTrezor(wallet.URL())
  290. }
  291. }
  292. }
  293. // Listen for wallet event till termination
  294. for event := range events {
  295. switch event.Kind {
  296. case accounts.WalletArrived:
  297. if err := event.Wallet.Open(""); err != nil {
  298. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  299. if err == usbwallet.ErrTrezorPINNeeded {
  300. go api.openTrezor(event.Wallet.URL())
  301. }
  302. }
  303. case accounts.WalletOpened:
  304. status, _ := event.Wallet.Status()
  305. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  306. derivationPath := accounts.DefaultBaseDerivationPath
  307. if event.Wallet.URL().Scheme == "ledger" {
  308. derivationPath = accounts.DefaultLedgerBaseDerivationPath
  309. }
  310. var nextPath = derivationPath
  311. // Derive first N accounts, hardcoded for now
  312. for i := 0; i < numberOfAccountsToDerive; i++ {
  313. acc, err := event.Wallet.Derive(nextPath, true)
  314. if err != nil {
  315. log.Warn("account derivation failed", "error", err)
  316. } else {
  317. log.Info("derived account", "address", acc.Address)
  318. }
  319. nextPath[len(nextPath)-1]++
  320. }
  321. case accounts.WalletDropped:
  322. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  323. event.Wallet.Close()
  324. }
  325. }
  326. }()
  327. }
  328. // List returns the set of wallet this signer manages. Each wallet can contain
  329. // multiple accounts.
  330. func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
  331. var accs []Account
  332. for _, wallet := range api.am.Wallets() {
  333. for _, acc := range wallet.Accounts() {
  334. acc := Account{Typ: "Account", URL: wallet.URL(), Address: acc.Address}
  335. accs = append(accs, acc)
  336. }
  337. }
  338. result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
  339. if err != nil {
  340. return nil, err
  341. }
  342. if result.Accounts == nil {
  343. return nil, ErrRequestDenied
  344. }
  345. addresses := make([]common.Address, 0)
  346. for _, acc := range result.Accounts {
  347. addresses = append(addresses, acc.Address)
  348. }
  349. return addresses, nil
  350. }
  351. // New creates a new password protected Account. The private key is protected with
  352. // the given password. Users are responsible to backup the private key that is stored
  353. // in the keystore location thas was specified when this API was created.
  354. func (api *SignerAPI) New(ctx context.Context) (accounts.Account, error) {
  355. be := api.am.Backends(keystore.KeyStoreType)
  356. if len(be) == 0 {
  357. return accounts.Account{}, errors.New("password based accounts not supported")
  358. }
  359. var (
  360. resp NewAccountResponse
  361. err error
  362. )
  363. // Three retries to get a valid password
  364. for i := 0; i < 3; i++ {
  365. resp, err = api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)})
  366. if err != nil {
  367. return accounts.Account{}, err
  368. }
  369. if !resp.Approved {
  370. return accounts.Account{}, ErrRequestDenied
  371. }
  372. if pwErr := ValidatePasswordFormat(resp.Password); pwErr != nil {
  373. api.UI.ShowError(fmt.Sprintf("Account creation attempt #%d failed due to password requirements: %v", (i + 1), pwErr))
  374. } else {
  375. // No error
  376. return be[0].(*keystore.KeyStore).NewAccount(resp.Password)
  377. }
  378. }
  379. // Otherwise fail, with generic error message
  380. return accounts.Account{}, errors.New("account creation failed")
  381. }
  382. // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
  383. // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
  384. // UI-modifications to requests
  385. func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
  386. modified := false
  387. if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
  388. log.Info("Sender-account changed by UI", "was", f0, "is", f1)
  389. modified = true
  390. }
  391. if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
  392. log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
  393. modified = true
  394. }
  395. if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
  396. modified = true
  397. log.Info("Gas changed by UI", "was", g0, "is", g1)
  398. }
  399. if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 {
  400. modified = true
  401. log.Info("GasPrice changed by UI", "was", g0, "is", g1)
  402. }
  403. if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
  404. modified = true
  405. log.Info("Value changed by UI", "was", v0, "is", v1)
  406. }
  407. if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
  408. d0s := ""
  409. d1s := ""
  410. if d0 != nil {
  411. d0s = hexutil.Encode(*d0)
  412. }
  413. if d1 != nil {
  414. d1s = hexutil.Encode(*d1)
  415. }
  416. if d1s != d0s {
  417. modified = true
  418. log.Info("Data changed by UI", "was", d0s, "is", d1s)
  419. }
  420. }
  421. if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
  422. modified = true
  423. log.Info("Nonce changed by UI", "was", n0, "is", n1)
  424. }
  425. return modified
  426. }
  427. // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
  428. func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
  429. var (
  430. err error
  431. result SignTxResponse
  432. )
  433. msgs, err := api.validator.ValidateTransaction(&args, methodSelector)
  434. if err != nil {
  435. return nil, err
  436. }
  437. // If we are in 'rejectMode', then reject rather than show the user warnings
  438. if api.rejectMode {
  439. if err := msgs.getWarnings(); err != nil {
  440. return nil, err
  441. }
  442. }
  443. req := SignTxRequest{
  444. Transaction: args,
  445. Meta: MetadataFromContext(ctx),
  446. Callinfo: msgs.Messages,
  447. }
  448. // Process approval
  449. result, err = api.UI.ApproveTx(&req)
  450. if err != nil {
  451. return nil, err
  452. }
  453. if !result.Approved {
  454. return nil, ErrRequestDenied
  455. }
  456. // Log changes made by the UI to the signing-request
  457. logDiff(&req, &result)
  458. var (
  459. acc accounts.Account
  460. wallet accounts.Wallet
  461. )
  462. acc = accounts.Account{Address: result.Transaction.From.Address()}
  463. wallet, err = api.am.Find(acc)
  464. if err != nil {
  465. return nil, err
  466. }
  467. // Convert fields into a real transaction
  468. var unsignedTx = result.Transaction.toTransaction()
  469. // The one to sign is the one that was returned from the UI
  470. signedTx, err := wallet.SignTxWithPassphrase(acc, result.Password, unsignedTx, api.chainID)
  471. if err != nil {
  472. api.UI.ShowError(err.Error())
  473. return nil, err
  474. }
  475. rlpdata, err := rlp.EncodeToBytes(signedTx)
  476. response := ethapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx}
  477. // Finally, send the signed tx to the UI
  478. api.UI.OnApprovedTx(response)
  479. // ...and to the external caller
  480. return &response, nil
  481. }
  482. // Sign calculates an Ethereum ECDSA signature for:
  483. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
  484. //
  485. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  486. // where the V value will be 27 or 28 for legacy reasons.
  487. //
  488. // The key used to calculate the signature is decrypted with the given password.
  489. //
  490. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
  491. func (api *SignerAPI) Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error) {
  492. sighash, msg := SignHash(data)
  493. // We make the request prior to looking up if we actually have the account, to prevent
  494. // account-enumeration via the API
  495. req := &SignDataRequest{Address: addr, Rawdata: data, Message: msg, Hash: sighash, Meta: MetadataFromContext(ctx)}
  496. res, err := api.UI.ApproveSignData(req)
  497. if err != nil {
  498. return nil, err
  499. }
  500. if !res.Approved {
  501. return nil, ErrRequestDenied
  502. }
  503. // Look up the wallet containing the requested signer
  504. account := accounts.Account{Address: addr.Address()}
  505. wallet, err := api.am.Find(account)
  506. if err != nil {
  507. return nil, err
  508. }
  509. // Assemble sign the data with the wallet
  510. signature, err := wallet.SignHashWithPassphrase(account, res.Password, sighash)
  511. if err != nil {
  512. api.UI.ShowError(err.Error())
  513. return nil, err
  514. }
  515. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  516. return signature, nil
  517. }
  518. // SignHash is a helper function that calculates a hash for the given message that can be
  519. // safely used to calculate a signature from.
  520. //
  521. // The hash is calculated as
  522. // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
  523. //
  524. // This gives context to the signed message and prevents signing of transactions.
  525. func SignHash(data []byte) ([]byte, string) {
  526. msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
  527. return crypto.Keccak256([]byte(msg)), msg
  528. }
  529. // Export returns encrypted private key associated with the given address in web3 keystore format.
  530. func (api *SignerAPI) Export(ctx context.Context, addr common.Address) (json.RawMessage, error) {
  531. res, err := api.UI.ApproveExport(&ExportRequest{Address: addr, Meta: MetadataFromContext(ctx)})
  532. if err != nil {
  533. return nil, err
  534. }
  535. if !res.Approved {
  536. return nil, ErrRequestDenied
  537. }
  538. // Look up the wallet containing the requested signer
  539. wallet, err := api.am.Find(accounts.Account{Address: addr})
  540. if err != nil {
  541. return nil, err
  542. }
  543. if wallet.URL().Scheme != keystore.KeyStoreScheme {
  544. return nil, fmt.Errorf("Account is not a keystore-account")
  545. }
  546. return ioutil.ReadFile(wallet.URL().Path)
  547. }
  548. // Import tries to import the given keyJSON in the local keystore. The keyJSON data is expected to be
  549. // in web3 keystore format. It will decrypt the keyJSON with the given passphrase and on successful
  550. // decryption it will encrypt the key with the given newPassphrase and store it in the keystore.
  551. // OBS! This method is removed from the public API. It should not be exposed on the external API
  552. // for a couple of reasons:
  553. // 1. Even though it is encrypted, it should still be seen as sensitive data
  554. // 2. It can be used to DoS clef, by using malicious data with e.g. extreme large
  555. // values for the kdfparams.
  556. func (api *SignerAPI) Import(ctx context.Context, keyJSON json.RawMessage) (Account, error) {
  557. be := api.am.Backends(keystore.KeyStoreType)
  558. if len(be) == 0 {
  559. return Account{}, errors.New("password based accounts not supported")
  560. }
  561. res, err := api.UI.ApproveImport(&ImportRequest{Meta: MetadataFromContext(ctx)})
  562. if err != nil {
  563. return Account{}, err
  564. }
  565. if !res.Approved {
  566. return Account{}, ErrRequestDenied
  567. }
  568. acc, err := be[0].(*keystore.KeyStore).Import(keyJSON, res.OldPassword, res.NewPassword)
  569. if err != nil {
  570. api.UI.ShowError(err.Error())
  571. return Account{}, err
  572. }
  573. return Account{Typ: "Account", URL: acc.URL, Address: acc.Address}, nil
  574. }