backend.go 6.6 KB

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