api.go 24.2 KB
Newer Older
1
// Copyright 2018 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
3
//
4 5
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
6 7 8
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
10 11
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
// GNU Lesser General Public License for more details.
13
//
14 15
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16 17 18 19

package core

import (
20
	"bytes"
21 22 23 24 25
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"math/big"
26
	"os"
27 28 29 30
	"reflect"

	"github.com/ethereum/go-ethereum/accounts"
	"github.com/ethereum/go-ethereum/accounts/keystore"
31
	"github.com/ethereum/go-ethereum/accounts/scwallet"
32 33 34
	"github.com/ethereum/go-ethereum/accounts/usbwallet"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
35
	"github.com/ethereum/go-ethereum/common/math"
36 37
	"github.com/ethereum/go-ethereum/internal/ethapi"
	"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 44 45 46
const (
	// numberOfAccountsToDerive For hardware wallets, the number of accounts to derive
	numberOfAccountsToDerive = 10
	// ExternalAPIVersion -- see extapi_changelog.md
47
	ExternalAPIVersion = "6.1.0"
48
	// InternalAPIVersion -- see intapi_changelog.md
49
	InternalAPIVersion = "7.0.1"
50
)
51

52 53 54
// ExternalAPI defines the external API through which signing requests are made.
type ExternalAPI interface {
	// 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 61 62
	// SignData - request to sign the given data (plus prefix)
	SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data interface{}) (hexutil.Bytes, error)
	// 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 65
	// EcRecover - recover public key from given message and signature
	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 69
	// SignGnosisSafeTransaction signs/confirms a gnosis-safe multisig transaction
	SignGnosisSafeTx(ctx context.Context, signerAddress common.MixedcaseAddress, gnosisTx GnosisSafeTx, methodSelector *string) (*GnosisSafeTx, error)
70 71
}

72 73 74
// UIClientAPI specifies what method a UI needs to implement to be able to be used as a
// UI for the signer
type UIClientAPI interface {
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
	// ApproveTx prompt the user for confirmation to request to sign Transaction
	ApproveTx(request *SignTxRequest) (SignTxResponse, error)
	// ApproveSignData prompt the user for confirmation to request to sign data
	ApproveSignData(request *SignDataRequest) (SignDataResponse, error)
	// ApproveListing prompt the user for confirmation to list accounts
	// the list of accounts to list can be modified by the UI
	ApproveListing(request *ListRequest) (ListResponse, error)
	// ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
	ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error)
	// ShowError displays error message to user
	ShowError(message string)
	// ShowInfo displays info message to user
	ShowInfo(message string)
	// OnApprovedTx notifies the UI about a transaction having been successfully signed.
	// This method can be used by a UI to keep track of e.g. how much has been sent to a particular recipient.
	OnApprovedTx(tx ethapi.SignTransactionResult)
	// OnSignerStartup is invoked when the signer boots, and tells the UI info about external API location and version
	// information
	OnSignerStartup(info StartupInfo)
94
	// OnInputRequired is invoked when clef requires user input, for example master password or
95 96
	// pin-code for unlocking hardware wallets
	OnInputRequired(info UserInputRequest) (UserInputResponse, error)
97 98
	// RegisterUIServer tells the UI to use the given UIServerAPI for ui->clef communication
	RegisterUIServer(api *UIServerAPI)
99 100
}

101 102 103 104 105 106 107 108 109 110
// Validator defines the methods required to validate a transaction against some
// sanity defaults as well as any underlying 4byte method database.
//
// Use fourbyte.Database as an implementation. It is separated out of this package
// to allow pieces of the signer package to be used without having to load the
// 7MB embedded 4byte dump.
type Validator interface {
	// ValidateTransaction does a number of checks on the supplied transaction, and
	// returns either a list of warnings, or an error (indicating that the transaction
	// should be immediately rejected).
111
	ValidateTransaction(selector *string, tx *apitypes.SendTxArgs) (*apitypes.ValidationMessages, error)
112 113
}

114 115
// SignerAPI defines the actual implementation of ExternalAPI
type SignerAPI struct {
116 117 118
	chainID     *big.Int
	am          *accounts.Manager
	UI          UIClientAPI
119
	validator   Validator
120 121
	rejectMode  bool
	credentials storage.Storage
122 123 124 125
}

// Metadata about a request
type Metadata struct {
126 127 128 129 130
	Remote    string `json:"remote"`
	Local     string `json:"local"`
	Scheme    string `json:"scheme"`
	UserAgent string `json:"User-Agent"`
	Origin    string `json:"Origin"`
131 132
}

133
func StartClefAccountManager(ksLocation string, nousb, lightKDF bool, scpath string) *accounts.Manager {
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
	var (
		backends []accounts.Backend
		n, p     = keystore.StandardScryptN, keystore.StandardScryptP
	)
	if lightKDF {
		n, p = keystore.LightScryptN, keystore.LightScryptP
	}
	// support password based accounts
	if len(ksLocation) > 0 {
		backends = append(backends, keystore.NewKeyStore(ksLocation, n, p))
	}
	if !nousb {
		// Start a USB hub for Ledger hardware wallets
		if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
			log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err))
		} else {
			backends = append(backends, ledgerhub)
			log.Debug("Ledger support enabled")
		}
153 154 155
		// Start a USB hub for Trezor hardware wallets (HID version)
		if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
			log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err))
156 157
		} else {
			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 162
		if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil {
			log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err))
163 164
		} else {
			backends = append(backends, trezorhub)
165
			log.Debug("Trezor support enabled via WebUSB")
166 167
		}
	}
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187

	// Start a smart card hub
	if len(scpath) > 0 {
		// Sanity check that the smartcard path is valid
		fi, err := os.Stat(scpath)
		if err != nil {
			log.Info("Smartcard socket file missing, disabling", "err", err)
		} else {
			if fi.Mode()&os.ModeType != os.ModeSocket {
				log.Error("Invalid smartcard socket file type", "path", scpath, "type", fi.Mode().String())
			} else {
				if schub, err := scwallet.NewHub(scpath, scwallet.Scheme, ksLocation); err != nil {
					log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err))
				} else {
					backends = append(backends, schub)
				}
			}
		}
	}

188 189
	// Clef doesn't allow insecure http account unlock.
	return accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: false}, backends...)
190 191
}

192 193
// MetadataFromContext extracts Metadata from a given context.Context
func MetadataFromContext(ctx context.Context) Metadata {
194 195
	info := rpc.PeerInfoFromContext(ctx)

196
	m := Metadata{"NA", "NA", "NA", "", ""} // batman
197

198 199 200 201 202
	if info.Transport != "" {
		if info.Transport == "http" {
			m.Scheme = info.HTTP.Version
		}
		m.Scheme = info.Transport
203
	}
204 205
	if info.RemoteAddr != "" {
		m.Remote = info.RemoteAddr
206
	}
207 208
	if info.HTTP.Host != "" {
		m.Local = info.HTTP.Host
209
	}
210 211
	m.Origin = info.HTTP.Origin
	m.UserAgent = info.HTTP.UserAgent
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
	return m
}

// String implements Stringer interface
func (m Metadata) String() string {
	s, err := json.Marshal(m)
	if err == nil {
		return string(s)
	}
	return err.Error()
}

// types for the requests/response types between signer and UI
type (
	// SignTxRequest contains info about a Transaction to sign
	SignTxRequest struct {
228 229 230
		Transaction apitypes.SendTxArgs       `json:"transaction"`
		Callinfo    []apitypes.ValidationInfo `json:"call_info"`
		Meta        Metadata                  `json:"meta"`
231 232 233 234
	}
	// SignTxResponse result from SignTxRequest
	SignTxResponse struct {
		//The UI may make changes to the TX
235 236
		Transaction apitypes.SendTxArgs `json:"transaction"`
		Approved    bool                `json:"approved"`
237 238
	}
	SignDataRequest struct {
239 240 241
		ContentType string                    `json:"content_type"`
		Address     common.MixedcaseAddress   `json:"address"`
		Rawdata     []byte                    `json:"raw_data"`
242
		Messages    []*apitypes.NameValueType `json:"messages"`
243 244 245
		Callinfo    []apitypes.ValidationInfo `json:"call_info"`
		Hash        hexutil.Bytes             `json:"hash"`
		Meta        Metadata                  `json:"meta"`
246 247 248 249 250 251 252 253
	}
	SignDataResponse struct {
		Approved bool `json:"approved"`
	}
	NewAccountRequest struct {
		Meta Metadata `json:"meta"`
	}
	NewAccountResponse struct {
254
		Approved bool `json:"approved"`
255 256
	}
	ListRequest struct {
257 258
		Accounts []accounts.Account `json:"accounts"`
		Meta     Metadata           `json:"meta"`
259 260
	}
	ListResponse struct {
261
		Accounts []accounts.Account `json:"accounts"`
262 263 264 265 266 267 268
	}
	Message struct {
		Text string `json:"text"`
	}
	StartupInfo struct {
		Info map[string]interface{} `json:"info"`
	}
269 270
	UserInputRequest struct {
		Title      string `json:"title"`
271
		Prompt     string `json:"prompt"`
272 273 274 275 276
		IsPassword bool   `json:"isPassword"`
	}
	UserInputResponse struct {
		Text string `json:"text"`
	}
277 278
)

279
var ErrRequestDenied = errors.New("request denied")
280 281 282 283 284 285

// NewSignerAPI creates a new API that can be used for Account management.
// ksLocation specifies the directory where to store the password protected private
// key that is generated when a new Account is created.
// noUSB disables USB support that is required to support hardware devices such as
// ledger and trezor.
286
func NewSignerAPI(am *accounts.Manager, chainID int64, noUSB bool, ui UIClientAPI, validator Validator, advancedMode bool, credentials storage.Storage) *SignerAPI {
287 288 289
	if advancedMode {
		log.Info("Clef is in advanced mode: will warn instead of reject")
	}
290
	signer := &SignerAPI{big.NewInt(chainID), am, ui, validator, !advancedMode, credentials}
291 292
	if !noUSB {
		signer.startUSBListener()
293
	}
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	return signer
}
func (api *SignerAPI) openTrezor(url accounts.URL) {
	resp, err := api.UI.OnInputRequired(UserInputRequest{
		Prompt: "Pin required to open Trezor wallet\n" +
			"Look at the device for number positions\n\n" +
			"7 | 8 | 9\n" +
			"--+---+--\n" +
			"4 | 5 | 6\n" +
			"--+---+--\n" +
			"1 | 2 | 3\n\n",
		IsPassword: true,
		Title:      "Trezor unlock",
	})
	if err != nil {
		log.Warn("failed getting trezor pin", "err", err)
		return
	}
	// We're using the URL instead of the pointer to the
	// Wallet -- perhaps it is not actually present anymore
	w, err := api.am.Wallet(url.String())
	if err != nil {
		log.Warn("wallet unavailable", "url", url)
		return
	}
	err = w.Open(resp.Text)
	if err != nil {
		log.Warn("failed to open wallet", "wallet", url, "err", err)
		return
	}
}

// startUSBListener starts a listener for USB events, for hardware wallet interaction
func (api *SignerAPI) startUSBListener() {
328
	eventCh := make(chan accounts.WalletEvent, 16)
329
	am := api.am
330 331 332 333 334 335 336 337 338 339 340 341
	am.Subscribe(eventCh)
	// Open any wallets already attached
	for _, wallet := range am.Wallets() {
		if err := wallet.Open(""); err != nil {
			log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
			if err == usbwallet.ErrTrezorPINNeeded {
				go api.openTrezor(wallet.URL())
			}
		}
	}
	go api.derivationLoop(eventCh)
}
342

343 344 345 346 347 348 349 350
// derivationLoop listens for wallet events
func (api *SignerAPI) derivationLoop(events chan accounts.WalletEvent) {
	// Listen for wallet event till termination
	for event := range events {
		switch event.Kind {
		case accounts.WalletArrived:
			if err := event.Wallet.Open(""); err != nil {
				log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
351
				if err == usbwallet.ErrTrezorPINNeeded {
352
					go api.openTrezor(event.Wallet.URL())
353 354
				}
			}
355 356 357 358 359 360 361 362 363 364 365
		case accounts.WalletOpened:
			status, _ := event.Wallet.Status()
			log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
			var derive = func(limit int, next func() accounts.DerivationPath) {
				// Derive first N accounts, hardcoded for now
				for i := 0; i < limit; i++ {
					path := next()
					if acc, err := event.Wallet.Derive(path, true); err != nil {
						log.Warn("Account derivation failed", "error", err)
					} else {
						log.Info("Derived account", "address", acc.Address, "path", path)
366
					}
367
				}
368
			}
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
			log.Info("Deriving default paths")
			derive(numberOfAccountsToDerive, accounts.DefaultIterator(accounts.DefaultBaseDerivationPath))
			if event.Wallet.URL().Scheme == "ledger" {
				log.Info("Deriving ledger legacy paths")
				derive(numberOfAccountsToDerive, accounts.DefaultIterator(accounts.LegacyLedgerBaseDerivationPath))
				log.Info("Deriving ledger live paths")
				// For ledger live, since it's based off the same (DefaultBaseDerivationPath)
				// as one we've already used, we need to step it forward one step to avoid
				// hitting the same path again
				nextFn := accounts.LedgerLiveIterator(accounts.DefaultBaseDerivationPath)
				nextFn()
				derive(numberOfAccountsToDerive, nextFn)
			}
		case accounts.WalletDropped:
			log.Info("Old wallet dropped", "url", event.Wallet.URL())
			event.Wallet.Close()
385
		}
386
	}
387 388 389 390
}

// List returns the set of wallet this signer manages. Each wallet can contain
// multiple accounts.
391
func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) {
392 393 394
	var accs = make([]accounts.Account, 0)
	// accs is initialized as empty list, not nil. We use 'nil' to signal
	// rejection, as opposed to an empty list.
395
	for _, wallet := range api.am.Wallets() {
396
		accs = append(accs, wallet.Accounts()...)
397 398 399 400 401 402 403 404
	}
	result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)})
	if err != nil {
		return nil, err
	}
	if result.Accounts == nil {
		return nil, ErrRequestDenied
	}
405 406 407 408 409
	addresses := make([]common.Address, 0)
	for _, acc := range result.Accounts {
		addresses = append(addresses, acc.Address)
	}
	return addresses, nil
410 411 412 413
}

// New creates a new password protected Account. The private key is protected with
// the given password. Users are responsible to backup the private key that is stored
414
// in the keystore location that was specified when this API was created.
415
func (api *SignerAPI) New(ctx context.Context) (common.Address, error) {
416
	if be := api.am.Backends(keystore.KeyStoreType); len(be) == 0 {
417
		return common.Address{}, errors.New("password based accounts not supported")
418
	}
419 420 421 422 423
	if resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)}); err != nil {
		return common.Address{}, err
	} else if !resp.Approved {
		return common.Address{}, ErrRequestDenied
	}
424 425
	return api.newAccount()
}
426

427 428 429 430 431 432 433
// newAccount is the internal method to create a new account. It should be used
// _after_ user-approval has been obtained
func (api *SignerAPI) newAccount() (common.Address, error) {
	be := api.am.Backends(keystore.KeyStoreType)
	if len(be) == 0 {
		return common.Address{}, errors.New("password based accounts not supported")
	}
434 435
	// Three retries to get a valid password
	for i := 0; i < 3; i++ {
436 437 438 439
		resp, err := api.UI.OnInputRequired(UserInputRequest{
			"New account password",
			fmt.Sprintf("Please enter a password for the new account to be created (attempt %d of 3)", i),
			true})
440
		if err != nil {
441 442
			log.Warn("error obtaining password", "attempt", i, "error", err)
			continue
443
		}
444
		if pwErr := ValidatePasswordFormat(resp.Text); pwErr != nil {
445
			api.UI.ShowError(fmt.Sprintf("Account creation attempt #%d failed due to password requirements: %v", i+1, pwErr))
446 447
		} else {
			// No error
448
			acc, err := be[0].(*keystore.KeyStore).NewAccount(resp.Text)
449 450 451
			log.Info("Your new key was generated", "address", acc.Address)
			log.Warn("Please backup your key file!", "path", acc.URL.Path)
			log.Warn("Please remember your password!")
452
			return acc.Address, err
453
		}
454
	}
455
	// Otherwise fail, with generic error message
456
	return common.Address{}, errors.New("account creation failed")
457 458 459 460 461 462
}

// logDiff logs the difference between the incoming (original) transaction and the one returned from the signer.
// it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow
// UI-modifications to requests
func logDiff(original *SignTxRequest, new *SignTxResponse) bool {
463 464 465 466 467 468 469 470 471 472
	var intPtrModified = func(a, b *hexutil.Big) bool {
		aBig := (*big.Int)(a)
		bBig := (*big.Int)(b)
		if aBig != nil && bBig != nil {
			return aBig.Cmp(bBig) != 0
		}
		// One or both of them are nil
		return a != b
	}

473 474 475 476 477 478 479 480 481 482 483 484 485
	modified := false
	if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) {
		log.Info("Sender-account changed by UI", "was", f0, "is", f1)
		modified = true
	}
	if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) {
		log.Info("Recipient-account changed by UI", "was", t0, "is", t1)
		modified = true
	}
	if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 {
		modified = true
		log.Info("Gas changed by UI", "was", g0, "is", g1)
	}
486 487 488 489 490 491 492 493 494 495
	if a, b := original.Transaction.GasPrice, new.Transaction.GasPrice; intPtrModified(a, b) {
		log.Info("GasPrice changed by UI", "was", a, "is", b)
		modified = true
	}
	if a, b := original.Transaction.MaxPriorityFeePerGas, new.Transaction.MaxPriorityFeePerGas; intPtrModified(a, b) {
		log.Info("maxPriorityFeePerGas changed by UI", "was", a, "is", b)
		modified = true
	}
	if a, b := original.Transaction.MaxFeePerGas, new.Transaction.MaxFeePerGas; intPtrModified(a, b) {
		log.Info("maxFeePerGas changed by UI", "was", a, "is", b)
496 497 498 499 500 501 502 503 504 505
		modified = true
	}
	if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 {
		modified = true
		log.Info("Value changed by UI", "was", v0, "is", v1)
	}
	if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 {
		d0s := ""
		d1s := ""
		if d0 != nil {
506
			d0s = hexutil.Encode(*d0)
507 508
		}
		if d1 != nil {
509
			d1s = hexutil.Encode(*d1)
510 511 512 513 514 515 516 517 518 519 520 521 522
		}
		if d1s != d0s {
			modified = true
			log.Info("Data changed by UI", "was", d0s, "is", d1s)
		}
	}
	if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 {
		modified = true
		log.Info("Nonce changed by UI", "was", n0, "is", n1)
	}
	return modified
}

523 524
func (api *SignerAPI) lookupPassword(address common.Address) (string, error) {
	return api.credentials.Get(address.Hex())
525
}
526

527
func (api *SignerAPI) lookupOrQueryPassword(address common.Address, title, prompt string) (string, error) {
528 529
	// Look up the password and return if available
	if pw, err := api.lookupPassword(address); err == nil {
530 531
		return pw, nil
	}
532 533 534 535 536 537 538 539 540
	// Password unavailable, request it from the user
	pwResp, err := api.UI.OnInputRequired(UserInputRequest{title, prompt, true})
	if err != nil {
		log.Warn("error obtaining password", "error", err)
		// We'll not forward the error here, in case the error contains info about the response from the UI,
		// which could leak the password if it was malformed json or something
		return "", errors.New("internal error")
	}
	return pwResp.Text, nil
541 542
}

543
// SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form
544
func (api *SignerAPI) SignTransaction(ctx context.Context, args apitypes.SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) {
545 546 547 548
	var (
		err    error
		result SignTxResponse
	)
549
	msgs, err := api.validator.ValidateTransaction(methodSelector, &args)
550 551 552
	if err != nil {
		return nil, err
	}
553 554
	// If we are in 'rejectMode', then reject rather than show the user warnings
	if api.rejectMode {
555
		if err := msgs.GetWarnings(); err != nil {
556
			log.Info("Signing aborted due to warnings. In order to continue despite warnings, please use the flag '--advanced'.")
557 558 559
			return nil, err
		}
	}
560 561 562 563 564 565 566 567
	if args.ChainID != nil {
		requestedChainId := (*big.Int)(args.ChainID)
		if api.chainID.Cmp(requestedChainId) != 0 {
			log.Error("Signing request with wrong chain id", "requested", requestedChainId, "configured", api.chainID)
			return nil, fmt.Errorf("requested chainid %d does not match the configuration of the signer",
				requestedChainId)
		}
	}
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
	req := SignTxRequest{
		Transaction: args,
		Meta:        MetadataFromContext(ctx),
		Callinfo:    msgs.Messages,
	}
	// Process approval
	result, err = api.UI.ApproveTx(&req)
	if err != nil {
		return nil, err
	}
	if !result.Approved {
		return nil, ErrRequestDenied
	}
	// Log changes made by the UI to the signing-request
	logDiff(&req, &result)
	var (
		acc    accounts.Account
		wallet accounts.Wallet
	)
	acc = accounts.Account{Address: result.Transaction.From.Address()}
	wallet, err = api.am.Find(acc)
	if err != nil {
		return nil, err
	}
	// Convert fields into a real transaction
593
	var unsignedTx = result.Transaction.ToTransaction()
594 595 596 597 598 599
	// Get the password for the transaction
	pw, err := api.lookupOrQueryPassword(acc.Address, "Account password",
		fmt.Sprintf("Please enter the password for account %s", acc.Address.String()))
	if err != nil {
		return nil, err
	}
600
	// The one to sign is the one that was returned from the UI
601
	signedTx, err := wallet.SignTxWithPassphrase(acc, pw, unsignedTx, api.chainID)
602 603 604 605 606
	if err != nil {
		api.UI.ShowError(err.Error())
		return nil, err
	}

607
	data, err := signedTx.MarshalBinary()
608 609 610
	if err != nil {
		return nil, err
	}
611
	response := ethapi.SignTransactionResult{Raw: data, Tx: signedTx}
612 613 614 615 616 617 618

	// Finally, send the signed tx to the UI
	api.UI.OnApprovedTx(response)
	// ...and to the external caller
	return &response, nil
}

619 620 621 622 623 624 625 626 627
func (api *SignerAPI) SignGnosisSafeTx(ctx context.Context, signerAddress common.MixedcaseAddress, gnosisTx GnosisSafeTx, methodSelector *string) (*GnosisSafeTx, error) {
	// Do the usual validations, but on the last-stage transaction
	args := gnosisTx.ArgsForValidation()
	msgs, err := api.validator.ValidateTransaction(methodSelector, args)
	if err != nil {
		return nil, err
	}
	// If we are in 'rejectMode', then reject rather than show the user warnings
	if api.rejectMode {
628
		if err := msgs.GetWarnings(); err != nil {
629
			log.Info("Signing aborted due to warnings. In order to continue despite warnings, please use the flag '--advanced'.")
630 631 632 633
			return nil, err
		}
	}
	typedData := gnosisTx.ToTypedData()
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
	// might aswell error early.
	// we are expected to sign. If our calculated hash does not match what they want,
	// The gnosis safetx input contains a 'safeTxHash' which is the expected safeTxHash that
	sighash, _, err := apitypes.TypedDataAndHash(typedData)
	if err != nil {
		return nil, err
	}
	if !bytes.Equal(sighash, gnosisTx.InputExpHash.Bytes()) {
		// It might be the case that the json is missing chain id.
		if gnosisTx.ChainId == nil {
			gnosisTx.ChainId = (*math.HexOrDecimal256)(api.chainID)
			typedData = gnosisTx.ToTypedData()
			sighash, _, _ = apitypes.TypedDataAndHash(typedData)
			if !bytes.Equal(sighash, gnosisTx.InputExpHash.Bytes()) {
				return nil, fmt.Errorf("mismatched safeTxHash; have %#x want %#x", sighash, gnosisTx.InputExpHash[:])
			}
		}
	}
652
	signature, preimage, err := api.signTypedData(ctx, signerAddress, typedData, msgs)
653

654 655 656 657 658 659 660
	if err != nil {
		return nil, err
	}
	checkSummedSender, _ := common.NewMixedcaseAddressFromString(signerAddress.Address().Hex())

	gnosisTx.Signature = signature
	gnosisTx.SafeTxHash = common.BytesToHash(preimage)
661
	gnosisTx.Sender = *checkSummedSender // Must be checksummed to be accepted by relay
662 663 664 665

	return &gnosisTx, nil
}

666 667 668 669 670
// Returns the external api version. This method does not require user acceptance. Available methods are
// available via enumeration anyway, and this info does not contain user-specific data
func (api *SignerAPI) Version(ctx context.Context) (string, error) {
	return ExternalAPIVersion, nil
}