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