api.go 23 KB

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