github.com/snowblossomcoin/go-ethereum@v1.9.25/signer/core/api.go (about)

     1  // Copyright 2018 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser 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  // The go-ethereum library 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 Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. 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  	"math/big"
    25  	"os"
    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/scwallet"
    31  	"github.com/ethereum/go-ethereum/accounts/usbwallet"
    32  	"github.com/ethereum/go-ethereum/common"
    33  	"github.com/ethereum/go-ethereum/common/hexutil"
    34  	"github.com/ethereum/go-ethereum/internal/ethapi"
    35  	"github.com/ethereum/go-ethereum/log"
    36  	"github.com/ethereum/go-ethereum/rlp"
    37  	"github.com/ethereum/go-ethereum/signer/storage"
    38  )
    39  
    40  const (
    41  	// numberOfAccountsToDerive For hardware wallets, the number of accounts to derive
    42  	numberOfAccountsToDerive = 10
    43  	// ExternalAPIVersion -- see extapi_changelog.md
    44  	ExternalAPIVersion = "6.1.0"
    45  	// InternalAPIVersion -- see intapi_changelog.md
    46  	InternalAPIVersion = "7.0.1"
    47  )
    48  
    49  // ExternalAPI defines the external API through which signing requests are made.
    50  type ExternalAPI interface {
    51  	// List available accounts
    52  	List(ctx context.Context) ([]common.Address, error)
    53  	// New request to create a new account
    54  	New(ctx context.Context) (common.Address, error)
    55  	// SignTransaction request to sign the specified transaction
    56  	SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error)
    57  	// SignData - request to sign the given data (plus prefix)
    58  	SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data interface{}) (hexutil.Bytes, error)
    59  	// SignTypedData - request to sign the given structured data (plus prefix)
    60  	SignTypedData(ctx context.Context, addr common.MixedcaseAddress, data TypedData) (hexutil.Bytes, error)
    61  	// EcRecover - recover public key from given message and signature
    62  	EcRecover(ctx context.Context, data hexutil.Bytes, sig hexutil.Bytes) (common.Address, error)
    63  	// Version info about the APIs
    64  	Version(ctx context.Context) (string, error)
    65  	// SignGnosisSafeTransaction signs/confirms a gnosis-safe multisig transaction
    66  	SignGnosisSafeTx(ctx context.Context, signerAddress common.MixedcaseAddress, gnosisTx GnosisSafeTx, methodSelector *string) (*GnosisSafeTx, error)
    67  }
    68  
    69  // UIClientAPI specifies what method a UI needs to implement to be able to be used as a
    70  // UI for the signer
    71  type UIClientAPI interface {
    72  	// ApproveTx prompt the user for confirmation to request to sign Transaction
    73  	ApproveTx(request *SignTxRequest) (SignTxResponse, error)
    74  	// ApproveSignData prompt the user for confirmation to request to sign data
    75  	ApproveSignData(request *SignDataRequest) (SignDataResponse, error)
    76  	// ApproveListing prompt the user for confirmation to list accounts
    77  	// the list of accounts to list can be modified by the UI
    78  	ApproveListing(request *ListRequest) (ListResponse, error)
    79  	// ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
    80  	ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error)
    81  	// ShowError displays error message to user
    82  	ShowError(message string)
    83  	// ShowInfo displays info message to user
    84  	ShowInfo(message string)
    85  	// OnApprovedTx notifies the UI about a transaction having been successfully signed.
    86  	// This method can be used by a UI to keep track of e.g. how much has been sent to a particular recipient.
    87  	OnApprovedTx(tx ethapi.SignTransactionResult)
    88  	// OnSignerStartup is invoked when the signer boots, and tells the UI info about external API location and version
    89  	// information
    90  	OnSignerStartup(info StartupInfo)
    91  	// OnInputRequired is invoked when clef requires user input, for example master password or
    92  	// pin-code for unlocking hardware wallets
    93  	OnInputRequired(info UserInputRequest) (UserInputResponse, error)
    94  	// RegisterUIServer tells the UI to use the given UIServerAPI for ui->clef communication
    95  	RegisterUIServer(api *UIServerAPI)
    96  }
    97  
    98  // Validator defines the methods required to validate a transaction against some
    99  // sanity defaults as well as any underlying 4byte method database.
   100  //
   101  // Use fourbyte.Database as an implementation. It is separated out of this package
   102  // to allow pieces of the signer package to be used without having to load the
   103  // 7MB embedded 4byte dump.
   104  type Validator interface {
   105  	// ValidateTransaction does a number of checks on the supplied transaction, and
   106  	// returns either a list of warnings, or an error (indicating that the transaction
   107  	// should be immediately rejected).
   108  	ValidateTransaction(selector *string, tx *SendTxArgs) (*ValidationMessages, error)
   109  }
   110  
   111  // SignerAPI defines the actual implementation of ExternalAPI
   112  type SignerAPI struct {
   113  	chainID     *big.Int
   114  	am          *accounts.Manager
   115  	UI          UIClientAPI
   116  	validator   Validator
   117  	rejectMode  bool
   118  	credentials storage.Storage
   119  }
   120  
   121  // Metadata about a request
   122  type Metadata struct {
   123  	Remote    string `json:"remote"`
   124  	Local     string `json:"local"`
   125  	Scheme    string `json:"scheme"`
   126  	UserAgent string `json:"User-Agent"`
   127  	Origin    string `json:"Origin"`
   128  }
   129  
   130  func StartClefAccountManager(ksLocation string, nousb, lightKDF bool, scpath string) *accounts.Manager {
   131  	var (
   132  		backends []accounts.Backend
   133  		n, p     = keystore.StandardScryptN, keystore.StandardScryptP
   134  	)
   135  	if lightKDF {
   136  		n, p = keystore.LightScryptN, keystore.LightScryptP
   137  	}
   138  	// support password based accounts
   139  	if len(ksLocation) > 0 {
   140  		backends = append(backends, keystore.NewKeyStore(ksLocation, n, p))
   141  	}
   142  	if !nousb {
   143  		// Start a USB hub for Ledger hardware wallets
   144  		if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   145  			log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   146  		} else {
   147  			backends = append(backends, ledgerhub)
   148  			log.Debug("Ledger support enabled")
   149  		}
   150  		// Start a USB hub for Trezor hardware wallets (HID version)
   151  		if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
   152  			log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
   153  		} else {
   154  			backends = append(backends, trezorhub)
   155  			log.Debug("Trezor support enabled via HID")
   156  		}
   157  		// Start a USB hub for Trezor hardware wallets (WebUSB version)
   158  		if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
   159  			log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
   160  		} else {
   161  			backends = append(backends, trezorhub)
   162  			log.Debug("Trezor support enabled via WebUSB")
   163  		}
   164  	}
   165  
   166  	// Start a smart card hub
   167  	if len(scpath) > 0 {
   168  		// Sanity check that the smartcard path is valid
   169  		fi, err := os.Stat(scpath)
   170  		if err != nil {
   171  			log.Info("Smartcard socket file missing, disabling", "err", err)
   172  		} else {
   173  			if fi.Mode()&os.ModeType != os.ModeSocket {
   174  				log.Error("Invalid smartcard socket file type", "path", scpath, "type", fi.Mode().String())
   175  			} else {
   176  				if schub, err := scwallet.NewHub(scpath, scwallet.Scheme, ksLocation); err != nil {
   177  					log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
   178  				} else {
   179  					backends = append(backends, schub)
   180  				}
   181  			}
   182  		}
   183  	}
   184  
   185  	// Clef doesn't allow insecure http account unlock.
   186  	return accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: false}, backends...)
   187  }
   188  
   189  // MetadataFromContext extracts Metadata from a given context.Context
   190  func MetadataFromContext(ctx context.Context) Metadata {
   191  	m := Metadata{"NA", "NA", "NA", "", ""} // batman
   192  
   193  	if v := ctx.Value("remote"); v != nil {
   194  		m.Remote = v.(string)
   195  	}
   196  	if v := ctx.Value("scheme"); v != nil {
   197  		m.Scheme = v.(string)
   198  	}
   199  	if v := ctx.Value("local"); v != nil {
   200  		m.Local = v.(string)
   201  	}
   202  	if v := ctx.Value("Origin"); v != nil {
   203  		m.Origin = v.(string)
   204  	}
   205  	if v := ctx.Value("User-Agent"); v != nil {
   206  		m.UserAgent = v.(string)
   207  	}
   208  	return m
   209  }
   210  
   211  // String implements Stringer interface
   212  func (m Metadata) String() string {
   213  	s, err := json.Marshal(m)
   214  	if err == nil {
   215  		return string(s)
   216  	}
   217  	return err.Error()
   218  }
   219  
   220  // types for the requests/response types between signer and UI
   221  type (
   222  	// SignTxRequest contains info about a Transaction to sign
   223  	SignTxRequest struct {
   224  		Transaction SendTxArgs       `json:"transaction"`
   225  		Callinfo    []ValidationInfo `json:"call_info"`
   226  		Meta        Metadata         `json:"meta"`
   227  	}
   228  	// SignTxResponse result from SignTxRequest
   229  	SignTxResponse struct {
   230  		//The UI may make changes to the TX
   231  		Transaction SendTxArgs `json:"transaction"`
   232  		Approved    bool       `json:"approved"`
   233  	}
   234  	SignDataRequest struct {
   235  		ContentType string                  `json:"content_type"`
   236  		Address     common.MixedcaseAddress `json:"address"`
   237  		Rawdata     []byte                  `json:"raw_data"`
   238  		Messages    []*NameValueType        `json:"messages"`
   239  		Callinfo    []ValidationInfo        `json:"call_info"`
   240  		Hash        hexutil.Bytes           `json:"hash"`
   241  		Meta        Metadata                `json:"meta"`
   242  	}
   243  	SignDataResponse struct {
   244  		Approved bool `json:"approved"`
   245  	}
   246  	NewAccountRequest struct {
   247  		Meta Metadata `json:"meta"`
   248  	}
   249  	NewAccountResponse struct {
   250  		Approved bool `json:"approved"`
   251  	}
   252  	ListRequest struct {
   253  		Accounts []accounts.Account `json:"accounts"`
   254  		Meta     Metadata           `json:"meta"`
   255  	}
   256  	ListResponse struct {
   257  		Accounts []accounts.Account `json:"accounts"`
   258  	}
   259  	Message struct {
   260  		Text string `json:"text"`
   261  	}
   262  	StartupInfo struct {
   263  		Info map[string]interface{} `json:"info"`
   264  	}
   265  	UserInputRequest struct {
   266  		Title      string `json:"title"`
   267  		Prompt     string `json:"prompt"`
   268  		IsPassword bool   `json:"isPassword"`
   269  	}
   270  	UserInputResponse struct {
   271  		Text string `json:"text"`
   272  	}
   273  )
   274  
   275  var ErrRequestDenied = errors.New("request denied")
   276  
   277  // NewSignerAPI creates a new API that can be used for Account management.
   278  // ksLocation specifies the directory where to store the password protected private
   279  // key that is generated when a new Account is created.
   280  // noUSB disables USB support that is required to support hardware devices such as
   281  // ledger and trezor.
   282  func NewSignerAPI(am *accounts.Manager, chainID int64, noUSB bool, ui UIClientAPI, validator Validator, advancedMode bool, credentials storage.Storage) *SignerAPI {
   283  	if advancedMode {
   284  		log.Info("Clef is in advanced mode: will warn instead of reject")
   285  	}
   286  	signer := &SignerAPI{big.NewInt(chainID), am, ui, validator, !advancedMode, credentials}
   287  	if !noUSB {
   288  		signer.startUSBListener()
   289  	}
   290  	return signer
   291  }
   292  func (api *SignerAPI) openTrezor(url accounts.URL) {
   293  	resp, err := api.UI.OnInputRequired(UserInputRequest{
   294  		Prompt: "Pin required to open Trezor wallet\n" +
   295  			"Look at the device for number positions\n\n" +
   296  			"7 | 8 | 9\n" +
   297  			"--+---+--\n" +
   298  			"4 | 5 | 6\n" +
   299  			"--+---+--\n" +
   300  			"1 | 2 | 3\n\n",
   301  		IsPassword: true,
   302  		Title:      "Trezor unlock",
   303  	})
   304  	if err != nil {
   305  		log.Warn("failed getting trezor pin", "err", err)
   306  		return
   307  	}
   308  	// We're using the URL instead of the pointer to the
   309  	// Wallet -- perhaps it is not actually present anymore
   310  	w, err := api.am.Wallet(url.String())
   311  	if err != nil {
   312  		log.Warn("wallet unavailable", "url", url)
   313  		return
   314  	}
   315  	err = w.Open(resp.Text)
   316  	if err != nil {
   317  		log.Warn("failed to open wallet", "wallet", url, "err", err)
   318  		return
   319  	}
   320  
   321  }
   322  
   323  // startUSBListener starts a listener for USB events, for hardware wallet interaction
   324  func (api *SignerAPI) startUSBListener() {
   325  	events := make(chan accounts.WalletEvent, 16)
   326  	am := api.am
   327  	am.Subscribe(events)
   328  	go func() {
   329  
   330  		// Open any wallets already attached
   331  		for _, wallet := range am.Wallets() {
   332  			if err := wallet.Open(""); err != nil {
   333  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   334  				if err == usbwallet.ErrTrezorPINNeeded {
   335  					go api.openTrezor(wallet.URL())
   336  				}
   337  			}
   338  		}
   339  		// Listen for wallet event till termination
   340  		for event := range events {
   341  			switch event.Kind {
   342  			case accounts.WalletArrived:
   343  				if err := event.Wallet.Open(""); err != nil {
   344  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   345  					if err == usbwallet.ErrTrezorPINNeeded {
   346  						go api.openTrezor(event.Wallet.URL())
   347  					}
   348  				}
   349  			case accounts.WalletOpened:
   350  				status, _ := event.Wallet.Status()
   351  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   352  				var derive = func(numToDerive int, base accounts.DerivationPath) {
   353  					// Derive first N accounts, hardcoded for now
   354  					var nextPath = make(accounts.DerivationPath, len(base))
   355  					copy(nextPath[:], base[:])
   356  
   357  					for i := 0; i < numToDerive; i++ {
   358  						acc, err := event.Wallet.Derive(nextPath, true)
   359  						if err != nil {
   360  							log.Warn("Account derivation failed", "error", err)
   361  						} else {
   362  							log.Info("Derived account", "address", acc.Address, "path", nextPath)
   363  						}
   364  						nextPath[len(nextPath)-1]++
   365  					}
   366  				}
   367  				if event.Wallet.URL().Scheme == "ledger" {
   368  					log.Info("Deriving ledger default paths")
   369  					derive(numberOfAccountsToDerive/2, accounts.DefaultBaseDerivationPath)
   370  					log.Info("Deriving ledger legacy paths")
   371  					derive(numberOfAccountsToDerive/2, accounts.LegacyLedgerBaseDerivationPath)
   372  				} else {
   373  					derive(numberOfAccountsToDerive, accounts.DefaultBaseDerivationPath)
   374  				}
   375  			case accounts.WalletDropped:
   376  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   377  				event.Wallet.Close()
   378  			}
   379  		}
   380  	}()
   381  }
   382  
   383  // List returns the set of wallet this signer manages. Each wallet can contain
   384  // multiple accounts.
   385  func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
   386  	var accs = make([]accounts.Account, 0)
   387  	// accs is initialized as empty list, not nil. We use 'nil' to signal
   388  	// rejection, as opposed to an empty list.
   389  	for _, wallet := range api.am.Wallets() {
   390  		accs = append(accs, wallet.Accounts()...)
   391  	}
   392  	result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
   393  	if err != nil {
   394  		return nil, err
   395  	}
   396  	if result.Accounts == nil {
   397  		return nil, ErrRequestDenied
   398  	}
   399  	addresses := make([]common.Address, 0)
   400  	for _, acc := range result.Accounts {
   401  		addresses = append(addresses, acc.Address)
   402  	}
   403  	return addresses, nil
   404  }
   405  
   406  // New creates a new password protected Account. The private key is protected with
   407  // the given password. Users are responsible to backup the private key that is stored
   408  // in the keystore location thas was specified when this API was created.
   409  func (api *SignerAPI) New(ctx context.Context) (common.Address, error) {
   410  	if be := api.am.Backends(keystore.KeyStoreType); len(be) == 0 {
   411  		return common.Address{}, errors.New("password based accounts not supported")
   412  	}
   413  	if resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)}); err != nil {
   414  		return common.Address{}, err
   415  	} else if !resp.Approved {
   416  		return common.Address{}, ErrRequestDenied
   417  	}
   418  	return api.newAccount()
   419  }
   420  
   421  // newAccount is the internal method to create a new account. It should be used
   422  // _after_ user-approval has been obtained
   423  func (api *SignerAPI) newAccount() (common.Address, error) {
   424  	be := api.am.Backends(keystore.KeyStoreType)
   425  	if len(be) == 0 {
   426  		return common.Address{}, errors.New("password based accounts not supported")
   427  	}
   428  	// Three retries to get a valid password
   429  	for i := 0; i < 3; i++ {
   430  		resp, err := api.UI.OnInputRequired(UserInputRequest{
   431  			"New account password",
   432  			fmt.Sprintf("Please enter a password for the new account to be created (attempt %d of 3)", i),
   433  			true})
   434  		if err != nil {
   435  			log.Warn("error obtaining password", "attempt", i, "error", err)
   436  			continue
   437  		}
   438  		if pwErr := ValidatePasswordFormat(resp.Text); pwErr != nil {
   439  			api.UI.ShowError(fmt.Sprintf("Account creation attempt #%d failed due to password requirements: %v", (i + 1), pwErr))
   440  		} else {
   441  			// No error
   442  			acc, err := be[0].(*keystore.KeyStore).NewAccount(resp.Text)
   443  			log.Info("Your new key was generated", "address", acc.Address)
   444  			log.Warn("Please backup your key file!", "path", acc.URL.Path)
   445  			log.Warn("Please remember your password!")
   446  			return acc.Address, err
   447  		}
   448  	}
   449  	// Otherwise fail, with generic error message
   450  	return common.Address{}, errors.New("account creation failed")
   451  }
   452  
   453  // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
   454  // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
   455  // UI-modifications to requests
   456  func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
   457  	modified := false
   458  	if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
   459  		log.Info("Sender-account changed by UI", "was", f0, "is", f1)
   460  		modified = true
   461  	}
   462  	if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
   463  		log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
   464  		modified = true
   465  	}
   466  	if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
   467  		modified = true
   468  		log.Info("Gas changed by UI", "was", g0, "is", g1)
   469  	}
   470  	if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 {
   471  		modified = true
   472  		log.Info("GasPrice changed by UI", "was", g0, "is", g1)
   473  	}
   474  	if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
   475  		modified = true
   476  		log.Info("Value changed by UI", "was", v0, "is", v1)
   477  	}
   478  	if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
   479  		d0s := ""
   480  		d1s := ""
   481  		if d0 != nil {
   482  			d0s = hexutil.Encode(*d0)
   483  		}
   484  		if d1 != nil {
   485  			d1s = hexutil.Encode(*d1)
   486  		}
   487  		if d1s != d0s {
   488  			modified = true
   489  			log.Info("Data changed by UI", "was", d0s, "is", d1s)
   490  		}
   491  	}
   492  	if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
   493  		modified = true
   494  		log.Info("Nonce changed by UI", "was", n0, "is", n1)
   495  	}
   496  	return modified
   497  }
   498  
   499  func (api *SignerAPI) lookupPassword(address common.Address) (string, error) {
   500  	return api.credentials.Get(address.Hex())
   501  }
   502  
   503  func (api *SignerAPI) lookupOrQueryPassword(address common.Address, title, prompt string) (string, error) {
   504  	// Look up the password and return if available
   505  	if pw, err := api.lookupPassword(address); err == nil {
   506  		return pw, nil
   507  	}
   508  	// Password unavailable, request it from the user
   509  	pwResp, err := api.UI.OnInputRequired(UserInputRequest{title, prompt, true})
   510  	if err != nil {
   511  		log.Warn("error obtaining password", "error", err)
   512  		// We'll not forward the error here, in case the error contains info about the response from the UI,
   513  		// which could leak the password if it was malformed json or something
   514  		return "", errors.New("internal error")
   515  	}
   516  	return pwResp.Text, nil
   517  }
   518  
   519  // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
   520  func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
   521  	var (
   522  		err    error
   523  		result SignTxResponse
   524  	)
   525  	msgs, err := api.validator.ValidateTransaction(methodSelector, &args)
   526  	if err != nil {
   527  		return nil, err
   528  	}
   529  	// If we are in 'rejectMode', then reject rather than show the user warnings
   530  	if api.rejectMode {
   531  		if err := msgs.getWarnings(); err != nil {
   532  			return nil, err
   533  		}
   534  	}
   535  	req := SignTxRequest{
   536  		Transaction: args,
   537  		Meta:        MetadataFromContext(ctx),
   538  		Callinfo:    msgs.Messages,
   539  	}
   540  	// Process approval
   541  	result, err = api.UI.ApproveTx(&req)
   542  	if err != nil {
   543  		return nil, err
   544  	}
   545  	if !result.Approved {
   546  		return nil, ErrRequestDenied
   547  	}
   548  	// Log changes made by the UI to the signing-request
   549  	logDiff(&req, &result)
   550  	var (
   551  		acc    accounts.Account
   552  		wallet accounts.Wallet
   553  	)
   554  	acc = accounts.Account{Address: result.Transaction.From.Address()}
   555  	wallet, err = api.am.Find(acc)
   556  	if err != nil {
   557  		return nil, err
   558  	}
   559  	// Convert fields into a real transaction
   560  	var unsignedTx = result.Transaction.toTransaction()
   561  	// Get the password for the transaction
   562  	pw, err := api.lookupOrQueryPassword(acc.Address, "Account password",
   563  		fmt.Sprintf("Please enter the password for account %s", acc.Address.String()))
   564  	if err != nil {
   565  		return nil, err
   566  	}
   567  	// The one to sign is the one that was returned from the UI
   568  	signedTx, err := wallet.SignTxWithPassphrase(acc, pw, unsignedTx, api.chainID)
   569  	if err != nil {
   570  		api.UI.ShowError(err.Error())
   571  		return nil, err
   572  	}
   573  
   574  	rlpdata, err := rlp.EncodeToBytes(signedTx)
   575  	if err != nil {
   576  		return nil, err
   577  	}
   578  	response := ethapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx}
   579  
   580  	// Finally, send the signed tx to the UI
   581  	api.UI.OnApprovedTx(response)
   582  	// ...and to the external caller
   583  	return &response, nil
   584  
   585  }
   586  
   587  func (api *SignerAPI) SignGnosisSafeTx(ctx context.Context, signerAddress common.MixedcaseAddress, gnosisTx GnosisSafeTx, methodSelector *string) (*GnosisSafeTx, error) {
   588  	// Do the usual validations, but on the last-stage transaction
   589  	args := gnosisTx.ArgsForValidation()
   590  	msgs, err := api.validator.ValidateTransaction(methodSelector, args)
   591  	if err != nil {
   592  		return nil, err
   593  	}
   594  	// If we are in 'rejectMode', then reject rather than show the user warnings
   595  	if api.rejectMode {
   596  		if err := msgs.getWarnings(); err != nil {
   597  			return nil, err
   598  		}
   599  	}
   600  	typedData := gnosisTx.ToTypedData()
   601  	signature, preimage, err := api.signTypedData(ctx, signerAddress, typedData, msgs)
   602  	if err != nil {
   603  		return nil, err
   604  	}
   605  	checkSummedSender, _ := common.NewMixedcaseAddressFromString(signerAddress.Address().Hex())
   606  
   607  	gnosisTx.Signature = signature
   608  	gnosisTx.SafeTxHash = common.BytesToHash(preimage)
   609  	gnosisTx.Sender = *checkSummedSender // Must be checksumed to be accepted by relay
   610  
   611  	return &gnosisTx, nil
   612  }
   613  
   614  // Returns the external api version. This method does not require user acceptance. Available methods are
   615  // available via enumeration anyway, and this info does not contain user-specific data
   616  func (api *SignerAPI) Version(ctx context.Context) (string, error) {
   617  	return ExternalAPIVersion, nil
   618  }