backend.go 7.0 KB

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