api.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 core
  17. import (
  18. "context"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "math/big"
  23. "reflect"
  24. "github.com/ethereum/go-ethereum/accounts"
  25. "github.com/ethereum/go-ethereum/accounts/keystore"
  26. "github.com/ethereum/go-ethereum/accounts/usbwallet"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/hexutil"
  29. "github.com/ethereum/go-ethereum/internal/ethapi"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. )
  33. const (
  34. // numberOfAccountsToDerive For hardware wallets, the number of accounts to derive
  35. numberOfAccountsToDerive = 10
  36. // ExternalAPIVersion -- see extapi_changelog.md
  37. ExternalAPIVersion = "6.0.0"
  38. // InternalAPIVersion -- see intapi_changelog.md
  39. InternalAPIVersion = "4.0.0"
  40. )
  41. // ExternalAPI defines the external API through which signing requests are made.
  42. type ExternalAPI interface {
  43. // List available accounts
  44. List(ctx context.Context) ([]common.Address, error)
  45. // New request to create a new account
  46. New(ctx context.Context) (common.Address, error)
  47. // SignTransaction request to sign the specified transaction
  48. SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error)
  49. // SignData - request to sign the given data (plus prefix)
  50. SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data interface{}) (hexutil.Bytes, error)
  51. // SignTypedData - request to sign the given structured data (plus prefix)
  52. SignTypedData(ctx context.Context, addr common.MixedcaseAddress, data TypedData) (hexutil.Bytes, error)
  53. // EcRecover - recover public key from given message and signature
  54. EcRecover(ctx context.Context, data hexutil.Bytes, sig hexutil.Bytes) (common.Address, error)
  55. // Version info about the APIs
  56. Version(ctx context.Context) (string, error)
  57. }
  58. // UIClientAPI specifies what method a UI needs to implement to be able to be used as a
  59. // UI for the signer
  60. type UIClientAPI interface {
  61. // ApproveTx prompt the user for confirmation to request to sign Transaction
  62. ApproveTx(request *SignTxRequest) (SignTxResponse, error)
  63. // ApproveSignData prompt the user for confirmation to request to sign data
  64. ApproveSignData(request *SignDataRequest) (SignDataResponse, error)
  65. // ApproveExport prompt the user for confirmation to export encrypted Account json
  66. ApproveExport(request *ExportRequest) (ExportResponse, error)
  67. // ApproveImport prompt the user for confirmation to import Account json
  68. ApproveImport(request *ImportRequest) (ImportResponse, error)
  69. // ApproveListing prompt the user for confirmation to list accounts
  70. // the list of accounts to list can be modified by the UI
  71. ApproveListing(request *ListRequest) (ListResponse, error)
  72. // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
  73. ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error)
  74. // ShowError displays error message to user
  75. ShowError(message string)
  76. // ShowInfo displays info message to user
  77. ShowInfo(message string)
  78. // OnApprovedTx notifies the UI about a transaction having been successfully signed.
  79. // This method can be used by a UI to keep track of e.g. how much has been sent to a particular recipient.
  80. OnApprovedTx(tx ethapi.SignTransactionResult)
  81. // OnSignerStartup is invoked when the signer boots, and tells the UI info about external API location and version
  82. // information
  83. OnSignerStartup(info StartupInfo)
  84. // OnInputRequired is invoked when clef requires user input, for example master password or
  85. // pin-code for unlocking hardware wallets
  86. OnInputRequired(info UserInputRequest) (UserInputResponse, error)
  87. // RegisterUIServer tells the UI to use the given UIServerAPI for ui->clef communication
  88. RegisterUIServer(api *UIServerAPI)
  89. }
  90. // SignerAPI defines the actual implementation of ExternalAPI
  91. type SignerAPI struct {
  92. chainID *big.Int
  93. am *accounts.Manager
  94. UI UIClientAPI
  95. validator *Validator
  96. rejectMode bool
  97. }
  98. // Metadata about a request
  99. type Metadata struct {
  100. Remote string `json:"remote"`
  101. Local string `json:"local"`
  102. Scheme string `json:"scheme"`
  103. UserAgent string `json:"User-Agent"`
  104. Origin string `json:"Origin"`
  105. }
  106. func StartClefAccountManager(ksLocation string, nousb, lightKDF bool) *accounts.Manager {
  107. var (
  108. backends []accounts.Backend
  109. n, p = keystore.StandardScryptN, keystore.StandardScryptP
  110. )
  111. if lightKDF {
  112. n, p = keystore.LightScryptN, keystore.LightScryptP
  113. }
  114. // support password based accounts
  115. if len(ksLocation) > 0 {
  116. backends = append(backends, keystore.NewKeyStore(ksLocation, n, p))
  117. }
  118. if !nousb {
  119. // Start a USB hub for Ledger hardware wallets
  120. if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
  121. log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
  122. } else {
  123. backends = append(backends, ledgerhub)
  124. log.Debug("Ledger support enabled")
  125. }
  126. // Start a USB hub for Trezor hardware wallets
  127. if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
  128. log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
  129. } else {
  130. backends = append(backends, trezorhub)
  131. log.Debug("Trezor support enabled")
  132. }
  133. }
  134. return accounts.NewManager(backends...)
  135. }
  136. // MetadataFromContext extracts Metadata from a given context.Context
  137. func MetadataFromContext(ctx context.Context) Metadata {
  138. m := Metadata{"NA", "NA", "NA", "", ""} // batman
  139. if v := ctx.Value("remote"); v != nil {
  140. m.Remote = v.(string)
  141. }
  142. if v := ctx.Value("scheme"); v != nil {
  143. m.Scheme = v.(string)
  144. }
  145. if v := ctx.Value("local"); v != nil {
  146. m.Local = v.(string)
  147. }
  148. if v := ctx.Value("Origin"); v != nil {
  149. m.Origin = v.(string)
  150. }
  151. if v := ctx.Value("User-Agent"); v != nil {
  152. m.UserAgent = v.(string)
  153. }
  154. return m
  155. }
  156. // String implements Stringer interface
  157. func (m Metadata) String() string {
  158. s, err := json.Marshal(m)
  159. if err == nil {
  160. return string(s)
  161. }
  162. return err.Error()
  163. }
  164. // types for the requests/response types between signer and UI
  165. type (
  166. // SignTxRequest contains info about a Transaction to sign
  167. SignTxRequest struct {
  168. Transaction SendTxArgs `json:"transaction"`
  169. Callinfo []ValidationInfo `json:"call_info"`
  170. Meta Metadata `json:"meta"`
  171. }
  172. // SignTxResponse result from SignTxRequest
  173. SignTxResponse struct {
  174. //The UI may make changes to the TX
  175. Transaction SendTxArgs `json:"transaction"`
  176. Approved bool `json:"approved"`
  177. Password string `json:"password"`
  178. }
  179. // ExportRequest info about query to export accounts
  180. ExportRequest struct {
  181. Address common.Address `json:"address"`
  182. Meta Metadata `json:"meta"`
  183. }
  184. // ExportResponse response to export-request
  185. ExportResponse struct {
  186. Approved bool `json:"approved"`
  187. }
  188. // ImportRequest info about request to import an Account
  189. ImportRequest struct {
  190. Meta Metadata `json:"meta"`
  191. }
  192. ImportResponse struct {
  193. Approved bool `json:"approved"`
  194. OldPassword string `json:"old_password"`
  195. NewPassword string `json:"new_password"`
  196. }
  197. SignDataRequest struct {
  198. ContentType string `json:"content_type"`
  199. Address common.MixedcaseAddress `json:"address"`
  200. Rawdata []byte `json:"raw_data"`
  201. Message []*NameValueType `json:"message"`
  202. Hash hexutil.Bytes `json:"hash"`
  203. Meta Metadata `json:"meta"`
  204. }
  205. SignDataResponse struct {
  206. Approved bool `json:"approved"`
  207. Password string
  208. }
  209. NewAccountRequest struct {
  210. Meta Metadata `json:"meta"`
  211. }
  212. NewAccountResponse struct {
  213. Approved bool `json:"approved"`
  214. Password string `json:"password"`
  215. }
  216. ListRequest struct {
  217. Accounts []accounts.Account `json:"accounts"`
  218. Meta Metadata `json:"meta"`
  219. }
  220. ListResponse struct {
  221. Accounts []accounts.Account `json:"accounts"`
  222. }
  223. Message struct {
  224. Text string `json:"text"`
  225. }
  226. PasswordRequest struct {
  227. Prompt string `json:"prompt"`
  228. }
  229. PasswordResponse struct {
  230. Password string `json:"password"`
  231. }
  232. StartupInfo struct {
  233. Info map[string]interface{} `json:"info"`
  234. }
  235. UserInputRequest struct {
  236. Prompt string `json:"prompt"`
  237. Title string `json:"title"`
  238. IsPassword bool `json:"isPassword"`
  239. }
  240. UserInputResponse struct {
  241. Text string `json:"text"`
  242. }
  243. )
  244. var ErrRequestDenied = errors.New("Request denied")
  245. // NewSignerAPI creates a new API that can be used for Account management.
  246. // ksLocation specifies the directory where to store the password protected private
  247. // key that is generated when a new Account is created.
  248. // noUSB disables USB support that is required to support hardware devices such as
  249. // ledger and trezor.
  250. func NewSignerAPI(am *accounts.Manager, chainID int64, noUSB bool, ui UIClientAPI, abidb *AbiDb, advancedMode bool) *SignerAPI {
  251. if advancedMode {
  252. log.Info("Clef is in advanced mode: will warn instead of reject")
  253. }
  254. signer := &SignerAPI{big.NewInt(chainID), am, ui, NewValidator(abidb), !advancedMode}
  255. if !noUSB {
  256. signer.startUSBListener()
  257. }
  258. return signer
  259. }
  260. func (api *SignerAPI) openTrezor(url accounts.URL) {
  261. resp, err := api.UI.OnInputRequired(UserInputRequest{
  262. Prompt: "Pin required to open Trezor wallet\n" +
  263. "Look at the device for number positions\n\n" +
  264. "7 | 8 | 9\n" +
  265. "--+---+--\n" +
  266. "4 | 5 | 6\n" +
  267. "--+---+--\n" +
  268. "1 | 2 | 3\n\n",
  269. IsPassword: true,
  270. Title: "Trezor unlock",
  271. })
  272. if err != nil {
  273. log.Warn("failed getting trezor pin", "err", err)
  274. return
  275. }
  276. // We're using the URL instead of the pointer to the
  277. // Wallet -- perhaps it is not actually present anymore
  278. w, err := api.am.Wallet(url.String())
  279. if err != nil {
  280. log.Warn("wallet unavailable", "url", url)
  281. return
  282. }
  283. err = w.Open(resp.Text)
  284. if err != nil {
  285. log.Warn("failed to open wallet", "wallet", url, "err", err)
  286. return
  287. }
  288. }
  289. // startUSBListener starts a listener for USB events, for hardware wallet interaction
  290. func (api *SignerAPI) startUSBListener() {
  291. events := make(chan accounts.WalletEvent, 16)
  292. am := api.am
  293. am.Subscribe(events)
  294. go func() {
  295. // Open any wallets already attached
  296. for _, wallet := range am.Wallets() {
  297. if err := wallet.Open(""); err != nil {
  298. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  299. if err == usbwallet.ErrTrezorPINNeeded {
  300. go api.openTrezor(wallet.URL())
  301. }
  302. }
  303. }
  304. // Listen for wallet event till termination
  305. for event := range events {
  306. switch event.Kind {
  307. case accounts.WalletArrived:
  308. if err := event.Wallet.Open(""); err != nil {
  309. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  310. if err == usbwallet.ErrTrezorPINNeeded {
  311. go api.openTrezor(event.Wallet.URL())
  312. }
  313. }
  314. case accounts.WalletOpened:
  315. status, _ := event.Wallet.Status()
  316. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  317. derivationPath := accounts.DefaultBaseDerivationPath
  318. if event.Wallet.URL().Scheme == "ledger" {
  319. derivationPath = accounts.DefaultLedgerBaseDerivationPath
  320. }
  321. var nextPath = derivationPath
  322. // Derive first N accounts, hardcoded for now
  323. for i := 0; i < numberOfAccountsToDerive; i++ {
  324. acc, err := event.Wallet.Derive(nextPath, true)
  325. if err != nil {
  326. log.Warn("account derivation failed", "error", err)
  327. } else {
  328. log.Info("derived account", "address", acc.Address)
  329. }
  330. nextPath[len(nextPath)-1]++
  331. }
  332. case accounts.WalletDropped:
  333. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  334. event.Wallet.Close()
  335. }
  336. }
  337. }()
  338. }
  339. // List returns the set of wallet this signer manages. Each wallet can contain
  340. // multiple accounts.
  341. func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
  342. var accs []accounts.Account
  343. for _, wallet := range api.am.Wallets() {
  344. accs = append(accs, wallet.Accounts()...)
  345. }
  346. result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
  347. if err != nil {
  348. return nil, err
  349. }
  350. if result.Accounts == nil {
  351. return nil, ErrRequestDenied
  352. }
  353. addresses := make([]common.Address, 0)
  354. for _, acc := range result.Accounts {
  355. addresses = append(addresses, acc.Address)
  356. }
  357. return addresses, nil
  358. }
  359. // New creates a new password protected Account. The private key is protected with
  360. // the given password. Users are responsible to backup the private key that is stored
  361. // in the keystore location thas was specified when this API was created.
  362. func (api *SignerAPI) New(ctx context.Context) (common.Address, error) {
  363. be := api.am.Backends(keystore.KeyStoreType)
  364. if len(be) == 0 {
  365. return common.Address{}, errors.New("password based accounts not supported")
  366. }
  367. var (
  368. resp NewAccountResponse
  369. err error
  370. )
  371. // Three retries to get a valid password
  372. for i := 0; i < 3; i++ {
  373. resp, err = api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)})
  374. if err != nil {
  375. return common.Address{}, err
  376. }
  377. if !resp.Approved {
  378. return common.Address{}, ErrRequestDenied
  379. }
  380. if pwErr := ValidatePasswordFormat(resp.Password); pwErr != nil {
  381. api.UI.ShowError(fmt.Sprintf("Account creation attempt #%d failed due to password requirements: %v", (i + 1), pwErr))
  382. } else {
  383. // No error
  384. acc, err := be[0].(*keystore.KeyStore).NewAccount(resp.Password)
  385. return acc.Address, err
  386. }
  387. }
  388. // Otherwise fail, with generic error message
  389. return common.Address{}, errors.New("account creation failed")
  390. }
  391. // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
  392. // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
  393. // UI-modifications to requests
  394. func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
  395. modified := false
  396. if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
  397. log.Info("Sender-account changed by UI", "was", f0, "is", f1)
  398. modified = true
  399. }
  400. if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
  401. log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
  402. modified = true
  403. }
  404. if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
  405. modified = true
  406. log.Info("Gas changed by UI", "was", g0, "is", g1)
  407. }
  408. if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 {
  409. modified = true
  410. log.Info("GasPrice changed by UI", "was", g0, "is", g1)
  411. }
  412. if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
  413. modified = true
  414. log.Info("Value changed by UI", "was", v0, "is", v1)
  415. }
  416. if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
  417. d0s := ""
  418. d1s := ""
  419. if d0 != nil {
  420. d0s = hexutil.Encode(*d0)
  421. }
  422. if d1 != nil {
  423. d1s = hexutil.Encode(*d1)
  424. }
  425. if d1s != d0s {
  426. modified = true
  427. log.Info("Data changed by UI", "was", d0s, "is", d1s)
  428. }
  429. }
  430. if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
  431. modified = true
  432. log.Info("Nonce changed by UI", "was", n0, "is", n1)
  433. }
  434. return modified
  435. }
  436. // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
  437. func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
  438. var (
  439. err error
  440. result SignTxResponse
  441. )
  442. msgs, err := api.validator.ValidateTransaction(&args, methodSelector)
  443. if err != nil {
  444. return nil, err
  445. }
  446. // If we are in 'rejectMode', then reject rather than show the user warnings
  447. if api.rejectMode {
  448. if err := msgs.getWarnings(); err != nil {
  449. return nil, err
  450. }
  451. }
  452. req := SignTxRequest{
  453. Transaction: args,
  454. Meta: MetadataFromContext(ctx),
  455. Callinfo: msgs.Messages,
  456. }
  457. // Process approval
  458. result, err = api.UI.ApproveTx(&req)
  459. if err != nil {
  460. return nil, err
  461. }
  462. if !result.Approved {
  463. return nil, ErrRequestDenied
  464. }
  465. // Log changes made by the UI to the signing-request
  466. logDiff(&req, &result)
  467. var (
  468. acc accounts.Account
  469. wallet accounts.Wallet
  470. )
  471. acc = accounts.Account{Address: result.Transaction.From.Address()}
  472. wallet, err = api.am.Find(acc)
  473. if err != nil {
  474. return nil, err
  475. }
  476. // Convert fields into a real transaction
  477. var unsignedTx = result.Transaction.toTransaction()
  478. // The one to sign is the one that was returned from the UI
  479. signedTx, err := wallet.SignTxWithPassphrase(acc, result.Password, unsignedTx, api.chainID)
  480. if err != nil {
  481. api.UI.ShowError(err.Error())
  482. return nil, err
  483. }
  484. rlpdata, err := rlp.EncodeToBytes(signedTx)
  485. response := ethapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx}
  486. // Finally, send the signed tx to the UI
  487. api.UI.OnApprovedTx(response)
  488. // ...and to the external caller
  489. return &response, nil
  490. }
  491. // Returns the external api version. This method does not require user acceptance. Available methods are
  492. // available via enumeration anyway, and this info does not contain user-specific data
  493. func (api *SignerAPI) Version(ctx context.Context) (string, error) {
  494. return ExternalAPIVersion, nil
  495. }