github.com/xfond/eth-implementation@v1.8.9-0.20180514135602-f6bc65fc6811/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  	"io/ioutil"
    25  	"math/big"
    26  	"reflect"
    27  
    28  	"github.com/ethereum/go-ethereum/accounts"
    29  	"github.com/ethereum/go-ethereum/accounts/keystore"
    30  	"github.com/ethereum/go-ethereum/accounts/usbwallet"
    31  	"github.com/ethereum/go-ethereum/common"
    32  	"github.com/ethereum/go-ethereum/common/hexutil"
    33  	"github.com/ethereum/go-ethereum/crypto"
    34  	"github.com/ethereum/go-ethereum/internal/ethapi"
    35  	"github.com/ethereum/go-ethereum/log"
    36  	"github.com/ethereum/go-ethereum/rlp"
    37  )
    38  
    39  // ExternalAPI defines the external API through which signing requests are made.
    40  type ExternalAPI interface {
    41  	// List available accounts
    42  	List(ctx context.Context) (Accounts, error)
    43  	// New request to create a new account
    44  	New(ctx context.Context) (accounts.Account, error)
    45  	// SignTransaction request to sign the specified transaction
    46  	SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error)
    47  	// Sign - request to sign the given data (plus prefix)
    48  	Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error)
    49  	// EcRecover - request to perform ecrecover
    50  	EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error)
    51  	// Export - request to export an account
    52  	Export(ctx context.Context, addr common.Address) (json.RawMessage, error)
    53  	// Import - request to import an account
    54  	Import(ctx context.Context, keyJSON json.RawMessage) (Account, error)
    55  }
    56  
    57  // SignerUI specifies what method a UI needs to implement to be able to be used as a UI for the signer
    58  type SignerUI interface {
    59  	// ApproveTx prompt the user for confirmation to request to sign Transaction
    60  	ApproveTx(request *SignTxRequest) (SignTxResponse, error)
    61  	// ApproveSignData prompt the user for confirmation to request to sign data
    62  	ApproveSignData(request *SignDataRequest) (SignDataResponse, error)
    63  	// ApproveExport prompt the user for confirmation to export encrypted Account json
    64  	ApproveExport(request *ExportRequest) (ExportResponse, error)
    65  	// ApproveImport prompt the user for confirmation to import Account json
    66  	ApproveImport(request *ImportRequest) (ImportResponse, error)
    67  	// ApproveListing prompt the user for confirmation to list accounts
    68  	// the list of accounts to list can be modified by the UI
    69  	ApproveListing(request *ListRequest) (ListResponse, error)
    70  	// ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
    71  	ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error)
    72  	// ShowError displays error message to user
    73  	ShowError(message string)
    74  	// ShowInfo displays info message to user
    75  	ShowInfo(message string)
    76  	// OnApprovedTx notifies the UI about a transaction having been successfully signed.
    77  	// This method can be used by a UI to keep track of e.g. how much has been sent to a particular recipient.
    78  	OnApprovedTx(tx ethapi.SignTransactionResult)
    79  	// OnSignerStartup is invoked when the signer boots, and tells the UI info about external API location and version
    80  	// information
    81  	OnSignerStartup(info StartupInfo)
    82  }
    83  
    84  // SignerAPI defines the actual implementation of ExternalAPI
    85  type SignerAPI struct {
    86  	chainID   *big.Int
    87  	am        *accounts.Manager
    88  	UI        SignerUI
    89  	validator *Validator
    90  }
    91  
    92  // Metadata about a request
    93  type Metadata struct {
    94  	Remote string `json:"remote"`
    95  	Local  string `json:"local"`
    96  	Scheme string `json:"scheme"`
    97  }
    98  
    99  // MetadataFromContext extracts Metadata from a given context.Context
   100  func MetadataFromContext(ctx context.Context) Metadata {
   101  	m := Metadata{"NA", "NA", "NA"} // batman
   102  
   103  	if v := ctx.Value("remote"); v != nil {
   104  		m.Remote = v.(string)
   105  	}
   106  	if v := ctx.Value("scheme"); v != nil {
   107  		m.Scheme = v.(string)
   108  	}
   109  	if v := ctx.Value("local"); v != nil {
   110  		m.Local = v.(string)
   111  	}
   112  	return m
   113  }
   114  
   115  // String implements Stringer interface
   116  func (m Metadata) String() string {
   117  	s, err := json.Marshal(m)
   118  	if err == nil {
   119  		return string(s)
   120  	}
   121  	return err.Error()
   122  }
   123  
   124  // types for the requests/response types between signer and UI
   125  type (
   126  	// SignTxRequest contains info about a Transaction to sign
   127  	SignTxRequest struct {
   128  		Transaction SendTxArgs       `json:"transaction"`
   129  		Callinfo    []ValidationInfo `json:"call_info"`
   130  		Meta        Metadata         `json:"meta"`
   131  	}
   132  	// SignTxResponse result from SignTxRequest
   133  	SignTxResponse struct {
   134  		//The UI may make changes to the TX
   135  		Transaction SendTxArgs `json:"transaction"`
   136  		Approved    bool       `json:"approved"`
   137  		Password    string     `json:"password"`
   138  	}
   139  	// ExportRequest info about query to export accounts
   140  	ExportRequest struct {
   141  		Address common.Address `json:"address"`
   142  		Meta    Metadata       `json:"meta"`
   143  	}
   144  	// ExportResponse response to export-request
   145  	ExportResponse struct {
   146  		Approved bool `json:"approved"`
   147  	}
   148  	// ImportRequest info about request to import an Account
   149  	ImportRequest struct {
   150  		Meta Metadata `json:"meta"`
   151  	}
   152  	ImportResponse struct {
   153  		Approved    bool   `json:"approved"`
   154  		OldPassword string `json:"old_password"`
   155  		NewPassword string `json:"new_password"`
   156  	}
   157  	SignDataRequest struct {
   158  		Address common.MixedcaseAddress `json:"address"`
   159  		Rawdata hexutil.Bytes           `json:"raw_data"`
   160  		Message string                  `json:"message"`
   161  		Hash    hexutil.Bytes           `json:"hash"`
   162  		Meta    Metadata                `json:"meta"`
   163  	}
   164  	SignDataResponse struct {
   165  		Approved bool `json:"approved"`
   166  		Password string
   167  	}
   168  	NewAccountRequest struct {
   169  		Meta Metadata `json:"meta"`
   170  	}
   171  	NewAccountResponse struct {
   172  		Approved bool   `json:"approved"`
   173  		Password string `json:"password"`
   174  	}
   175  	ListRequest struct {
   176  		Accounts []Account `json:"accounts"`
   177  		Meta     Metadata  `json:"meta"`
   178  	}
   179  	ListResponse struct {
   180  		Accounts []Account `json:"accounts"`
   181  	}
   182  	Message struct {
   183  		Text string `json:"text"`
   184  	}
   185  	StartupInfo struct {
   186  		Info map[string]interface{} `json:"info"`
   187  	}
   188  )
   189  
   190  var ErrRequestDenied = errors.New("Request denied")
   191  
   192  type errorWrapper struct {
   193  	msg string
   194  	err error
   195  }
   196  
   197  func (ew errorWrapper) String() string {
   198  	return fmt.Sprintf("%s\n%s", ew.msg, ew.err)
   199  }
   200  
   201  // NewSignerAPI creates a new API that can be used for Account management.
   202  // ksLocation specifies the directory where to store the password protected private
   203  // key that is generated when a new Account is created.
   204  // noUSB disables USB support that is required to support hardware devices such as
   205  // ledger and trezor.
   206  func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abidb *AbiDb, lightKDF bool) *SignerAPI {
   207  	var (
   208  		backends []accounts.Backend
   209  		n, p     = keystore.StandardScryptN, keystore.StandardScryptP
   210  	)
   211  	if lightKDF {
   212  		n, p = keystore.LightScryptN, keystore.LightScryptP
   213  	}
   214  	// support password based accounts
   215  	if len(ksLocation) > 0 {
   216  		backends = append(backends, keystore.NewKeyStore(ksLocation, n, p))
   217  	}
   218  	if !noUSB {
   219  		// Start a USB hub for Ledger hardware wallets
   220  		if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
   221  			log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
   222  		} else {
   223  			backends = append(backends, ledgerhub)
   224  			log.Debug("Ledger support enabled")
   225  		}
   226  		// Start a USB hub for Trezor hardware wallets
   227  		if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
   228  			log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
   229  		} else {
   230  			backends = append(backends, trezorhub)
   231  			log.Debug("Trezor support enabled")
   232  		}
   233  	}
   234  	return &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb)}
   235  }
   236  
   237  // List returns the set of wallet this signer manages. Each wallet can contain
   238  // multiple accounts.
   239  func (api *SignerAPI) List(ctx context.Context) (Accounts, error) {
   240  	var accs []Account
   241  	for _, wallet := range api.am.Wallets() {
   242  		for _, acc := range wallet.Accounts() {
   243  			acc := Account{Typ: "Account", URL: wallet.URL(), Address: acc.Address}
   244  			accs = append(accs, acc)
   245  		}
   246  	}
   247  	result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
   248  	if err != nil {
   249  		return nil, err
   250  	}
   251  	if result.Accounts == nil {
   252  		return nil, ErrRequestDenied
   253  
   254  	}
   255  	return result.Accounts, nil
   256  }
   257  
   258  // New creates a new password protected Account. The private key is protected with
   259  // the given password. Users are responsible to backup the private key that is stored
   260  // in the keystore location thas was specified when this API was created.
   261  func (api *SignerAPI) New(ctx context.Context) (accounts.Account, error) {
   262  	be := api.am.Backends(keystore.KeyStoreType)
   263  	if len(be) == 0 {
   264  		return accounts.Account{}, errors.New("password based accounts not supported")
   265  	}
   266  	resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)})
   267  
   268  	if err != nil {
   269  		return accounts.Account{}, err
   270  	}
   271  	if !resp.Approved {
   272  		return accounts.Account{}, ErrRequestDenied
   273  	}
   274  	return be[0].(*keystore.KeyStore).NewAccount(resp.Password)
   275  }
   276  
   277  // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
   278  // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
   279  // UI-modifications to requests
   280  func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
   281  	modified := false
   282  	if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
   283  		log.Info("Sender-account changed by UI", "was", f0, "is", f1)
   284  		modified = true
   285  	}
   286  	if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
   287  		log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
   288  		modified = true
   289  	}
   290  	if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
   291  		modified = true
   292  		log.Info("Gas changed by UI", "was", g0, "is", g1)
   293  	}
   294  	if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 {
   295  		modified = true
   296  		log.Info("GasPrice changed by UI", "was", g0, "is", g1)
   297  	}
   298  	if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
   299  		modified = true
   300  		log.Info("Value changed by UI", "was", v0, "is", v1)
   301  	}
   302  	if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
   303  		d0s := ""
   304  		d1s := ""
   305  		if d0 != nil {
   306  			d0s = common.ToHex(*d0)
   307  		}
   308  		if d1 != nil {
   309  			d1s = common.ToHex(*d1)
   310  		}
   311  		if d1s != d0s {
   312  			modified = true
   313  			log.Info("Data changed by UI", "was", d0s, "is", d1s)
   314  		}
   315  	}
   316  	if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
   317  		modified = true
   318  		log.Info("Nonce changed by UI", "was", n0, "is", n1)
   319  	}
   320  	return modified
   321  }
   322  
   323  // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
   324  func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
   325  	var (
   326  		err    error
   327  		result SignTxResponse
   328  	)
   329  	msgs, err := api.validator.ValidateTransaction(&args, methodSelector)
   330  	if err != nil {
   331  		return nil, err
   332  	}
   333  
   334  	req := SignTxRequest{
   335  		Transaction: args,
   336  		Meta:        MetadataFromContext(ctx),
   337  		Callinfo:    msgs.Messages,
   338  	}
   339  	// Process approval
   340  	result, err = api.UI.ApproveTx(&req)
   341  	if err != nil {
   342  		return nil, err
   343  	}
   344  	if !result.Approved {
   345  		return nil, ErrRequestDenied
   346  	}
   347  	// Log changes made by the UI to the signing-request
   348  	logDiff(&req, &result)
   349  	var (
   350  		acc    accounts.Account
   351  		wallet accounts.Wallet
   352  	)
   353  	acc = accounts.Account{Address: result.Transaction.From.Address()}
   354  	wallet, err = api.am.Find(acc)
   355  	if err != nil {
   356  		return nil, err
   357  	}
   358  	// Convert fields into a real transaction
   359  	var unsignedTx = result.Transaction.toTransaction()
   360  
   361  	// The one to sign is the one that was returned from the UI
   362  	signedTx, err := wallet.SignTxWithPassphrase(acc, result.Password, unsignedTx, api.chainID)
   363  	if err != nil {
   364  		api.UI.ShowError(err.Error())
   365  		return nil, err
   366  	}
   367  
   368  	rlpdata, err := rlp.EncodeToBytes(signedTx)
   369  	response := ethapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx}
   370  
   371  	// Finally, send the signed tx to the UI
   372  	api.UI.OnApprovedTx(response)
   373  	// ...and to the external caller
   374  	return &response, nil
   375  
   376  }
   377  
   378  // Sign calculates an Ethereum ECDSA signature for:
   379  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
   380  //
   381  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
   382  // where the V value will be 27 or 28 for legacy reasons.
   383  //
   384  // The key used to calculate the signature is decrypted with the given password.
   385  //
   386  // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
   387  func (api *SignerAPI) Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error) {
   388  	sighash, msg := SignHash(data)
   389  	// We make the request prior to looking up if we actually have the account, to prevent
   390  	// account-enumeration via the API
   391  	req := &SignDataRequest{Address: addr, Rawdata: data, Message: msg, Hash: sighash, Meta: MetadataFromContext(ctx)}
   392  	res, err := api.UI.ApproveSignData(req)
   393  
   394  	if err != nil {
   395  		return nil, err
   396  	}
   397  	if !res.Approved {
   398  		return nil, ErrRequestDenied
   399  	}
   400  	// Look up the wallet containing the requested signer
   401  	account := accounts.Account{Address: addr.Address()}
   402  	wallet, err := api.am.Find(account)
   403  	if err != nil {
   404  		return nil, err
   405  	}
   406  	// Assemble sign the data with the wallet
   407  	signature, err := wallet.SignHashWithPassphrase(account, res.Password, sighash)
   408  	if err != nil {
   409  		api.UI.ShowError(err.Error())
   410  		return nil, err
   411  	}
   412  	signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
   413  	return signature, nil
   414  }
   415  
   416  // EcRecover returns the address for the Account that was used to create the signature.
   417  // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
   418  // the address of:
   419  // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
   420  // addr = ecrecover(hash, signature)
   421  //
   422  // Note, the signature must conform to the secp256k1 curve R, S and V values, where
   423  // the V value must be be 27 or 28 for legacy reasons.
   424  //
   425  // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
   426  func (api *SignerAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
   427  	if len(sig) != 65 {
   428  		return common.Address{}, fmt.Errorf("signature must be 65 bytes long")
   429  	}
   430  	if sig[64] != 27 && sig[64] != 28 {
   431  		return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
   432  	}
   433  	sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
   434  	hash, _ := SignHash(data)
   435  	rpk, err := crypto.Ecrecover(hash, sig)
   436  	if err != nil {
   437  		return common.Address{}, err
   438  	}
   439  	pubKey := crypto.ToECDSAPub(rpk)
   440  	recoveredAddr := crypto.PubkeyToAddress(*pubKey)
   441  	return recoveredAddr, nil
   442  }
   443  
   444  // SignHash is a helper function that calculates a hash for the given message that can be
   445  // safely used to calculate a signature from.
   446  //
   447  // The hash is calculated as
   448  //   keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
   449  //
   450  // This gives context to the signed message and prevents signing of transactions.
   451  func SignHash(data []byte) ([]byte, string) {
   452  	msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
   453  	return crypto.Keccak256([]byte(msg)), msg
   454  }
   455  
   456  // Export returns encrypted private key associated with the given address in web3 keystore format.
   457  func (api *SignerAPI) Export(ctx context.Context, addr common.Address) (json.RawMessage, error) {
   458  	res, err := api.UI.ApproveExport(&ExportRequest{Address: addr, Meta: MetadataFromContext(ctx)})
   459  
   460  	if err != nil {
   461  		return nil, err
   462  	}
   463  	if !res.Approved {
   464  		return nil, ErrRequestDenied
   465  	}
   466  	// Look up the wallet containing the requested signer
   467  	wallet, err := api.am.Find(accounts.Account{Address: addr})
   468  	if err != nil {
   469  		return nil, err
   470  	}
   471  	if wallet.URL().Scheme != keystore.KeyStoreScheme {
   472  		return nil, fmt.Errorf("Account is not a keystore-account")
   473  	}
   474  	return ioutil.ReadFile(wallet.URL().Path)
   475  }
   476  
   477  // Import tries to import the given keyJSON in the local keystore. The keyJSON data is expected to be
   478  // in web3 keystore format. It will decrypt the keyJSON with the given passphrase and on successful
   479  // decryption it will encrypt the key with the given newPassphrase and store it in the keystore.
   480  func (api *SignerAPI) Import(ctx context.Context, keyJSON json.RawMessage) (Account, error) {
   481  	be := api.am.Backends(keystore.KeyStoreType)
   482  
   483  	if len(be) == 0 {
   484  		return Account{}, errors.New("password based accounts not supported")
   485  	}
   486  	res, err := api.UI.ApproveImport(&ImportRequest{Meta: MetadataFromContext(ctx)})
   487  
   488  	if err != nil {
   489  		return Account{}, err
   490  	}
   491  	if !res.Approved {
   492  		return Account{}, ErrRequestDenied
   493  	}
   494  	acc, err := be[0].(*keystore.KeyStore).Import(keyJSON, res.OldPassword, res.NewPassword)
   495  	if err != nil {
   496  		api.UI.ShowError(err.Error())
   497  		return Account{}, err
   498  	}
   499  	return Account{Typ: "Account", URL: acc.URL, Address: acc.Address}, nil
   500  }