github.com/felberj/go-ethereum@v1.8.23/signer/core/api.go (about)

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