github.com/core-coin/go-core/v2@v2.1.9/accounts/external/backend.go (about)

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