github.com/ConsenSys/Quorum@v20.10.0+incompatible/accounts/external/backend.go (about)

     1  // Copyright 2019 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 external
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  	"sync"
    23  
    24  	"github.com/ethereum/go-ethereum"
    25  	"github.com/ethereum/go-ethereum/accounts"
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/common/hexutil"
    28  	"github.com/ethereum/go-ethereum/core/types"
    29  	"github.com/ethereum/go-ethereum/event"
    30  	"github.com/ethereum/go-ethereum/internal/ethapi"
    31  	"github.com/ethereum/go-ethereum/log"
    32  	"github.com/ethereum/go-ethereum/rpc"
    33  	"github.com/ethereum/go-ethereum/signer/core"
    34  )
    35  
    36  type ExternalBackend struct {
    37  	signers []accounts.Wallet
    38  }
    39  
    40  func (eb *ExternalBackend) Wallets() []accounts.Wallet {
    41  	return eb.signers
    42  }
    43  
    44  func NewExternalBackend(endpoint string) (*ExternalBackend, error) {
    45  	signer, err := NewExternalSigner(endpoint)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	return &ExternalBackend{
    50  		signers: []accounts.Wallet{signer},
    51  	}, nil
    52  }
    53  
    54  func (eb *ExternalBackend) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
    55  	return event.NewSubscription(func(quit <-chan struct{}) error {
    56  		<-quit
    57  		return nil
    58  	})
    59  }
    60  
    61  // ExternalSigner provides an API to interact with an external signer (clef)
    62  // It proxies request to the external signer while forwarding relevant
    63  // request headers
    64  type ExternalSigner struct {
    65  	client   *rpc.Client
    66  	endpoint string
    67  	status   string
    68  	cacheMu  sync.RWMutex
    69  	cache    []accounts.Account
    70  }
    71  
    72  func NewExternalSigner(endpoint string) (*ExternalSigner, error) {
    73  	client, err := rpc.Dial(endpoint)
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  	extsigner := &ExternalSigner{
    78  		client:   client,
    79  		endpoint: endpoint,
    80  	}
    81  	// Check if reachable
    82  	version, err := extsigner.pingVersion()
    83  	if err != nil {
    84  		return nil, err
    85  	}
    86  	extsigner.status = fmt.Sprintf("ok [version=%v]", version)
    87  	return extsigner, nil
    88  }
    89  
    90  func (api *ExternalSigner) URL() accounts.URL {
    91  	return accounts.URL{
    92  		Scheme: "extapi",
    93  		Path:   api.endpoint,
    94  	}
    95  }
    96  
    97  func (api *ExternalSigner) Status() (string, error) {
    98  	return api.status, nil
    99  }
   100  
   101  func (api *ExternalSigner) Open(passphrase string) error {
   102  	return fmt.Errorf("operation not supported on external signers")
   103  }
   104  
   105  func (api *ExternalSigner) Close() error {
   106  	return fmt.Errorf("operation not supported on external signers")
   107  }
   108  
   109  func (api *ExternalSigner) Accounts() []accounts.Account {
   110  	var accnts []accounts.Account
   111  	res, err := api.listAccounts()
   112  	if err != nil {
   113  		log.Error("account listing failed", "error", err)
   114  		return accnts
   115  	}
   116  	for _, addr := range res {
   117  		accnts = append(accnts, accounts.Account{
   118  			URL: accounts.URL{
   119  				Scheme: "extapi",
   120  				Path:   api.endpoint,
   121  			},
   122  			Address: addr,
   123  		})
   124  	}
   125  	api.cacheMu.Lock()
   126  	api.cache = accnts
   127  	api.cacheMu.Unlock()
   128  	return accnts
   129  }
   130  
   131  func (api *ExternalSigner) Contains(account accounts.Account) bool {
   132  	api.cacheMu.RLock()
   133  	defer api.cacheMu.RUnlock()
   134  	if api.cache == nil {
   135  		// If we haven't already fetched the accounts, it's time to do so now
   136  		api.cacheMu.RUnlock()
   137  		api.Accounts()
   138  		api.cacheMu.RLock()
   139  	}
   140  	for _, a := range api.cache {
   141  		if a.Address == account.Address && (account.URL == (accounts.URL{}) || account.URL == api.URL()) {
   142  			return true
   143  		}
   144  	}
   145  	return false
   146  }
   147  
   148  func (api *ExternalSigner) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
   149  	return accounts.Account{}, fmt.Errorf("operation not supported on external signers")
   150  }
   151  
   152  func (api *ExternalSigner) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) {
   153  	log.Error("operation SelfDerive not supported on external signers")
   154  }
   155  
   156  func (api *ExternalSigner) signHash(account accounts.Account, hash []byte) ([]byte, error) {
   157  	return []byte{}, fmt.Errorf("operation not supported on external signers")
   158  }
   159  
   160  // SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
   161  func (api *ExternalSigner) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
   162  	var res hexutil.Bytes
   163  	var signAddress = common.NewMixedcaseAddress(account.Address)
   164  	if err := api.client.Call(&res, "account_signData",
   165  		mimeType,
   166  		&signAddress, // Need to use the pointer here, because of how MarshalJSON is defined
   167  		hexutil.Encode(data)); err != nil {
   168  		return nil, err
   169  	}
   170  	// If V is on 27/28-form, convert to to 0/1 for Clique
   171  	if mimeType == accounts.MimetypeClique && (res[64] == 27 || res[64] == 28) {
   172  		res[64] -= 27 // Transform V from 27/28 to 0/1 for Clique use
   173  	}
   174  	return res, nil
   175  }
   176  
   177  func (api *ExternalSigner) SignText(account accounts.Account, text []byte) ([]byte, error) {
   178  	var signature hexutil.Bytes
   179  	var signAddress = common.NewMixedcaseAddress(account.Address)
   180  	if err := api.client.Call(&signature, "account_signData",
   181  		accounts.MimetypeTextPlain,
   182  		&signAddress, // Need to use the pointer here, because of how MarshalJSON is defined
   183  		hexutil.Encode(text)); err != nil {
   184  		return nil, err
   185  	}
   186  	if signature[64] == 27 || signature[64] == 28 {
   187  		// If clef is used as a backend, it may already have transformed
   188  		// the signature to ethereum-type signature.
   189  		signature[64] -= 27 // Transform V from Ethereum-legacy to 0/1
   190  	}
   191  	return signature, nil
   192  }
   193  
   194  func (api *ExternalSigner) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   195  	res := ethapi.SignTransactionResult{}
   196  	data := hexutil.Bytes(tx.Data())
   197  	var to *common.MixedcaseAddress
   198  	if tx.To() != nil {
   199  		t := common.NewMixedcaseAddress(*tx.To())
   200  		to = &t
   201  	}
   202  	args := &core.SendTxArgs{
   203  		Data:      &data,
   204  		Nonce:     hexutil.Uint64(tx.Nonce()),
   205  		Value:     hexutil.Big(*tx.Value()),
   206  		Gas:       hexutil.Uint64(tx.Gas()),
   207  		GasPrice:  hexutil.Big(*tx.GasPrice()),
   208  		To:        to,
   209  		From:      common.NewMixedcaseAddress(account.Address),
   210  		IsPrivate: tx.IsPrivate(),
   211  	}
   212  	if err := api.client.Call(&res, "account_signTransaction", args); err != nil {
   213  		return nil, err
   214  	}
   215  	return res.Tx, nil
   216  }
   217  
   218  func (api *ExternalSigner) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
   219  	return []byte{}, fmt.Errorf("password-operations not supported on external signers")
   220  }
   221  
   222  func (api *ExternalSigner) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   223  	return nil, fmt.Errorf("password-operations not supported on external signers")
   224  }
   225  func (api *ExternalSigner) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
   226  	return nil, fmt.Errorf("password-operations not supported on external signers")
   227  }
   228  
   229  func (api *ExternalSigner) listAccounts() ([]common.Address, error) {
   230  	var res []common.Address
   231  	if err := api.client.Call(&res, "account_list"); err != nil {
   232  		return nil, err
   233  	}
   234  	return res, nil
   235  }
   236  
   237  func (api *ExternalSigner) pingVersion() (string, error) {
   238  	var v string
   239  	if err := api.client.Call(&v, "account_version"); err != nil {
   240  		return "", err
   241  	}
   242  	return v, nil
   243  }