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