github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/signer/core/api.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package core 19 20 import ( 21 "context" 22 "encoding/json" 23 "errors" 24 "fmt" 25 "math/big" 26 "os" 27 "reflect" 28 29 "github.com/AigarNetwork/aigar/accounts" 30 "github.com/AigarNetwork/aigar/accounts/keystore" 31 "github.com/AigarNetwork/aigar/accounts/scwallet" 32 "github.com/AigarNetwork/aigar/accounts/usbwallet" 33 "github.com/AigarNetwork/aigar/common" 34 "github.com/AigarNetwork/aigar/common/hexutil" 35 "github.com/AigarNetwork/aigar/internal/ethapi" 36 "github.com/AigarNetwork/aigar/log" 37 "github.com/AigarNetwork/aigar/rlp" 38 "github.com/AigarNetwork/aigar/signer/storage" 39 ) 40 41 const ( 42 // numberOfAccountsToDerive For hardware wallets, the number of accounts to derive 43 numberOfAccountsToDerive = 10 44 // ExternalAPIVersion -- see extapi_changelog.md 45 ExternalAPIVersion = "6.0.0" 46 // InternalAPIVersion -- see intapi_changelog.md 47 InternalAPIVersion = "7.0.0" 48 ) 49 50 // ExternalAPI defines the external API through which signing requests are made. 51 type ExternalAPI interface { 52 // List available accounts 53 List(ctx context.Context) ([]common.Address, error) 54 // New request to create a new account 55 New(ctx context.Context) (common.Address, error) 56 // SignTransaction request to sign the specified transaction 57 SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) 58 // SignData - request to sign the given data (plus prefix) 59 SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data interface{}) (hexutil.Bytes, error) 60 // SignTypedData - request to sign the given structured data (plus prefix) 61 SignTypedData(ctx context.Context, addr common.MixedcaseAddress, data TypedData) (hexutil.Bytes, error) 62 // EcRecover - recover public key from given message and signature 63 EcRecover(ctx context.Context, data hexutil.Bytes, sig hexutil.Bytes) (common.Address, error) 64 // Version info about the APIs 65 Version(ctx context.Context) (string, error) 66 } 67 68 // UIClientAPI specifies what method a UI needs to implement to be able to be used as a 69 // UI for the signer 70 type UIClientAPI interface { 71 // ApproveTx prompt the user for confirmation to request to sign Transaction 72 ApproveTx(request *SignTxRequest) (SignTxResponse, error) 73 // ApproveSignData prompt the user for confirmation to request to sign data 74 ApproveSignData(request *SignDataRequest) (SignDataResponse, error) 75 // ApproveListing prompt the user for confirmation to list accounts 76 // the list of accounts to list can be modified by the UI 77 ApproveListing(request *ListRequest) (ListResponse, error) 78 // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller 79 ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) 80 // ShowError displays error message to user 81 ShowError(message string) 82 // ShowInfo displays info message to user 83 ShowInfo(message string) 84 // OnApprovedTx notifies the UI about a transaction having been successfully signed. 85 // This method can be used by a UI to keep track of e.g. how much has been sent to a particular recipient. 86 OnApprovedTx(tx ethapi.SignTransactionResult) 87 // OnSignerStartup is invoked when the signer boots, and tells the UI info about external API location and version 88 // information 89 OnSignerStartup(info StartupInfo) 90 // OnInputRequired is invoked when clef requires user input, for example master password or 91 // pin-code for unlocking hardware wallets 92 OnInputRequired(info UserInputRequest) (UserInputResponse, error) 93 // RegisterUIServer tells the UI to use the given UIServerAPI for ui->clef communication 94 RegisterUIServer(api *UIServerAPI) 95 } 96 97 // Validator defines the methods required to validate a transaction against some 98 // sanity defaults as well as any underlying 4byte method database. 99 // 100 // Use fourbyte.Database as an implementation. It is separated out of this package 101 // to allow pieces of the signer package to be used without having to load the 102 // 7MB embedded 4byte dump. 103 type Validator interface { 104 // ValidateTransaction does a number of checks on the supplied transaction, and 105 // returns either a list of warnings, or an error (indicating that the transaction 106 // should be immediately rejected). 107 ValidateTransaction(selector *string, tx *SendTxArgs) (*ValidationMessages, error) 108 } 109 110 // SignerAPI defines the actual implementation of ExternalAPI 111 type SignerAPI struct { 112 chainID *big.Int 113 am *accounts.Manager 114 UI UIClientAPI 115 validator Validator 116 rejectMode bool 117 credentials storage.Storage 118 } 119 120 // Metadata about a request 121 type Metadata struct { 122 Remote string `json:"remote"` 123 Local string `json:"local"` 124 Scheme string `json:"scheme"` 125 UserAgent string `json:"User-Agent"` 126 Origin string `json:"Origin"` 127 } 128 129 func StartClefAccountManager(ksLocation string, nousb, lightKDF bool, scpath string) *accounts.Manager { 130 var ( 131 backends []accounts.Backend 132 n, p = keystore.StandardScryptN, keystore.StandardScryptP 133 ) 134 if lightKDF { 135 n, p = keystore.LightScryptN, keystore.LightScryptP 136 } 137 // support password based accounts 138 if len(ksLocation) > 0 { 139 backends = append(backends, keystore.NewKeyStore(ksLocation, n, p)) 140 } 141 if !nousb { 142 // Start a USB hub for Ledger hardware wallets 143 if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil { 144 log.Warn(fmt.Sprintf("Failed to start Ledger hub, disabling: %v", err)) 145 } else { 146 backends = append(backends, ledgerhub) 147 log.Debug("Ledger support enabled") 148 } 149 // Start a USB hub for Trezor hardware wallets (HID version) 150 if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil { 151 log.Warn(fmt.Sprintf("Failed to start HID Trezor hub, disabling: %v", err)) 152 } else { 153 backends = append(backends, trezorhub) 154 log.Debug("Trezor support enabled via HID") 155 } 156 // Start a USB hub for Trezor hardware wallets (WebUSB version) 157 if trezorhub, err := usbwallet.NewTrezorHubWithWebUSB(); err != nil { 158 log.Warn(fmt.Sprintf("Failed to start WebUSB Trezor hub, disabling: %v", err)) 159 } else { 160 backends = append(backends, trezorhub) 161 log.Debug("Trezor support enabled via WebUSB") 162 } 163 } 164 165 // Start a smart card hub 166 if len(scpath) > 0 { 167 // Sanity check that the smartcard path is valid 168 fi, err := os.Stat(scpath) 169 if err != nil { 170 log.Info("Smartcard socket file missing, disabling", "err", err) 171 } else { 172 if fi.Mode()&os.ModeType != os.ModeSocket { 173 log.Error("Invalid smartcard socket file type", "path", scpath, "type", fi.Mode().String()) 174 } else { 175 if schub, err := scwallet.NewHub(scpath, scwallet.Scheme, ksLocation); err != nil { 176 log.Warn(fmt.Sprintf("Failed to start smart card hub, disabling: %v", err)) 177 } else { 178 backends = append(backends, schub) 179 } 180 } 181 } 182 } 183 184 // Clef doesn't allow insecure http account unlock. 185 return accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: false}, backends...) 186 } 187 188 // MetadataFromContext extracts Metadata from a given context.Context 189 func MetadataFromContext(ctx context.Context) Metadata { 190 m := Metadata{"NA", "NA", "NA", "", ""} // batman 191 192 if v := ctx.Value("remote"); v != nil { 193 m.Remote = v.(string) 194 } 195 if v := ctx.Value("scheme"); v != nil { 196 m.Scheme = v.(string) 197 } 198 if v := ctx.Value("local"); v != nil { 199 m.Local = v.(string) 200 } 201 if v := ctx.Value("Origin"); v != nil { 202 m.Origin = v.(string) 203 } 204 if v := ctx.Value("User-Agent"); v != nil { 205 m.UserAgent = v.(string) 206 } 207 return m 208 } 209 210 // String implements Stringer interface 211 func (m Metadata) String() string { 212 s, err := json.Marshal(m) 213 if err == nil { 214 return string(s) 215 } 216 return err.Error() 217 } 218 219 // types for the requests/response types between signer and UI 220 type ( 221 // SignTxRequest contains info about a Transaction to sign 222 SignTxRequest struct { 223 Transaction SendTxArgs `json:"transaction"` 224 Callinfo []ValidationInfo `json:"call_info"` 225 Meta Metadata `json:"meta"` 226 } 227 // SignTxResponse result from SignTxRequest 228 SignTxResponse struct { 229 //The UI may make changes to the TX 230 Transaction SendTxArgs `json:"transaction"` 231 Approved bool `json:"approved"` 232 } 233 SignDataRequest struct { 234 ContentType string `json:"content_type"` 235 Address common.MixedcaseAddress `json:"address"` 236 Rawdata []byte `json:"raw_data"` 237 Messages []*NameValueType `json:"messages"` 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) 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 351 // Derive first N accounts, hardcoded for now 352 var nextPath = make(accounts.DerivationPath, len(accounts.DefaultBaseDerivationPath)) 353 copy(nextPath[:], accounts.DefaultBaseDerivationPath[:]) 354 355 for i := 0; i < numberOfAccountsToDerive; 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) 361 } 362 nextPath[len(nextPath)-1]++ 363 } 364 case accounts.WalletDropped: 365 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 366 event.Wallet.Close() 367 } 368 } 369 }() 370 } 371 372 // List returns the set of wallet this signer manages. Each wallet can contain 373 // multiple accounts. 374 func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) { 375 var accs []accounts.Account 376 for _, wallet := range api.am.Wallets() { 377 accs = append(accs, wallet.Accounts()...) 378 } 379 result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)}) 380 if err != nil { 381 return nil, err 382 } 383 if result.Accounts == nil { 384 return nil, ErrRequestDenied 385 386 } 387 addresses := make([]common.Address, 0) 388 for _, acc := range result.Accounts { 389 addresses = append(addresses, acc.Address) 390 } 391 392 return addresses, nil 393 } 394 395 // New creates a new password protected Account. The private key is protected with 396 // the given password. Users are responsible to backup the private key that is stored 397 // in the keystore location thas was specified when this API was created. 398 func (api *SignerAPI) New(ctx context.Context) (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 if resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)}); err != nil { 404 return common.Address{}, err 405 } else if !resp.Approved { 406 return common.Address{}, ErrRequestDenied 407 } 408 409 // Three retries to get a valid password 410 for i := 0; i < 3; i++ { 411 resp, err := api.UI.OnInputRequired(UserInputRequest{ 412 "New account password", 413 fmt.Sprintf("Please enter a password for the new account to be created (attempt %d of 3)", i), 414 true}) 415 if err != nil { 416 log.Warn("error obtaining password", "attempt", i, "error", err) 417 continue 418 } 419 if pwErr := ValidatePasswordFormat(resp.Text); pwErr != nil { 420 api.UI.ShowError(fmt.Sprintf("Account creation attempt #%d failed due to password requirements: %v", (i + 1), pwErr)) 421 } else { 422 // No error 423 acc, err := be[0].(*keystore.KeyStore).NewAccount(resp.Text) 424 log.Info("Your new key was generated", "address", acc.Address) 425 log.Warn("Please backup your key file!", "path", acc.URL.Path) 426 log.Warn("Please remember your password!") 427 return acc.Address, err 428 } 429 } 430 // Otherwise fail, with generic error message 431 return common.Address{}, errors.New("account creation failed") 432 } 433 434 // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer. 435 // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow 436 // UI-modifications to requests 437 func logDiff(original *SignTxRequest, new *SignTxResponse) bool { 438 modified := false 439 if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) { 440 log.Info("Sender-account changed by UI", "was", f0, "is", f1) 441 modified = true 442 } 443 if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) { 444 log.Info("Recipient-account changed by UI", "was", t0, "is", t1) 445 modified = true 446 } 447 if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 { 448 modified = true 449 log.Info("Gas changed by UI", "was", g0, "is", g1) 450 } 451 if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 { 452 modified = true 453 log.Info("GasPrice changed by UI", "was", g0, "is", g1) 454 } 455 if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 { 456 modified = true 457 log.Info("Value changed by UI", "was", v0, "is", v1) 458 } 459 if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 { 460 d0s := "" 461 d1s := "" 462 if d0 != nil { 463 d0s = hexutil.Encode(*d0) 464 } 465 if d1 != nil { 466 d1s = hexutil.Encode(*d1) 467 } 468 if d1s != d0s { 469 modified = true 470 log.Info("Data changed by UI", "was", d0s, "is", d1s) 471 } 472 } 473 if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 { 474 modified = true 475 log.Info("Nonce changed by UI", "was", n0, "is", n1) 476 } 477 return modified 478 } 479 480 func (api *SignerAPI) lookupPassword(address common.Address) (string, error) { 481 return api.credentials.Get(address.Hex()) 482 } 483 484 func (api *SignerAPI) lookupOrQueryPassword(address common.Address, title, prompt string) (string, error) { 485 // Look up the password and return if available 486 if pw, err := api.lookupPassword(address); err == nil { 487 return pw, nil 488 } 489 // Password unavailable, request it from the user 490 pwResp, err := api.UI.OnInputRequired(UserInputRequest{title, prompt, true}) 491 if err != nil { 492 log.Warn("error obtaining password", "error", err) 493 // We'll not forward the error here, in case the error contains info about the response from the UI, 494 // which could leak the password if it was malformed json or something 495 return "", errors.New("internal error") 496 } 497 return pwResp.Text, nil 498 } 499 500 // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form 501 func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) { 502 var ( 503 err error 504 result SignTxResponse 505 ) 506 msgs, err := api.validator.ValidateTransaction(methodSelector, &args) 507 if err != nil { 508 return nil, err 509 } 510 // If we are in 'rejectMode', then reject rather than show the user warnings 511 if api.rejectMode { 512 if err := msgs.getWarnings(); err != nil { 513 return nil, err 514 } 515 } 516 req := SignTxRequest{ 517 Transaction: args, 518 Meta: MetadataFromContext(ctx), 519 Callinfo: msgs.Messages, 520 } 521 // Process approval 522 result, err = api.UI.ApproveTx(&req) 523 if err != nil { 524 return nil, err 525 } 526 if !result.Approved { 527 return nil, ErrRequestDenied 528 } 529 // Log changes made by the UI to the signing-request 530 logDiff(&req, &result) 531 var ( 532 acc accounts.Account 533 wallet accounts.Wallet 534 ) 535 acc = accounts.Account{Address: result.Transaction.From.Address()} 536 wallet, err = api.am.Find(acc) 537 if err != nil { 538 return nil, err 539 } 540 // Convert fields into a real transaction 541 var unsignedTx = result.Transaction.toTransaction() 542 // Get the password for the transaction 543 pw, err := api.lookupOrQueryPassword(acc.Address, "Account password", 544 fmt.Sprintf("Please enter the password for account %s", acc.Address.String())) 545 if err != nil { 546 return nil, err 547 } 548 // The one to sign is the one that was returned from the UI 549 signedTx, err := wallet.SignTxWithPassphrase(acc, pw, unsignedTx, api.chainID) 550 if err != nil { 551 api.UI.ShowError(err.Error()) 552 return nil, err 553 } 554 555 rlpdata, err := rlp.EncodeToBytes(signedTx) 556 response := ethapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx} 557 558 // Finally, send the signed tx to the UI 559 api.UI.OnApprovedTx(response) 560 // ...and to the external caller 561 return &response, nil 562 563 } 564 565 // Returns the external api version. This method does not require user acceptance. Available methods are 566 // available via enumeration anyway, and this info does not contain user-specific data 567 func (api *SignerAPI) Version(ctx context.Context) (string, error) { 568 return ExternalAPIVersion, nil 569 }