backend.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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/apitypes"
  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. // SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
  138. func (api *ExternalSigner) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
  139. var res hexutil.Bytes
  140. var signAddress = common.NewMixedcaseAddress(account.Address)
  141. if err := api.client.Call(&res, "account_signData",
  142. mimeType,
  143. &signAddress, // Need to use the pointer here, because of how MarshalJSON is defined
  144. hexutil.Encode(data)); err != nil {
  145. return nil, err
  146. }
  147. // If V is on 27/28-form, convert to 0/1 for Clique
  148. if mimeType == accounts.MimetypeClique && (res[64] == 27 || res[64] == 28) {
  149. res[64] -= 27 // Transform V from 27/28 to 0/1 for Clique use
  150. }
  151. return res, nil
  152. }
  153. func (api *ExternalSigner) SignText(account accounts.Account, text []byte) ([]byte, error) {
  154. var signature hexutil.Bytes
  155. var signAddress = common.NewMixedcaseAddress(account.Address)
  156. if err := api.client.Call(&signature, "account_signData",
  157. accounts.MimetypeTextPlain,
  158. &signAddress, // Need to use the pointer here, because of how MarshalJSON is defined
  159. hexutil.Encode(text)); err != nil {
  160. return nil, err
  161. }
  162. if signature[64] == 27 || signature[64] == 28 {
  163. // If clef is used as a backend, it may already have transformed
  164. // the signature to ethereum-type signature.
  165. signature[64] -= 27 // Transform V from Ethereum-legacy to 0/1
  166. }
  167. return signature, nil
  168. }
  169. // signTransactionResult represents the signinig result returned by clef.
  170. type signTransactionResult struct {
  171. Raw hexutil.Bytes `json:"raw"`
  172. Tx *types.Transaction `json:"tx"`
  173. }
  174. // SignTx sends the transaction to the external signer.
  175. // If chainID is nil, or tx.ChainID is zero, the chain ID will be assigned
  176. // by the external signer. For non-legacy transactions, the chain ID of the
  177. // transaction overrides the chainID parameter.
  178. func (api *ExternalSigner) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  179. data := hexutil.Bytes(tx.Data())
  180. var to *common.MixedcaseAddress
  181. if tx.To() != nil {
  182. t := common.NewMixedcaseAddress(*tx.To())
  183. to = &t
  184. }
  185. args := &apitypes.SendTxArgs{
  186. Data: &data,
  187. Nonce: hexutil.Uint64(tx.Nonce()),
  188. Value: hexutil.Big(*tx.Value()),
  189. Gas: hexutil.Uint64(tx.Gas()),
  190. To: to,
  191. From: common.NewMixedcaseAddress(account.Address),
  192. }
  193. switch tx.Type() {
  194. case types.LegacyTxType, types.AccessListTxType:
  195. args.GasPrice = (*hexutil.Big)(tx.GasPrice())
  196. case types.DynamicFeeTxType:
  197. args.MaxFeePerGas = (*hexutil.Big)(tx.GasFeeCap())
  198. args.MaxPriorityFeePerGas = (*hexutil.Big)(tx.GasTipCap())
  199. default:
  200. return nil, fmt.Errorf("unsupported tx type %d", tx.Type())
  201. }
  202. // We should request the default chain id that we're operating with
  203. // (the chain we're executing on)
  204. if chainID != nil && chainID.Sign() != 0 {
  205. args.ChainID = (*hexutil.Big)(chainID)
  206. }
  207. if tx.Type() != types.LegacyTxType {
  208. // However, if the user asked for a particular chain id, then we should
  209. // use that instead.
  210. if tx.ChainId().Sign() != 0 {
  211. args.ChainID = (*hexutil.Big)(tx.ChainId())
  212. }
  213. accessList := tx.AccessList()
  214. args.AccessList = &accessList
  215. }
  216. var res signTransactionResult
  217. if err := api.client.Call(&res, "account_signTransaction", args); err != nil {
  218. return nil, err
  219. }
  220. return res.Tx, nil
  221. }
  222. func (api *ExternalSigner) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
  223. return []byte{}, fmt.Errorf("password-operations not supported on external signers")
  224. }
  225. func (api *ExternalSigner) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  226. return nil, fmt.Errorf("password-operations not supported on external signers")
  227. }
  228. func (api *ExternalSigner) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
  229. return nil, fmt.Errorf("password-operations not supported on external signers")
  230. }
  231. func (api *ExternalSigner) listAccounts() ([]common.Address, error) {
  232. var res []common.Address
  233. if err := api.client.Call(&res, "account_list"); err != nil {
  234. return nil, err
  235. }
  236. return res, nil
  237. }
  238. func (api *ExternalSigner) pingVersion() (string, error) {
  239. var v string
  240. if err := api.client.Call(&v, "account_version"); err != nil {
  241. return "", err
  242. }
  243. return v, nil
  244. }