github.com/kaleido-io/go-ethereum@v1.9.7/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  	for _, a := range api.cache {
   135  		if a.Address == account.Address && (account.URL == (accounts.URL{}) || account.URL == api.URL()) {
   136  			return true
   137  		}
   138  	}
   139  	return false
   140  }
   141  
   142  func (api *ExternalSigner) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
   143  	return accounts.Account{}, fmt.Errorf("operation not supported on external signers")
   144  }
   145  
   146  func (api *ExternalSigner) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) {
   147  	log.Error("operation SelfDerive not supported on external signers")
   148  }
   149  
   150  func (api *ExternalSigner) signHash(account accounts.Account, hash []byte) ([]byte, error) {
   151  	return []byte{}, fmt.Errorf("operation not supported on external signers")
   152  }
   153  
   154  // SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
   155  func (api *ExternalSigner) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
   156  	var res hexutil.Bytes
   157  	var signAddress = common.NewMixedcaseAddress(account.Address)
   158  	if err := api.client.Call(&res, "account_signData",
   159  		mimeType,
   160  		&signAddress, // Need to use the pointer here, because of how MarshalJSON is defined
   161  		hexutil.Encode(data)); err != nil {
   162  		return nil, err
   163  	}
   164  	// If V is on 27/28-form, convert to to 0/1 for Clique
   165  	if mimeType == accounts.MimetypeClique && (res[64] == 27 || res[64] == 28) {
   166  		res[64] -= 27 // Transform V from 27/28 to 0/1 for Clique use
   167  	}
   168  	return res, nil
   169  }
   170  
   171  func (api *ExternalSigner) SignText(account accounts.Account, text []byte) ([]byte, error) {
   172  	var res hexutil.Bytes
   173  	var signAddress = common.NewMixedcaseAddress(account.Address)
   174  	if err := api.client.Call(&res, "account_signData",
   175  		accounts.MimetypeTextPlain,
   176  		&signAddress, // Need to use the pointer here, because of how MarshalJSON is defined
   177  		hexutil.Encode(text)); err != nil {
   178  		return nil, err
   179  	}
   180  	return res, nil
   181  }
   182  
   183  func (api *ExternalSigner) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   184  	res := ethapi.SignTransactionResult{}
   185  	data := hexutil.Bytes(tx.Data())
   186  	var to *common.MixedcaseAddress
   187  	if tx.To() != nil {
   188  		t := common.NewMixedcaseAddress(*tx.To())
   189  		to = &t
   190  	}
   191  	args := &core.SendTxArgs{
   192  		Data:     &data,
   193  		Nonce:    hexutil.Uint64(tx.Nonce()),
   194  		Value:    hexutil.Big(*tx.Value()),
   195  		Gas:      hexutil.Uint64(tx.Gas()),
   196  		GasPrice: hexutil.Big(*tx.GasPrice()),
   197  		To:       to,
   198  		From:     common.NewMixedcaseAddress(account.Address),
   199  	}
   200  	if err := api.client.Call(&res, "account_signTransaction", args); err != nil {
   201  		return nil, err
   202  	}
   203  	return res.Tx, nil
   204  }
   205  
   206  func (api *ExternalSigner) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
   207  	return []byte{}, fmt.Errorf("password-operations not supported on external signers")
   208  }
   209  
   210  func (api *ExternalSigner) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   211  	return nil, fmt.Errorf("password-operations not supported on external signers")
   212  }
   213  func (api *ExternalSigner) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
   214  	return nil, fmt.Errorf("password-operations not supported on external signers")
   215  }
   216  
   217  func (api *ExternalSigner) listAccounts() ([]common.Address, error) {
   218  	var res []common.Address
   219  	if err := api.client.Call(&res, "account_list"); err != nil {
   220  		return nil, err
   221  	}
   222  	return res, nil
   223  }
   224  
   225  func (api *ExternalSigner) pingVersion() (string, error) {
   226  	var v string
   227  	if err := api.client.Call(&v, "account_version"); err != nil {
   228  		return "", err
   229  	}
   230  	return v, nil
   231  }