github.com/cryptogateway/go-paymex@v0.0.0-20210204174735-96277fb1e602/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/cryptogateway/go-paymex/accounts"
    29  	"github.com/cryptogateway/go-paymex/accounts/keystore"
    30  	"github.com/cryptogateway/go-paymex/accounts/scwallet"
    31  	"github.com/cryptogateway/go-paymex/accounts/usbwallet"
    32  	"github.com/cryptogateway/go-paymex/common"
    33  	"github.com/cryptogateway/go-paymex/common/hexutil"
    34  	"github.com/cryptogateway/go-paymex/internal/ethapi"
    35  	"github.com/cryptogateway/go-paymex/log"
    36  	"github.com/cryptogateway/go-paymex/rlp"
    37  	"github.com/cryptogateway/go-paymex/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  	eventCh := make(chan accounts.WalletEvent, 16)
   326  	am := api.am
   327  	am.Subscribe(eventCh)
   328  	// Open any wallets already attached
   329  	for _, wallet := range am.Wallets() {
   330  		if err := wallet.Open(""); err != nil {
   331  			log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   332  			if err == usbwallet.ErrTrezorPINNeeded {
   333  				go api.openTrezor(wallet.URL())
   334  			}
   335  		}
   336  	}
   337  	go api.derivationLoop(eventCh)
   338  }
   339  
   340  // derivationLoop listens for wallet events
   341  func (api *SignerAPI) derivationLoop(events chan accounts.WalletEvent) {
   342  	// Listen for wallet event till termination
   343  	for event := range events {
   344  		switch event.Kind {
   345  		case accounts.WalletArrived:
   346  			if err := event.Wallet.Open(""); err != nil {
   347  				log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   348  				if err == usbwallet.ErrTrezorPINNeeded {
   349  					go api.openTrezor(event.Wallet.URL())
   350  				}
   351  			}
   352  		case accounts.WalletOpened:
   353  			status, _ := event.Wallet.Status()
   354  			log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   355  			var derive = func(limit int, next func() accounts.DerivationPath) {
   356  				// Derive first N accounts, hardcoded for now
   357  				for i := 0; i < limit; i++ {
   358  					path := next()
   359  					if acc, err := event.Wallet.Derive(path, true); err != nil {
   360  						log.Warn("Account derivation failed", "error", err)
   361  					} else {
   362  						log.Info("Derived account", "address", acc.Address, "path", path)
   363  					}
   364  				}
   365  			}
   366  			log.Info("Deriving default paths")
   367  			derive(numberOfAccountsToDerive, accounts.DefaultIterator(accounts.DefaultBaseDerivationPath))
   368  			if event.Wallet.URL().Scheme == "ledger" {
   369  				log.Info("Deriving ledger legacy paths")
   370  				derive(numberOfAccountsToDerive, accounts.DefaultIterator(accounts.LegacyLedgerBaseDerivationPath))
   371  				log.Info("Deriving ledger live paths")
   372  				// For ledger live, since it's based off the same (DefaultBaseDerivationPath)
   373  				// as one we've already used, we need to step it forward one step to avoid
   374  				// hitting the same path again
   375  				nextFn := accounts.LedgerLiveIterator(accounts.DefaultBaseDerivationPath)
   376  				nextFn()
   377  				derive(numberOfAccountsToDerive, nextFn)
   378  			}
   379  		case accounts.WalletDropped:
   380  			log.Info("Old wallet dropped", "url", event.Wallet.URL())
   381  			event.Wallet.Close()
   382  		}
   383  	}
   384  }
   385  
   386  // List returns the set of wallet this signer manages. Each wallet can contain
   387  // multiple accounts.
   388  func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
   389  	var accs = make([]accounts.Account, 0)
   390  	// accs is initialized as empty list, not nil. We use 'nil' to signal
   391  	// rejection, as opposed to an empty list.
   392  	for _, wallet := range api.am.Wallets() {
   393  		accs = append(accs, wallet.Accounts()...)
   394  	}
   395  	result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
   396  	if err != nil {
   397  		return nil, err
   398  	}
   399  	if result.Accounts == nil {
   400  		return nil, ErrRequestDenied
   401  	}
   402  	addresses := make([]common.Address, 0)
   403  	for _, acc := range result.Accounts {
   404  		addresses = append(addresses, acc.Address)
   405  	}
   406  	return addresses, nil
   407  }
   408  
   409  // New creates a new password protected Account. The private key is protected with
   410  // the given password. Users are responsible to backup the private key that is stored
   411  // in the keystore location thas was specified when this API was created.
   412  func (api *SignerAPI) New(ctx context.Context) (common.Address, error) {
   413  	if be := api.am.Backends(keystore.KeyStoreType); len(be) == 0 {
   414  		return common.Address{}, errors.New("password based accounts not supported")
   415  	}
   416  	if resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)}); err != nil {
   417  		return common.Address{}, err
   418  	} else if !resp.Approved {
   419  		return common.Address{}, ErrRequestDenied
   420  	}
   421  	return api.newAccount()
   422  }
   423  
   424  // newAccount is the internal method to create a new account. It should be used
   425  // _after_ user-approval has been obtained
   426  func (api *SignerAPI) newAccount() (common.Address, error) {
   427  	be := api.am.Backends(keystore.KeyStoreType)
   428  	if len(be) == 0 {
   429  		return common.Address{}, errors.New("password based accounts not supported")
   430  	}
   431  	// Three retries to get a valid password
   432  	for i := 0; i < 3; i++ {
   433  		resp, err := api.UI.OnInputRequired(UserInputRequest{
   434  			"New account password",
   435  			fmt.Sprintf("Please enter a password for the new account to be created (attempt %d of 3)", i),
   436  			true})
   437  		if err != nil {
   438  			log.Warn("error obtaining password", "attempt", i, "error", err)
   439  			continue
   440  		}
   441  		if pwErr := ValidatePasswordFormat(resp.Text); pwErr != nil {
   442  			api.UI.ShowError(fmt.Sprintf("Account creation attempt #%d failed due to password requirements: %v", i+1, pwErr))
   443  		} else {
   444  			// No error
   445  			acc, err := be[0].(*keystore.KeyStore).NewAccount(resp.Text)
   446  			log.Info("Your new key was generated", "address", acc.Address)
   447  			log.Warn("Please backup your key file!", "path", acc.URL.Path)
   448  			log.Warn("Please remember your password!")
   449  			return acc.Address, err
   450  		}
   451  	}
   452  	// Otherwise fail, with generic error message
   453  	return common.Address{}, errors.New("account creation failed")
   454  }
   455  
   456  // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
   457  // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
   458  // UI-modifications to requests
   459  func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
   460  	modified := false
   461  	if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
   462  		log.Info("Sender-account changed by UI", "was", f0, "is", f1)
   463  		modified = true
   464  	}
   465  	if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
   466  		log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
   467  		modified = true
   468  	}
   469  	if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
   470  		modified = true
   471  		log.Info("Gas changed by UI", "was", g0, "is", g1)
   472  	}
   473  	if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 {
   474  		modified = true
   475  		log.Info("GasPrice changed by UI", "was", g0, "is", g1)
   476  	}
   477  	if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
   478  		modified = true
   479  		log.Info("Value changed by UI", "was", v0, "is", v1)
   480  	}
   481  	if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
   482  		d0s := ""
   483  		d1s := ""
   484  		if d0 != nil {
   485  			d0s = hexutil.Encode(*d0)
   486  		}
   487  		if d1 != nil {
   488  			d1s = hexutil.Encode(*d1)
   489  		}
   490  		if d1s != d0s {
   491  			modified = true
   492  			log.Info("Data changed by UI", "was", d0s, "is", d1s)
   493  		}
   494  	}
   495  	if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
   496  		modified = true
   497  		log.Info("Nonce changed by UI", "was", n0, "is", n1)
   498  	}
   499  	return modified
   500  }
   501  
   502  func (api *SignerAPI) lookupPassword(address common.Address) (string, error) {
   503  	return api.credentials.Get(address.Hex())
   504  }
   505  
   506  func (api *SignerAPI) lookupOrQueryPassword(address common.Address, title, prompt string) (string, error) {
   507  	// Look up the password and return if available
   508  	if pw, err := api.lookupPassword(address); err == nil {
   509  		return pw, nil
   510  	}
   511  	// Password unavailable, request it from the user
   512  	pwResp, err := api.UI.OnInputRequired(UserInputRequest{title, prompt, true})
   513  	if err != nil {
   514  		log.Warn("error obtaining password", "error", err)
   515  		// We'll not forward the error here, in case the error contains info about the response from the UI,
   516  		// which could leak the password if it was malformed json or something
   517  		return "", errors.New("internal error")
   518  	}
   519  	return pwResp.Text, nil
   520  }
   521  
   522  // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
   523  func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
   524  	var (
   525  		err    error
   526  		result SignTxResponse
   527  	)
   528  	msgs, err := api.validator.ValidateTransaction(methodSelector, &args)
   529  	if err != nil {
   530  		return nil, err
   531  	}
   532  	// If we are in 'rejectMode', then reject rather than show the user warnings
   533  	if api.rejectMode {
   534  		if err := msgs.getWarnings(); err != nil {
   535  			return nil, err
   536  		}
   537  	}
   538  	req := SignTxRequest{
   539  		Transaction: args,
   540  		Meta:        MetadataFromContext(ctx),
   541  		Callinfo:    msgs.Messages,
   542  	}
   543  	// Process approval
   544  	result, err = api.UI.ApproveTx(&req)
   545  	if err != nil {
   546  		return nil, err
   547  	}
   548  	if !result.Approved {
   549  		return nil, ErrRequestDenied
   550  	}
   551  	// Log changes made by the UI to the signing-request
   552  	logDiff(&req, &result)
   553  	var (
   554  		acc    accounts.Account
   555  		wallet accounts.Wallet
   556  	)
   557  	acc = accounts.Account{Address: result.Transaction.From.Address()}
   558  	wallet, err = api.am.Find(acc)
   559  	if err != nil {
   560  		return nil, err
   561  	}
   562  	// Convert fields into a real transaction
   563  	var unsignedTx = result.Transaction.toTransaction()
   564  	// Get the password for the transaction
   565  	pw, err := api.lookupOrQueryPassword(acc.Address, "Account password",
   566  		fmt.Sprintf("Please enter the password for account %s", acc.Address.String()))
   567  	if err != nil {
   568  		return nil, err
   569  	}
   570  	// The one to sign is the one that was returned from the UI
   571  	signedTx, err := wallet.SignTxWithPassphrase(acc, pw, unsignedTx, api.chainID)
   572  	if err != nil {
   573  		api.UI.ShowError(err.Error())
   574  		return nil, err
   575  	}
   576  
   577  	rlpdata, err := rlp.EncodeToBytes(signedTx)
   578  	if err != nil {
   579  		return nil, err
   580  	}
   581  	response := ethapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx}
   582  
   583  	// Finally, send the signed tx to the UI
   584  	api.UI.OnApprovedTx(response)
   585  	// ...and to the external caller
   586  	return &response, nil
   587  
   588  }
   589  
   590  func (api *SignerAPI) SignGnosisSafeTx(ctx context.Context, signerAddress common.MixedcaseAddress, gnosisTx GnosisSafeTx, methodSelector *string) (*GnosisSafeTx, error) {
   591  	// Do the usual validations, but on the last-stage transaction
   592  	args := gnosisTx.ArgsForValidation()
   593  	msgs, err := api.validator.ValidateTransaction(methodSelector, args)
   594  	if err != nil {
   595  		return nil, err
   596  	}
   597  	// If we are in 'rejectMode', then reject rather than show the user warnings
   598  	if api.rejectMode {
   599  		if err := msgs.getWarnings(); err != nil {
   600  			return nil, err
   601  		}
   602  	}
   603  	typedData := gnosisTx.ToTypedData()
   604  	signature, preimage, err := api.signTypedData(ctx, signerAddress, typedData, msgs)
   605  	if err != nil {
   606  		return nil, err
   607  	}
   608  	checkSummedSender, _ := common.NewMixedcaseAddressFromString(signerAddress.Address().Hex())
   609  
   610  	gnosisTx.Signature = signature
   611  	gnosisTx.SafeTxHash = common.BytesToHash(preimage)
   612  	gnosisTx.Sender = *checkSummedSender // Must be checksumed to be accepted by relay
   613  
   614  	return &gnosisTx, nil
   615  }
   616  
   617  // Returns the external api version. This method does not require user acceptance. Available methods are
   618  // available via enumeration anyway, and this info does not contain user-specific data
   619  func (api *SignerAPI) Version(ctx context.Context) (string, error) {
   620  	return ExternalAPIVersion, nil
   621  }