github.com/daeglee/go-ethereum@v0.0.0-20190504220456-cad3e8d18e9b/signer/core/api.go (about)

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