api.go 22 KB

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