api.go 19 KB

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