api.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. events := make(chan accounts.WalletEvent, 16)
  306. am := api.am
  307. am.Subscribe(events)
  308. go func() {
  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. // Listen for wallet event till termination
  319. for event := range events {
  320. switch event.Kind {
  321. case accounts.WalletArrived:
  322. if err := event.Wallet.Open(""); err != nil {
  323. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  324. if err == usbwallet.ErrTrezorPINNeeded {
  325. go api.openTrezor(event.Wallet.URL())
  326. }
  327. }
  328. case accounts.WalletOpened:
  329. status, _ := event.Wallet.Status()
  330. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  331. var derive = func(numToDerive int, base accounts.DerivationPath) {
  332. // Derive first N accounts, hardcoded for now
  333. var nextPath = make(accounts.DerivationPath, len(base))
  334. copy(nextPath[:], base[:])
  335. for i := 0; i < numToDerive; i++ {
  336. acc, err := event.Wallet.Derive(nextPath, true)
  337. if err != nil {
  338. log.Warn("Account derivation failed", "error", err)
  339. } else {
  340. log.Info("Derived account", "address", acc.Address, "path", nextPath)
  341. }
  342. nextPath[len(nextPath)-1]++
  343. }
  344. }
  345. if event.Wallet.URL().Scheme == "ledger" {
  346. log.Info("Deriving ledger default paths")
  347. derive(numberOfAccountsToDerive/2, accounts.DefaultBaseDerivationPath)
  348. log.Info("Deriving ledger legacy paths")
  349. derive(numberOfAccountsToDerive/2, accounts.LegacyLedgerBaseDerivationPath)
  350. } else {
  351. derive(numberOfAccountsToDerive, accounts.DefaultBaseDerivationPath)
  352. }
  353. case accounts.WalletDropped:
  354. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  355. event.Wallet.Close()
  356. }
  357. }
  358. }()
  359. }
  360. // List returns the set of wallet this signer manages. Each wallet can contain
  361. // multiple accounts.
  362. func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
  363. var accs = make([]accounts.Account, 0)
  364. // accs is initialized as empty list, not nil. We use 'nil' to signal
  365. // rejection, as opposed to an empty list.
  366. for _, wallet := range api.am.Wallets() {
  367. accs = append(accs, wallet.Accounts()...)
  368. }
  369. result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
  370. if err != nil {
  371. return nil, err
  372. }
  373. if result.Accounts == nil {
  374. return nil, ErrRequestDenied
  375. }
  376. addresses := make([]common.Address, 0)
  377. for _, acc := range result.Accounts {
  378. addresses = append(addresses, acc.Address)
  379. }
  380. return addresses, nil
  381. }
  382. // New creates a new password protected Account. The private key is protected with
  383. // the given password. Users are responsible to backup the private key that is stored
  384. // in the keystore location thas was specified when this API was created.
  385. func (api *SignerAPI) New(ctx context.Context) (common.Address, error) {
  386. if be := api.am.Backends(keystore.KeyStoreType); len(be) == 0 {
  387. return common.Address{}, errors.New("password based accounts not supported")
  388. }
  389. if resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)}); err != nil {
  390. return common.Address{}, err
  391. } else if !resp.Approved {
  392. return common.Address{}, ErrRequestDenied
  393. }
  394. return api.newAccount()
  395. }
  396. // newAccount is the internal method to create a new account. It should be used
  397. // _after_ user-approval has been obtained
  398. func (api *SignerAPI) newAccount() (common.Address, error) {
  399. be := api.am.Backends(keystore.KeyStoreType)
  400. if len(be) == 0 {
  401. return common.Address{}, errors.New("password based accounts not supported")
  402. }
  403. // Three retries to get a valid password
  404. for i := 0; i < 3; i++ {
  405. resp, err := api.UI.OnInputRequired(UserInputRequest{
  406. "New account password",
  407. fmt.Sprintf("Please enter a password for the new account to be created (attempt %d of 3)", i),
  408. true})
  409. if err != nil {
  410. log.Warn("error obtaining password", "attempt", i, "error", err)
  411. continue
  412. }
  413. if pwErr := ValidatePasswordFormat(resp.Text); pwErr != nil {
  414. api.UI.ShowError(fmt.Sprintf("Account creation attempt #%d failed due to password requirements: %v", (i + 1), pwErr))
  415. } else {
  416. // No error
  417. acc, err := be[0].(*keystore.KeyStore).NewAccount(resp.Text)
  418. log.Info("Your new key was generated", "address", acc.Address)
  419. log.Warn("Please backup your key file!", "path", acc.URL.Path)
  420. log.Warn("Please remember your password!")
  421. return acc.Address, err
  422. }
  423. }
  424. // Otherwise fail, with generic error message
  425. return common.Address{}, errors.New("account creation failed")
  426. }
  427. // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
  428. // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
  429. // UI-modifications to requests
  430. func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
  431. modified := false
  432. if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
  433. log.Info("Sender-account changed by UI", "was", f0, "is", f1)
  434. modified = true
  435. }
  436. if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
  437. log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
  438. modified = true
  439. }
  440. if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
  441. modified = true
  442. log.Info("Gas changed by UI", "was", g0, "is", g1)
  443. }
  444. if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 {
  445. modified = true
  446. log.Info("GasPrice changed by UI", "was", g0, "is", g1)
  447. }
  448. if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
  449. modified = true
  450. log.Info("Value changed by UI", "was", v0, "is", v1)
  451. }
  452. if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
  453. d0s := ""
  454. d1s := ""
  455. if d0 != nil {
  456. d0s = hexutil.Encode(*d0)
  457. }
  458. if d1 != nil {
  459. d1s = hexutil.Encode(*d1)
  460. }
  461. if d1s != d0s {
  462. modified = true
  463. log.Info("Data changed by UI", "was", d0s, "is", d1s)
  464. }
  465. }
  466. if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
  467. modified = true
  468. log.Info("Nonce changed by UI", "was", n0, "is", n1)
  469. }
  470. return modified
  471. }
  472. func (api *SignerAPI) lookupPassword(address common.Address) (string, error) {
  473. return api.credentials.Get(address.Hex())
  474. }
  475. func (api *SignerAPI) lookupOrQueryPassword(address common.Address, title, prompt string) (string, error) {
  476. // Look up the password and return if available
  477. if pw, err := api.lookupPassword(address); err == nil {
  478. return pw, nil
  479. }
  480. // Password unavailable, request it from the user
  481. pwResp, err := api.UI.OnInputRequired(UserInputRequest{title, prompt, true})
  482. if err != nil {
  483. log.Warn("error obtaining password", "error", err)
  484. // We'll not forward the error here, in case the error contains info about the response from the UI,
  485. // which could leak the password if it was malformed json or something
  486. return "", errors.New("internal error")
  487. }
  488. return pwResp.Text, nil
  489. }
  490. // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
  491. func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
  492. var (
  493. err error
  494. result SignTxResponse
  495. )
  496. msgs, err := api.validator.ValidateTransaction(methodSelector, &args)
  497. if err != nil {
  498. return nil, err
  499. }
  500. // If we are in 'rejectMode', then reject rather than show the user warnings
  501. if api.rejectMode {
  502. if err := msgs.getWarnings(); err != nil {
  503. return nil, err
  504. }
  505. }
  506. req := SignTxRequest{
  507. Transaction: args,
  508. Meta: MetadataFromContext(ctx),
  509. Callinfo: msgs.Messages,
  510. }
  511. // Process approval
  512. result, err = api.UI.ApproveTx(&req)
  513. if err != nil {
  514. return nil, err
  515. }
  516. if !result.Approved {
  517. return nil, ErrRequestDenied
  518. }
  519. // Log changes made by the UI to the signing-request
  520. logDiff(&req, &result)
  521. var (
  522. acc accounts.Account
  523. wallet accounts.Wallet
  524. )
  525. acc = accounts.Account{Address: result.Transaction.From.Address()}
  526. wallet, err = api.am.Find(acc)
  527. if err != nil {
  528. return nil, err
  529. }
  530. // Convert fields into a real transaction
  531. var unsignedTx = result.Transaction.toTransaction()
  532. // Get the password for the transaction
  533. pw, err := api.lookupOrQueryPassword(acc.Address, "Account password",
  534. fmt.Sprintf("Please enter the password for account %s", acc.Address.String()))
  535. if err != nil {
  536. return nil, err
  537. }
  538. // The one to sign is the one that was returned from the UI
  539. signedTx, err := wallet.SignTxWithPassphrase(acc, pw, unsignedTx, api.chainID)
  540. if err != nil {
  541. api.UI.ShowError(err.Error())
  542. return nil, err
  543. }
  544. rlpdata, err := rlp.EncodeToBytes(signedTx)
  545. if err != nil {
  546. return nil, err
  547. }
  548. response := ethapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx}
  549. // Finally, send the signed tx to the UI
  550. api.UI.OnApprovedTx(response)
  551. // ...and to the external caller
  552. return &response, nil
  553. }
  554. func (api *SignerAPI) SignGnosisSafeTx(ctx context.Context, signerAddress common.MixedcaseAddress, gnosisTx GnosisSafeTx, methodSelector *string) (*GnosisSafeTx, error) {
  555. // Do the usual validations, but on the last-stage transaction
  556. args := gnosisTx.ArgsForValidation()
  557. msgs, err := api.validator.ValidateTransaction(methodSelector, args)
  558. if err != nil {
  559. return nil, err
  560. }
  561. // If we are in 'rejectMode', then reject rather than show the user warnings
  562. if api.rejectMode {
  563. if err := msgs.getWarnings(); err != nil {
  564. return nil, err
  565. }
  566. }
  567. typedData := gnosisTx.ToTypedData()
  568. signature, preimage, err := api.signTypedData(ctx, signerAddress, typedData, msgs)
  569. if err != nil {
  570. return nil, err
  571. }
  572. checkSummedSender, _ := common.NewMixedcaseAddressFromString(signerAddress.Address().Hex())
  573. gnosisTx.Signature = signature
  574. gnosisTx.SafeTxHash = common.BytesToHash(preimage)
  575. gnosisTx.Sender = *checkSummedSender // Must be checksumed to be accepted by relay
  576. return &gnosisTx, nil
  577. }
  578. // Returns the external api version. This method does not require user acceptance. Available methods are
  579. // available via enumeration anyway, and this info does not contain user-specific data
  580. func (api *SignerAPI) Version(ctx context.Context) (string, error) {
  581. return ExternalAPIVersion, nil
  582. }