uiapi.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. // Copyright 2019 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. //
  17. package core
  18. import (
  19. "context"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "io/ioutil"
  24. "math/big"
  25. "github.com/ethereum/go-ethereum/accounts"
  26. "github.com/ethereum/go-ethereum/accounts/keystore"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/math"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. )
  31. // SignerUIAPI implements methods Clef provides for a UI to query, in the bidirectional communication
  32. // channel.
  33. // This API is considered secure, since a request can only
  34. // ever arrive from the UI -- and the UI is capable of approving any action, thus we can consider these
  35. // requests pre-approved.
  36. // NB: It's very important that these methods are not ever exposed on the external service
  37. // registry.
  38. type UIServerAPI struct {
  39. extApi *SignerAPI
  40. am *accounts.Manager
  41. }
  42. // NewUIServerAPI creates a new UIServerAPI
  43. func NewUIServerAPI(extapi *SignerAPI) *UIServerAPI {
  44. return &UIServerAPI{extapi, extapi.am}
  45. }
  46. // List available accounts. As opposed to the external API definition, this method delivers
  47. // the full Account object and not only Address.
  48. // Example call
  49. // {"jsonrpc":"2.0","method":"clef_listAccounts","params":[], "id":4}
  50. func (s *UIServerAPI) ListAccounts(ctx context.Context) ([]accounts.Account, error) {
  51. var accs []accounts.Account
  52. for _, wallet := range s.am.Wallets() {
  53. accs = append(accs, wallet.Accounts()...)
  54. }
  55. return accs, nil
  56. }
  57. // rawWallet is a JSON representation of an accounts.Wallet interface, with its
  58. // data contents extracted into plain fields.
  59. type rawWallet struct {
  60. URL string `json:"url"`
  61. Status string `json:"status"`
  62. Failure string `json:"failure,omitempty"`
  63. Accounts []accounts.Account `json:"accounts,omitempty"`
  64. }
  65. // ListWallets will return a list of wallets that clef manages
  66. // Example call
  67. // {"jsonrpc":"2.0","method":"clef_listWallets","params":[], "id":5}
  68. func (s *UIServerAPI) ListWallets() []rawWallet {
  69. wallets := make([]rawWallet, 0) // return [] instead of nil if empty
  70. for _, wallet := range s.am.Wallets() {
  71. status, failure := wallet.Status()
  72. raw := rawWallet{
  73. URL: wallet.URL().String(),
  74. Status: status,
  75. Accounts: wallet.Accounts(),
  76. }
  77. if failure != nil {
  78. raw.Failure = failure.Error()
  79. }
  80. wallets = append(wallets, raw)
  81. }
  82. return wallets
  83. }
  84. // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
  85. // it for later reuse.
  86. // Example call
  87. // {"jsonrpc":"2.0","method":"clef_deriveAccount","params":["ledger://","m/44'/60'/0'", false], "id":6}
  88. func (s *UIServerAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
  89. wallet, err := s.am.Wallet(url)
  90. if err != nil {
  91. return accounts.Account{}, err
  92. }
  93. derivPath, err := accounts.ParseDerivationPath(path)
  94. if err != nil {
  95. return accounts.Account{}, err
  96. }
  97. if pin == nil {
  98. pin = new(bool)
  99. }
  100. return wallet.Derive(derivPath, *pin)
  101. }
  102. // fetchKeystore retrives the encrypted keystore from the account manager.
  103. func fetchKeystore(am *accounts.Manager) *keystore.KeyStore {
  104. return am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  105. }
  106. // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
  107. // encrypting it with the passphrase.
  108. // Example call (should fail on password too short)
  109. // {"jsonrpc":"2.0","method":"clef_importRawKey","params":["1111111111111111111111111111111111111111111111111111111111111111","test"], "id":6}
  110. func (s *UIServerAPI) ImportRawKey(privkey string, password string) (accounts.Account, error) {
  111. key, err := crypto.HexToECDSA(privkey)
  112. if err != nil {
  113. return accounts.Account{}, err
  114. }
  115. if err := ValidatePasswordFormat(password); err != nil {
  116. return accounts.Account{}, fmt.Errorf("password requirements not met: %v", err)
  117. }
  118. // No error
  119. return fetchKeystore(s.am).ImportECDSA(key, password)
  120. }
  121. // OpenWallet initiates a hardware wallet opening procedure, establishing a USB
  122. // connection and attempting to authenticate via the provided passphrase. Note,
  123. // the method may return an extra challenge requiring a second open (e.g. the
  124. // Trezor PIN matrix challenge).
  125. // Example
  126. // {"jsonrpc":"2.0","method":"clef_openWallet","params":["ledger://",""], "id":6}
  127. func (s *UIServerAPI) OpenWallet(url string, passphrase *string) error {
  128. wallet, err := s.am.Wallet(url)
  129. if err != nil {
  130. return err
  131. }
  132. pass := ""
  133. if passphrase != nil {
  134. pass = *passphrase
  135. }
  136. return wallet.Open(pass)
  137. }
  138. // ChainId returns the chainid in use for Eip-155 replay protection
  139. // Example call
  140. // {"jsonrpc":"2.0","method":"clef_chainId","params":[], "id":8}
  141. func (s *UIServerAPI) ChainId() math.HexOrDecimal64 {
  142. return (math.HexOrDecimal64)(s.extApi.chainID.Uint64())
  143. }
  144. // SetChainId sets the chain id to use when signing transactions.
  145. // Example call to set Ropsten:
  146. // {"jsonrpc":"2.0","method":"clef_setChainId","params":["3"], "id":8}
  147. func (s *UIServerAPI) SetChainId(id math.HexOrDecimal64) math.HexOrDecimal64 {
  148. s.extApi.chainID = new(big.Int).SetUint64(uint64(id))
  149. return s.ChainId()
  150. }
  151. // Export returns encrypted private key associated with the given address in web3 keystore format.
  152. // Example
  153. // {"jsonrpc":"2.0","method":"clef_export","params":["0x19e7e376e7c213b7e7e7e46cc70a5dd086daff2a"], "id":4}
  154. func (s *UIServerAPI) Export(ctx context.Context, addr common.Address) (json.RawMessage, error) {
  155. // Look up the wallet containing the requested signer
  156. wallet, err := s.am.Find(accounts.Account{Address: addr})
  157. if err != nil {
  158. return nil, err
  159. }
  160. if wallet.URL().Scheme != keystore.KeyStoreScheme {
  161. return nil, fmt.Errorf("Account is not a keystore-account")
  162. }
  163. return ioutil.ReadFile(wallet.URL().Path)
  164. }
  165. // Import tries to import the given keyJSON in the local keystore. The keyJSON data is expected to be
  166. // in web3 keystore format. It will decrypt the keyJSON with the given passphrase and on successful
  167. // decryption it will encrypt the key with the given newPassphrase and store it in the keystore.
  168. // Example (the address in question has privkey `11...11`):
  169. // {"jsonrpc":"2.0","method":"clef_import","params":[{"address":"19e7e376e7c213b7e7e7e46cc70a5dd086daff2a","crypto":{"cipher":"aes-128-ctr","ciphertext":"33e4cd3756091d037862bb7295e9552424a391a6e003272180a455ca2a9fb332","cipherparams":{"iv":"b54b263e8f89c42bb219b6279fba5cce"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"e4ca94644fd30569c1b1afbbc851729953c92637b7fe4bb9840bbb31ffbc64a5"},"mac":"f4092a445c2b21c0ef34f17c9cd0d873702b2869ec5df4439a0c2505823217e7"},"id":"216c7eac-e8c1-49af-a215-fa0036f29141","version":3},"test","yaddayadda"], "id":4}
  170. func (api *UIServerAPI) Import(ctx context.Context, keyJSON json.RawMessage, oldPassphrase, newPassphrase string) (accounts.Account, error) {
  171. be := api.am.Backends(keystore.KeyStoreType)
  172. if len(be) == 0 {
  173. return accounts.Account{}, errors.New("password based accounts not supported")
  174. }
  175. if err := ValidatePasswordFormat(newPassphrase); err != nil {
  176. return accounts.Account{}, fmt.Errorf("password requirements not met: %v", err)
  177. }
  178. return be[0].(*keystore.KeyStore).Import(keyJSON, oldPassphrase, newPassphrase)
  179. }
  180. // Other methods to be added, not yet implemented are:
  181. // - Ruleset interaction: add rules, attest rulefiles
  182. // - Store metadata about accounts, e.g. naming of accounts