github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/signer/core/api.go (about)

     1  // Copyright 2021 The adkgo Authors
     2  // This file is part of the adkgo library (adapted for adkgo from go--ethereum v1.10.8).
     3  //
     4  // the adkgo 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 adkgo 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 adkgo 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/aidoskuneen/adk-node/accounts"
    29  	"github.com/aidoskuneen/adk-node/accounts/keystore"
    30  	"github.com/aidoskuneen/adk-node/accounts/scwallet"
    31  	"github.com/aidoskuneen/adk-node/accounts/usbwallet"
    32  	"github.com/aidoskuneen/adk-node/common"
    33  	"github.com/aidoskuneen/adk-node/common/hexutil"
    34  	"github.com/aidoskuneen/adk-node/internal/ethapi"
    35  	"github.com/aidoskuneen/adk-node/log"
    36  	"github.com/aidoskuneen/adk-node/signer/core/apitypes"
    37  	"github.com/aidoskuneen/adk-node/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 apitypes.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 *apitypes.SendTxArgs) (*apitypes.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 apitypes.SendTxArgs       `json:"transaction"`
   225  		Callinfo    []apitypes.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 apitypes.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    []apitypes.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  	var intPtrModified = func(a, b *hexutil.Big) bool {
   461  		aBig := (*big.Int)(a)
   462  		bBig := (*big.Int)(b)
   463  		if aBig != nil && bBig != nil {
   464  			return aBig.Cmp(bBig) != 0
   465  		}
   466  		// One or both of them are nil
   467  		return a != b
   468  	}
   469  
   470  	modified := false
   471  	if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
   472  		log.Info("Sender-account changed by UI", "was", f0, "is", f1)
   473  		modified = true
   474  	}
   475  	if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
   476  		log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
   477  		modified = true
   478  	}
   479  	if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
   480  		modified = true
   481  		log.Info("Gas changed by UI", "was", g0, "is", g1)
   482  	}
   483  	if a, b := original.Transaction.GasPrice, new.Transaction.GasPrice; intPtrModified(a, b) {
   484  		log.Info("GasPrice changed by UI", "was", a, "is", b)
   485  		modified = true
   486  	}
   487  	if a, b := original.Transaction.MaxPriorityFeePerGas, new.Transaction.MaxPriorityFeePerGas; intPtrModified(a, b) {
   488  		log.Info("maxPriorityFeePerGas changed by UI", "was", a, "is", b)
   489  		modified = true
   490  	}
   491  	if a, b := original.Transaction.MaxFeePerGas, new.Transaction.MaxFeePerGas; intPtrModified(a, b) {
   492  		log.Info("maxFeePerGas changed by UI", "was", a, "is", b)
   493  		modified = true
   494  	}
   495  	if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
   496  		modified = true
   497  		log.Info("Value changed by UI", "was", v0, "is", v1)
   498  	}
   499  	if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
   500  		d0s := ""
   501  		d1s := ""
   502  		if d0 != nil {
   503  			d0s = hexutil.Encode(*d0)
   504  		}
   505  		if d1 != nil {
   506  			d1s = hexutil.Encode(*d1)
   507  		}
   508  		if d1s != d0s {
   509  			modified = true
   510  			log.Info("Data changed by UI", "was", d0s, "is", d1s)
   511  		}
   512  	}
   513  	if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
   514  		modified = true
   515  		log.Info("Nonce changed by UI", "was", n0, "is", n1)
   516  	}
   517  	return modified
   518  }
   519  
   520  func (api *SignerAPI) lookupPassword(address common.Address) (string, error) {
   521  	return api.credentials.Get(address.Hex())
   522  }
   523  
   524  func (api *SignerAPI) lookupOrQueryPassword(address common.Address, title, prompt string) (string, error) {
   525  	// Look up the password and return if available
   526  	if pw, err := api.lookupPassword(address); err == nil {
   527  		return pw, nil
   528  	}
   529  	// Password unavailable, request it from the user
   530  	pwResp, err := api.UI.OnInputRequired(UserInputRequest{title, prompt, true})
   531  	if err != nil {
   532  		log.Warn("error obtaining password", "error", err)
   533  		// We'll not forward the error here, in case the error contains info about the response from the UI,
   534  		// which could leak the password if it was malformed json or something
   535  		return "", errors.New("internal error")
   536  	}
   537  	return pwResp.Text, nil
   538  }
   539  
   540  // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
   541  func (api *SignerAPI) SignTransaction(ctx context.Context, args apitypes.SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
   542  	var (
   543  		err    error
   544  		result SignTxResponse
   545  	)
   546  	msgs, err := api.validator.ValidateTransaction(methodSelector, &args)
   547  	if err != nil {
   548  		return nil, err
   549  	}
   550  	// If we are in 'rejectMode', then reject rather than show the user warnings
   551  	if api.rejectMode {
   552  		if err := msgs.GetWarnings(); err != nil {
   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 := ethapi.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  
   616  func (api *SignerAPI) SignGnosisSafeTx(ctx context.Context, signerAddress common.MixedcaseAddress, gnosisTx GnosisSafeTx, methodSelector *string) (*GnosisSafeTx, error) {
   617  	// Do the usual validations, but on the last-stage transaction
   618  	args := gnosisTx.ArgsForValidation()
   619  	msgs, err := api.validator.ValidateTransaction(methodSelector, args)
   620  	if err != nil {
   621  		return nil, err
   622  	}
   623  	// If we are in 'rejectMode', then reject rather than show the user warnings
   624  	if api.rejectMode {
   625  		if err := msgs.GetWarnings(); err != nil {
   626  			return nil, err
   627  		}
   628  	}
   629  	typedData := gnosisTx.ToTypedData()
   630  	signature, preimage, err := api.signTypedData(ctx, signerAddress, typedData, msgs)
   631  	if err != nil {
   632  		return nil, err
   633  	}
   634  	checkSummedSender, _ := common.NewMixedcaseAddressFromString(signerAddress.Address().Hex())
   635  
   636  	gnosisTx.Signature = signature
   637  	gnosisTx.SafeTxHash = common.BytesToHash(preimage)
   638  	gnosisTx.Sender = *checkSummedSender // Must be checksumed to be accepted by relay
   639  
   640  	return &gnosisTx, nil
   641  }
   642  
   643  // Returns the external api version. This method does not require user acceptance. Available methods are
   644  // available via enumeration anyway, and this info does not contain user-specific data
   645  func (api *SignerAPI) Version(ctx context.Context) (string, error) {
   646  	return ExternalAPIVersion, nil
   647  }