api.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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/pluggable"
  28. "github.com/ethereum/go-ethereum/accounts/scwallet"
  29. "github.com/ethereum/go-ethereum/accounts/usbwallet"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/common/hexutil"
  32. "github.com/ethereum/go-ethereum/internal/ethapi"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/plugin"
  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 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 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 *SendTxArgs) (*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, plugins *plugin.Settings, 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. // <Quorum>
  157. if plugins != nil {
  158. if _, ok := plugins.Providers[plugin.AccountPluginInterfaceName]; ok {
  159. pluginBackend := pluggable.NewBackend()
  160. backends = append(backends, pluginBackend)
  161. }
  162. }
  163. // </Quorum>
  164. // Start a smart card hub
  165. if len(scpath) > 0 {
  166. // Sanity check that the smartcard path is valid
  167. fi, err := os.Stat(scpath)
  168. if err != nil {
  169. log.Info("Smartcard socket file missing, disabling", "err", err)
  170. } else {
  171. if fi.Mode()&os.ModeType != os.ModeSocket {
  172. log.Error("Invalid smartcard socket file type", "path", scpath, "type", fi.Mode().String())
  173. } else {
  174. if schub, err := scwallet.NewHub(scpath, scwallet.Scheme, ksLocation); err != nil {
  175. log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
  176. } else {
  177. backends = append(backends, schub)
  178. }
  179. }
  180. }
  181. }
  182. // Clef doesn't allow insecure http account unlock.
  183. return accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: false}, backends...)
  184. }
  185. // MetadataFromContext extracts Metadata from a given context.Context
  186. func MetadataFromContext(ctx context.Context) Metadata {
  187. m := Metadata{"NA", "NA", "NA", "", ""} // batman
  188. if v := ctx.Value("remote"); v != nil {
  189. m.Remote = v.(string)
  190. }
  191. if v := ctx.Value("scheme"); v != nil {
  192. m.Scheme = v.(string)
  193. }
  194. if v := ctx.Value("local"); v != nil {
  195. m.Local = v.(string)
  196. }
  197. if v := ctx.Value("Origin"); v != nil {
  198. m.Origin = v.(string)
  199. }
  200. if v := ctx.Value("User-Agent"); v != nil {
  201. m.UserAgent = v.(string)
  202. }
  203. return m
  204. }
  205. // String implements Stringer interface
  206. func (m Metadata) String() string {
  207. s, err := json.Marshal(m)
  208. if err == nil {
  209. return string(s)
  210. }
  211. return err.Error()
  212. }
  213. // types for the requests/response types between signer and UI
  214. type (
  215. // SignTxRequest contains info about a Transaction to sign
  216. SignTxRequest struct {
  217. Transaction SendTxArgs `json:"transaction"`
  218. Callinfo []ValidationInfo `json:"call_info"`
  219. Meta Metadata `json:"meta"`
  220. }
  221. // SignTxResponse result from SignTxRequest
  222. SignTxResponse struct {
  223. //The UI may make changes to the TX
  224. Transaction SendTxArgs `json:"transaction"`
  225. Approved bool `json:"approved"`
  226. }
  227. SignDataRequest struct {
  228. ContentType string `json:"content_type"`
  229. Address common.MixedcaseAddress `json:"address"`
  230. Rawdata []byte `json:"raw_data"`
  231. Messages []*NameValueType `json:"messages"`
  232. Callinfo []ValidationInfo `json:"call_info"`
  233. Hash hexutil.Bytes `json:"hash"`
  234. Meta Metadata `json:"meta"`
  235. }
  236. SignDataResponse struct {
  237. Approved bool `json:"approved"`
  238. }
  239. NewAccountRequest struct {
  240. Meta Metadata `json:"meta"`
  241. }
  242. NewAccountResponse struct {
  243. Approved bool `json:"approved"`
  244. }
  245. ListRequest struct {
  246. Accounts []accounts.Account `json:"accounts"`
  247. Meta Metadata `json:"meta"`
  248. }
  249. ListResponse struct {
  250. Accounts []accounts.Account `json:"accounts"`
  251. }
  252. Message struct {
  253. Text string `json:"text"`
  254. }
  255. StartupInfo struct {
  256. Info map[string]interface{} `json:"info"`
  257. }
  258. UserInputRequest struct {
  259. Title string `json:"title"`
  260. Prompt string `json:"prompt"`
  261. IsPassword bool `json:"isPassword"`
  262. }
  263. UserInputResponse struct {
  264. Text string `json:"text"`
  265. }
  266. )
  267. var ErrRequestDenied = errors.New("request denied")
  268. // NewSignerAPI creates a new API that can be used for Account management.
  269. // ksLocation specifies the directory where to store the password protected private
  270. // key that is generated when a new Account is created.
  271. // noUSB disables USB support that is required to support hardware devices such as
  272. // ledger and trezor.
  273. func NewSignerAPI(am *accounts.Manager, chainID int64, noUSB bool, ui UIClientAPI, validator Validator, advancedMode bool, credentials storage.Storage) *SignerAPI {
  274. if advancedMode {
  275. log.Info("Clef is in advanced mode: will warn instead of reject")
  276. }
  277. signer := &SignerAPI{big.NewInt(chainID), am, ui, validator, !advancedMode, credentials}
  278. if !noUSB {
  279. signer.startUSBListener()
  280. }
  281. return signer
  282. }
  283. func (api *SignerAPI) openTrezor(url accounts.URL) {
  284. resp, err := api.UI.OnInputRequired(UserInputRequest{
  285. Prompt: "Pin required to open Trezor wallet\n" +
  286. "Look at the device for number positions\n\n" +
  287. "7 | 8 | 9\n" +
  288. "--+---+--\n" +
  289. "4 | 5 | 6\n" +
  290. "--+---+--\n" +
  291. "1 | 2 | 3\n\n",
  292. IsPassword: true,
  293. Title: "Trezor unlock",
  294. })
  295. if err != nil {
  296. log.Warn("failed getting trezor pin", "err", err)
  297. return
  298. }
  299. // We're using the URL instead of the pointer to the
  300. // Wallet -- perhaps it is not actually present anymore
  301. w, err := api.am.Wallet(url.String())
  302. if err != nil {
  303. log.Warn("wallet unavailable", "url", url)
  304. return
  305. }
  306. err = w.Open(resp.Text)
  307. if err != nil {
  308. log.Warn("failed to open wallet", "wallet", url, "err", err)
  309. return
  310. }
  311. }
  312. // startUSBListener starts a listener for USB events, for hardware wallet interaction
  313. func (api *SignerAPI) startUSBListener() {
  314. eventCh := make(chan accounts.WalletEvent, 16)
  315. am := api.am
  316. am.Subscribe(eventCh)
  317. // Open any wallets already attached
  318. for _, wallet := range am.Wallets() {
  319. if err := wallet.Open(""); err != nil {
  320. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  321. if err == usbwallet.ErrTrezorPINNeeded {
  322. go api.openTrezor(wallet.URL())
  323. }
  324. }
  325. }
  326. go api.derivationLoop(eventCh)
  327. }
  328. // derivationLoop listens for wallet events
  329. func (api *SignerAPI) derivationLoop(events chan accounts.WalletEvent) {
  330. // Listen for wallet event till termination
  331. for event := range events {
  332. switch event.Kind {
  333. case accounts.WalletArrived:
  334. if err := event.Wallet.Open(""); err != nil {
  335. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  336. if err == usbwallet.ErrTrezorPINNeeded {
  337. go api.openTrezor(event.Wallet.URL())
  338. }
  339. }
  340. case accounts.WalletOpened:
  341. status, _ := event.Wallet.Status()
  342. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  343. var derive = func(limit int, next func() accounts.DerivationPath) {
  344. // Derive first N accounts, hardcoded for now
  345. for i := 0; i < limit; i++ {
  346. path := next()
  347. if acc, err := event.Wallet.Derive(path, true); err != nil {
  348. log.Warn("Account derivation failed", "error", err)
  349. } else {
  350. log.Info("Derived account", "address", acc.Address, "path", path)
  351. }
  352. }
  353. }
  354. log.Info("Deriving default paths")
  355. derive(numberOfAccountsToDerive, accounts.DefaultIterator(accounts.DefaultBaseDerivationPath))
  356. if event.Wallet.URL().Scheme == "ledger" {
  357. log.Info("Deriving ledger legacy paths")
  358. derive(numberOfAccountsToDerive, accounts.DefaultIterator(accounts.LegacyLedgerBaseDerivationPath))
  359. log.Info("Deriving ledger live paths")
  360. // For ledger live, since it's based off the same (DefaultBaseDerivationPath)
  361. // as one we've already used, we need to step it forward one step to avoid
  362. // hitting the same path again
  363. nextFn := accounts.LedgerLiveIterator(accounts.DefaultBaseDerivationPath)
  364. nextFn()
  365. derive(numberOfAccountsToDerive, nextFn)
  366. }
  367. case accounts.WalletDropped:
  368. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  369. event.Wallet.Close()
  370. }
  371. }
  372. }
  373. // List returns the set of wallet this signer manages. Each wallet can contain
  374. // multiple accounts.
  375. func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
  376. var accs = make([]accounts.Account, 0)
  377. // accs is initialized as empty list, not nil. We use 'nil' to signal
  378. // rejection, as opposed to an empty list.
  379. for _, wallet := range api.am.Wallets() {
  380. accs = append(accs, wallet.Accounts()...)
  381. }
  382. result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
  383. if err != nil {
  384. return nil, err
  385. }
  386. if result.Accounts == nil {
  387. return nil, ErrRequestDenied
  388. }
  389. addresses := make([]common.Address, 0)
  390. for _, acc := range result.Accounts {
  391. addresses = append(addresses, acc.Address)
  392. }
  393. return addresses, nil
  394. }
  395. // New creates a new password protected Account. The private key is protected with
  396. // the given password. Users are responsible to backup the private key that is stored
  397. // in the keystore location thas was specified when this API was created.
  398. func (api *SignerAPI) New(ctx context.Context) (common.Address, error) {
  399. if be := api.am.Backends(keystore.KeyStoreType); len(be) == 0 {
  400. return common.Address{}, errors.New("password based accounts not supported")
  401. }
  402. if resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)}); err != nil {
  403. return common.Address{}, err
  404. } else if !resp.Approved {
  405. return common.Address{}, ErrRequestDenied
  406. }
  407. return api.newAccount()
  408. }
  409. // newAccount is the internal method to create a new account. It should be used
  410. // _after_ user-approval has been obtained
  411. func (api *SignerAPI) newAccount() (common.Address, error) {
  412. be := api.am.Backends(keystore.KeyStoreType)
  413. if len(be) == 0 {
  414. return common.Address{}, errors.New("password based accounts not supported")
  415. }
  416. // Three retries to get a valid password
  417. for i := 0; i < 3; i++ {
  418. resp, err := api.UI.OnInputRequired(UserInputRequest{
  419. "New account password",
  420. fmt.Sprintf("Please enter a password for the new account to be created (attempt %d of 3)", i),
  421. true})
  422. if err != nil {
  423. log.Warn("error obtaining password", "attempt", i, "error", err)
  424. continue
  425. }
  426. if pwErr := ValidatePasswordFormat(resp.Text); pwErr != nil {
  427. api.UI.ShowError(fmt.Sprintf("Account creation attempt #%d failed due to password requirements: %v", i+1, pwErr))
  428. } else {
  429. // No error
  430. acc, err := be[0].(*keystore.KeyStore).NewAccount(resp.Text)
  431. log.Info("Your new key was generated", "address", acc.Address)
  432. log.Warn("Please backup your key file!", "path", acc.URL.Path)
  433. log.Warn("Please remember your password!")
  434. return acc.Address, err
  435. }
  436. }
  437. // Otherwise fail, with generic error message
  438. return common.Address{}, errors.New("account creation failed")
  439. }
  440. // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
  441. // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
  442. // UI-modifications to requests
  443. func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
  444. modified := false
  445. if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
  446. log.Info("Sender-account changed by UI", "was", f0, "is", f1)
  447. modified = true
  448. }
  449. if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
  450. log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
  451. modified = true
  452. }
  453. if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
  454. modified = true
  455. log.Info("Gas changed by UI", "was", g0, "is", g1)
  456. }
  457. if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 {
  458. modified = true
  459. log.Info("GasPrice changed by UI", "was", g0, "is", g1)
  460. }
  461. if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
  462. modified = true
  463. log.Info("Value changed by UI", "was", v0, "is", v1)
  464. }
  465. if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
  466. d0s := ""
  467. d1s := ""
  468. if d0 != nil {
  469. d0s = hexutil.Encode(*d0)
  470. }
  471. if d1 != nil {
  472. d1s = hexutil.Encode(*d1)
  473. }
  474. if d1s != d0s {
  475. modified = true
  476. log.Info("Data changed by UI", "was", d0s, "is", d1s)
  477. }
  478. }
  479. if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
  480. modified = true
  481. log.Info("Nonce changed by UI", "was", n0, "is", n1)
  482. }
  483. return modified
  484. }
  485. func (api *SignerAPI) lookupPassword(address common.Address) (string, error) {
  486. return api.credentials.Get(address.Hex())
  487. }
  488. func (api *SignerAPI) lookupOrQueryPassword(address common.Address, title, prompt string) (string, error) {
  489. // Look up the password and return if available
  490. if pw, err := api.lookupPassword(address); err == nil {
  491. return pw, nil
  492. }
  493. // Password unavailable, request it from the user
  494. pwResp, err := api.UI.OnInputRequired(UserInputRequest{title, prompt, true})
  495. if err != nil {
  496. log.Warn("error obtaining password", "error", err)
  497. // We'll not forward the error here, in case the error contains info about the response from the UI,
  498. // which could leak the password if it was malformed json or something
  499. return "", errors.New("internal error")
  500. }
  501. return pwResp.Text, nil
  502. }
  503. // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
  504. func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
  505. var (
  506. err error
  507. result SignTxResponse
  508. msgs *ValidationMessages
  509. )
  510. if args.IsPrivate || args.isPrivacyMarker() {
  511. msgs = new(ValidationMessages)
  512. } else {
  513. msgs, err = api.validator.ValidateTransaction(methodSelector, &args)
  514. if err != nil {
  515. return nil, err
  516. }
  517. }
  518. // If we are in 'rejectMode', then reject rather than show the user warnings
  519. if api.rejectMode {
  520. if err := msgs.getWarnings(); err != nil {
  521. return nil, err
  522. }
  523. }
  524. if args.ChainID != nil {
  525. requestedChainId := (*big.Int)(args.ChainID)
  526. if api.chainID.Cmp(requestedChainId) != 0 {
  527. log.Error("Signing request with wrong chain id", "requested", requestedChainId, "configured", api.chainID)
  528. return nil, fmt.Errorf("requested chainid %d does not match the configuration of the signer",
  529. requestedChainId)
  530. }
  531. }
  532. req := SignTxRequest{
  533. Transaction: args,
  534. Meta: MetadataFromContext(ctx),
  535. Callinfo: msgs.Messages,
  536. }
  537. // Process approval
  538. result, err = api.UI.ApproveTx(&req)
  539. if err != nil {
  540. return nil, err
  541. }
  542. if !result.Approved {
  543. return nil, ErrRequestDenied
  544. }
  545. // Log changes made by the UI to the signing-request
  546. logDiff(&req, &result)
  547. var (
  548. acc accounts.Account
  549. wallet accounts.Wallet
  550. )
  551. acc = accounts.Account{Address: result.Transaction.From.Address()}
  552. wallet, err = api.am.Find(acc)
  553. if err != nil {
  554. return nil, err
  555. }
  556. // Convert fields into a real transaction
  557. var unsignedTx = result.Transaction.toTransaction()
  558. // Get the password for the transaction
  559. pw, err := api.lookupOrQueryPassword(acc.Address, "Account password",
  560. fmt.Sprintf("Please enter the password for account %s", acc.Address.String()))
  561. if err != nil {
  562. return nil, err
  563. }
  564. // The one to sign is the one that was returned from the UI
  565. signedTx, err := wallet.SignTxWithPassphrase(acc, pw, unsignedTx, api.chainID)
  566. if err != nil {
  567. api.UI.ShowError(err.Error())
  568. return nil, err
  569. }
  570. data, err := signedTx.MarshalBinary()
  571. if err != nil {
  572. return nil, err
  573. }
  574. response := ethapi.SignTransactionResult{Raw: data, Tx: signedTx}
  575. // Finally, send the signed tx to the UI
  576. api.UI.OnApprovedTx(response)
  577. // ...and to the external caller
  578. return &response, nil
  579. }
  580. func (api *SignerAPI) SignGnosisSafeTx(ctx context.Context, signerAddress common.MixedcaseAddress, gnosisTx GnosisSafeTx, methodSelector *string) (*GnosisSafeTx, error) {
  581. // Do the usual validations, but on the last-stage transaction
  582. args := gnosisTx.ArgsForValidation()
  583. msgs, err := api.validator.ValidateTransaction(methodSelector, args)
  584. if err != nil {
  585. return nil, err
  586. }
  587. // If we are in 'rejectMode', then reject rather than show the user warnings
  588. if api.rejectMode {
  589. if err := msgs.getWarnings(); err != nil {
  590. return nil, err
  591. }
  592. }
  593. typedData := gnosisTx.ToTypedData()
  594. signature, preimage, err := api.signTypedData(ctx, signerAddress, typedData, msgs)
  595. if err != nil {
  596. return nil, err
  597. }
  598. checkSummedSender, _ := common.NewMixedcaseAddressFromString(signerAddress.Address().Hex())
  599. gnosisTx.Signature = signature
  600. gnosisTx.SafeTxHash = common.BytesToHash(preimage)
  601. gnosisTx.Sender = *checkSummedSender // Must be checksumed to be accepted by relay
  602. return &gnosisTx, nil
  603. }
  604. // Returns the external api version. This method does not require user acceptance. Available methods are
  605. // available via enumeration anyway, and this info does not contain user-specific data
  606. func (api *SignerAPI) Version(ctx context.Context) (string, error) {
  607. return ExternalAPIVersion, nil
  608. }