backend.go 8.1 KB

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