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