api.go 22 KB

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