github.com/ConsenSys/Quorum@v20.10.0+incompatible/accounts/usbwallet/wallet.go (about) 1 // Copyright 2017 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 usbwallet implements support for USB hardware wallets. 18 package usbwallet 19 20 import ( 21 "context" 22 "errors" 23 "fmt" 24 "io" 25 "math/big" 26 "sync" 27 "time" 28 29 ethereum "github.com/ethereum/go-ethereum" 30 "github.com/ethereum/go-ethereum/accounts" 31 "github.com/ethereum/go-ethereum/common" 32 "github.com/ethereum/go-ethereum/core/types" 33 "github.com/ethereum/go-ethereum/crypto" 34 "github.com/ethereum/go-ethereum/log" 35 "github.com/karalabe/usb" 36 ) 37 38 // Maximum time between wallet health checks to detect USB unplugs. 39 const heartbeatCycle = time.Second 40 41 // Minimum time to wait between self derivation attempts, even it the user is 42 // requesting accounts like crazy. 43 const selfDeriveThrottling = time.Second 44 45 // driver defines the vendor specific functionality hardware wallets instances 46 // must implement to allow using them with the wallet lifecycle management. 47 type driver interface { 48 // Status returns a textual status to aid the user in the current state of the 49 // wallet. It also returns an error indicating any failure the wallet might have 50 // encountered. 51 Status() (string, error) 52 53 // Open initializes access to a wallet instance. The passphrase parameter may 54 // or may not be used by the implementation of a particular wallet instance. 55 Open(device io.ReadWriter, passphrase string) error 56 57 // Close releases any resources held by an open wallet instance. 58 Close() error 59 60 // Heartbeat performs a sanity check against the hardware wallet to see if it 61 // is still online and healthy. 62 Heartbeat() error 63 64 // Derive sends a derivation request to the USB device and returns the Ethereum 65 // address located on that path. 66 Derive(path accounts.DerivationPath) (common.Address, error) 67 68 // SignTx sends the transaction to the USB device and waits for the user to confirm 69 // or deny the transaction. 70 SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) 71 } 72 73 // wallet represents the common functionality shared by all USB hardware 74 // wallets to prevent reimplementing the same complex maintenance mechanisms 75 // for different vendors. 76 type wallet struct { 77 hub *Hub // USB hub scanning 78 driver driver // Hardware implementation of the low level device operations 79 url *accounts.URL // Textual URL uniquely identifying this wallet 80 81 info usb.DeviceInfo // Known USB device infos about the wallet 82 device usb.Device // USB device advertising itself as a hardware wallet 83 84 accounts []accounts.Account // List of derive accounts pinned on the hardware wallet 85 paths map[common.Address]accounts.DerivationPath // Known derivation paths for signing operations 86 87 deriveNextPaths []accounts.DerivationPath // Next derivation paths for account auto-discovery (multiple bases supported) 88 deriveNextAddrs []common.Address // Next derived account addresses for auto-discovery (multiple bases supported) 89 deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with 90 deriveReq chan chan struct{} // Channel to request a self-derivation on 91 deriveQuit chan chan error // Channel to terminate the self-deriver with 92 93 healthQuit chan chan error 94 95 // Locking a hardware wallet is a bit special. Since hardware devices are lower 96 // performing, any communication with them might take a non negligible amount of 97 // time. Worse still, waiting for user confirmation can take arbitrarily long, 98 // but exclusive communication must be upheld during. Locking the entire wallet 99 // in the mean time however would stall any parts of the system that don't want 100 // to communicate, just read some state (e.g. list the accounts). 101 // 102 // As such, a hardware wallet needs two locks to function correctly. A state 103 // lock can be used to protect the wallet's software-side internal state, which 104 // must not be held exclusively during hardware communication. A communication 105 // lock can be used to achieve exclusive access to the device itself, this one 106 // however should allow "skipping" waiting for operations that might want to 107 // use the device, but can live without too (e.g. account self-derivation). 108 // 109 // Since we have two locks, it's important to know how to properly use them: 110 // - Communication requires the `device` to not change, so obtaining the 111 // commsLock should be done after having a stateLock. 112 // - Communication must not disable read access to the wallet state, so it 113 // must only ever hold a *read* lock to stateLock. 114 commsLock chan struct{} // Mutex (buf=1) for the USB comms without keeping the state locked 115 stateLock sync.RWMutex // Protects read and write access to the wallet struct fields 116 117 log log.Logger // Contextual logger to tag the base with its id 118 } 119 120 // URL implements accounts.Wallet, returning the URL of the USB hardware device. 121 func (w *wallet) URL() accounts.URL { 122 return *w.url // Immutable, no need for a lock 123 } 124 125 // Status implements accounts.Wallet, returning a custom status message from the 126 // underlying vendor-specific hardware wallet implementation. 127 func (w *wallet) Status() (string, error) { 128 w.stateLock.RLock() // No device communication, state lock is enough 129 defer w.stateLock.RUnlock() 130 131 status, failure := w.driver.Status() 132 if w.device == nil { 133 return "Closed", failure 134 } 135 return status, failure 136 } 137 138 // Open implements accounts.Wallet, attempting to open a USB connection to the 139 // hardware wallet. 140 func (w *wallet) Open(passphrase string) error { 141 w.stateLock.Lock() // State lock is enough since there's no connection yet at this point 142 defer w.stateLock.Unlock() 143 144 // If the device was already opened once, refuse to try again 145 if w.paths != nil { 146 return accounts.ErrWalletAlreadyOpen 147 } 148 // Make sure the actual device connection is done only once 149 if w.device == nil { 150 device, err := w.info.Open() 151 if err != nil { 152 return err 153 } 154 w.device = device 155 w.commsLock = make(chan struct{}, 1) 156 w.commsLock <- struct{}{} // Enable lock 157 } 158 // Delegate device initialization to the underlying driver 159 if err := w.driver.Open(w.device, passphrase); err != nil { 160 return err 161 } 162 // Connection successful, start life-cycle management 163 w.paths = make(map[common.Address]accounts.DerivationPath) 164 165 w.deriveReq = make(chan chan struct{}) 166 w.deriveQuit = make(chan chan error) 167 w.healthQuit = make(chan chan error) 168 169 go w.heartbeat() 170 go w.selfDerive() 171 172 // Notify anyone listening for wallet events that a new device is accessible 173 go w.hub.updateFeed.Send(accounts.WalletEvent{Wallet: w, Kind: accounts.WalletOpened}) 174 175 return nil 176 } 177 178 // heartbeat is a health check loop for the USB wallets to periodically verify 179 // whether they are still present or if they malfunctioned. 180 func (w *wallet) heartbeat() { 181 w.log.Debug("USB wallet health-check started") 182 defer w.log.Debug("USB wallet health-check stopped") 183 184 // Execute heartbeat checks until termination or error 185 var ( 186 errc chan error 187 err error 188 ) 189 for errc == nil && err == nil { 190 // Wait until termination is requested or the heartbeat cycle arrives 191 select { 192 case errc = <-w.healthQuit: 193 // Termination requested 194 continue 195 case <-time.After(heartbeatCycle): 196 // Heartbeat time 197 } 198 // Execute a tiny data exchange to see responsiveness 199 w.stateLock.RLock() 200 if w.device == nil { 201 // Terminated while waiting for the lock 202 w.stateLock.RUnlock() 203 continue 204 } 205 <-w.commsLock // Don't lock state while resolving version 206 err = w.driver.Heartbeat() 207 w.commsLock <- struct{}{} 208 w.stateLock.RUnlock() 209 210 if err != nil { 211 w.stateLock.Lock() // Lock state to tear the wallet down 212 w.close() 213 w.stateLock.Unlock() 214 } 215 // Ignore non hardware related errors 216 err = nil 217 } 218 // In case of error, wait for termination 219 if err != nil { 220 w.log.Debug("USB wallet health-check failed", "err", err) 221 errc = <-w.healthQuit 222 } 223 errc <- err 224 } 225 226 // Close implements accounts.Wallet, closing the USB connection to the device. 227 func (w *wallet) Close() error { 228 // Ensure the wallet was opened 229 w.stateLock.RLock() 230 hQuit, dQuit := w.healthQuit, w.deriveQuit 231 w.stateLock.RUnlock() 232 233 // Terminate the health checks 234 var herr error 235 if hQuit != nil { 236 errc := make(chan error) 237 hQuit <- errc 238 herr = <-errc // Save for later, we *must* close the USB 239 } 240 // Terminate the self-derivations 241 var derr error 242 if dQuit != nil { 243 errc := make(chan error) 244 dQuit <- errc 245 derr = <-errc // Save for later, we *must* close the USB 246 } 247 // Terminate the device connection 248 w.stateLock.Lock() 249 defer w.stateLock.Unlock() 250 251 w.healthQuit = nil 252 w.deriveQuit = nil 253 w.deriveReq = nil 254 255 if err := w.close(); err != nil { 256 return err 257 } 258 if herr != nil { 259 return herr 260 } 261 return derr 262 } 263 264 // close is the internal wallet closer that terminates the USB connection and 265 // resets all the fields to their defaults. 266 // 267 // Note, close assumes the state lock is held! 268 func (w *wallet) close() error { 269 // Allow duplicate closes, especially for health-check failures 270 if w.device == nil { 271 return nil 272 } 273 // Close the device, clear everything, then return 274 w.device.Close() 275 w.device = nil 276 277 w.accounts, w.paths = nil, nil 278 return w.driver.Close() 279 } 280 281 // Accounts implements accounts.Wallet, returning the list of accounts pinned to 282 // the USB hardware wallet. If self-derivation was enabled, the account list is 283 // periodically expanded based on current chain state. 284 func (w *wallet) Accounts() []accounts.Account { 285 // Attempt self-derivation if it's running 286 reqc := make(chan struct{}, 1) 287 select { 288 case w.deriveReq <- reqc: 289 // Self-derivation request accepted, wait for it 290 <-reqc 291 default: 292 // Self-derivation offline, throttled or busy, skip 293 } 294 // Return whatever account list we ended up with 295 w.stateLock.RLock() 296 defer w.stateLock.RUnlock() 297 298 cpy := make([]accounts.Account, len(w.accounts)) 299 copy(cpy, w.accounts) 300 return cpy 301 } 302 303 // selfDerive is an account derivation loop that upon request attempts to find 304 // new non-zero accounts. 305 func (w *wallet) selfDerive() { 306 w.log.Debug("USB wallet self-derivation started") 307 defer w.log.Debug("USB wallet self-derivation stopped") 308 309 // Execute self-derivations until termination or error 310 var ( 311 reqc chan struct{} 312 errc chan error 313 err error 314 ) 315 for errc == nil && err == nil { 316 // Wait until either derivation or termination is requested 317 select { 318 case errc = <-w.deriveQuit: 319 // Termination requested 320 continue 321 case reqc = <-w.deriveReq: 322 // Account discovery requested 323 } 324 // Derivation needs a chain and device access, skip if either unavailable 325 w.stateLock.RLock() 326 if w.device == nil || w.deriveChain == nil { 327 w.stateLock.RUnlock() 328 reqc <- struct{}{} 329 continue 330 } 331 select { 332 case <-w.commsLock: 333 default: 334 w.stateLock.RUnlock() 335 reqc <- struct{}{} 336 continue 337 } 338 // Device lock obtained, derive the next batch of accounts 339 var ( 340 accs []accounts.Account 341 paths []accounts.DerivationPath 342 343 nextPaths = append([]accounts.DerivationPath{}, w.deriveNextPaths...) 344 nextAddrs = append([]common.Address{}, w.deriveNextAddrs...) 345 346 context = context.Background() 347 ) 348 for i := 0; i < len(nextAddrs); i++ { 349 for empty := false; !empty; { 350 // Retrieve the next derived Ethereum account 351 if nextAddrs[i] == (common.Address{}) { 352 if nextAddrs[i], err = w.driver.Derive(nextPaths[i]); err != nil { 353 w.log.Warn("USB wallet account derivation failed", "err", err) 354 break 355 } 356 } 357 // Check the account's status against the current chain state 358 var ( 359 balance *big.Int 360 nonce uint64 361 ) 362 balance, err = w.deriveChain.BalanceAt(context, nextAddrs[i], nil) 363 if err != nil { 364 w.log.Warn("USB wallet balance retrieval failed", "err", err) 365 break 366 } 367 nonce, err = w.deriveChain.NonceAt(context, nextAddrs[i], nil) 368 if err != nil { 369 w.log.Warn("USB wallet nonce retrieval failed", "err", err) 370 break 371 } 372 // If the next account is empty, stop self-derivation, but add for the last base path 373 if balance.Sign() == 0 && nonce == 0 { 374 empty = true 375 if i < len(nextAddrs)-1 { 376 break 377 } 378 } 379 // We've just self-derived a new account, start tracking it locally 380 path := make(accounts.DerivationPath, len(nextPaths[i])) 381 copy(path[:], nextPaths[i][:]) 382 paths = append(paths, path) 383 384 account := accounts.Account{ 385 Address: nextAddrs[i], 386 URL: accounts.URL{Scheme: w.url.Scheme, Path: fmt.Sprintf("%s/%s", w.url.Path, path)}, 387 } 388 accs = append(accs, account) 389 390 // Display a log message to the user for new (or previously empty accounts) 391 if _, known := w.paths[nextAddrs[i]]; !known || (!empty && nextAddrs[i] == w.deriveNextAddrs[i]) { 392 w.log.Info("USB wallet discovered new account", "address", nextAddrs[i], "path", path, "balance", balance, "nonce", nonce) 393 } 394 // Fetch the next potential account 395 if !empty { 396 nextAddrs[i] = common.Address{} 397 nextPaths[i][len(nextPaths[i])-1]++ 398 } 399 } 400 } 401 // Self derivation complete, release device lock 402 w.commsLock <- struct{}{} 403 w.stateLock.RUnlock() 404 405 // Insert any accounts successfully derived 406 w.stateLock.Lock() 407 for i := 0; i < len(accs); i++ { 408 if _, ok := w.paths[accs[i].Address]; !ok { 409 w.accounts = append(w.accounts, accs[i]) 410 w.paths[accs[i].Address] = paths[i] 411 } 412 } 413 // Shift the self-derivation forward 414 // TODO(karalabe): don't overwrite changes from wallet.SelfDerive 415 w.deriveNextAddrs = nextAddrs 416 w.deriveNextPaths = nextPaths 417 w.stateLock.Unlock() 418 419 // Notify the user of termination and loop after a bit of time (to avoid trashing) 420 reqc <- struct{}{} 421 if err == nil { 422 select { 423 case errc = <-w.deriveQuit: 424 // Termination requested, abort 425 case <-time.After(selfDeriveThrottling): 426 // Waited enough, willing to self-derive again 427 } 428 } 429 } 430 // In case of error, wait for termination 431 if err != nil { 432 w.log.Debug("USB wallet self-derivation failed", "err", err) 433 errc = <-w.deriveQuit 434 } 435 errc <- err 436 } 437 438 // Contains implements accounts.Wallet, returning whether a particular account is 439 // or is not pinned into this wallet instance. Although we could attempt to resolve 440 // unpinned accounts, that would be an non-negligible hardware operation. 441 func (w *wallet) Contains(account accounts.Account) bool { 442 w.stateLock.RLock() 443 defer w.stateLock.RUnlock() 444 445 _, exists := w.paths[account.Address] 446 return exists 447 } 448 449 // Derive implements accounts.Wallet, deriving a new account at the specific 450 // derivation path. If pin is set to true, the account will be added to the list 451 // of tracked accounts. 452 func (w *wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) { 453 // Try to derive the actual account and update its URL if successful 454 w.stateLock.RLock() // Avoid device disappearing during derivation 455 456 if w.device == nil { 457 w.stateLock.RUnlock() 458 return accounts.Account{}, accounts.ErrWalletClosed 459 } 460 <-w.commsLock // Avoid concurrent hardware access 461 address, err := w.driver.Derive(path) 462 w.commsLock <- struct{}{} 463 464 w.stateLock.RUnlock() 465 466 // If an error occurred or no pinning was requested, return 467 if err != nil { 468 return accounts.Account{}, err 469 } 470 account := accounts.Account{ 471 Address: address, 472 URL: accounts.URL{Scheme: w.url.Scheme, Path: fmt.Sprintf("%s/%s", w.url.Path, path)}, 473 } 474 if !pin { 475 return account, nil 476 } 477 // Pinning needs to modify the state 478 w.stateLock.Lock() 479 defer w.stateLock.Unlock() 480 481 if _, ok := w.paths[address]; !ok { 482 w.accounts = append(w.accounts, account) 483 w.paths[address] = make(accounts.DerivationPath, len(path)) 484 copy(w.paths[address], path) 485 } 486 return account, nil 487 } 488 489 // SelfDerive sets a base account derivation path from which the wallet attempts 490 // to discover non zero accounts and automatically add them to list of tracked 491 // accounts. 492 // 493 // Note, self derivaton will increment the last component of the specified path 494 // opposed to decending into a child path to allow discovering accounts starting 495 // from non zero components. 496 // 497 // Some hardware wallets switched derivation paths through their evolution, so 498 // this method supports providing multiple bases to discover old user accounts 499 // too. Only the last base will be used to derive the next empty account. 500 // 501 // You can disable automatic account discovery by calling SelfDerive with a nil 502 // chain state reader. 503 func (w *wallet) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) { 504 w.stateLock.Lock() 505 defer w.stateLock.Unlock() 506 507 w.deriveNextPaths = make([]accounts.DerivationPath, len(bases)) 508 for i, base := range bases { 509 w.deriveNextPaths[i] = make(accounts.DerivationPath, len(base)) 510 copy(w.deriveNextPaths[i][:], base[:]) 511 } 512 w.deriveNextAddrs = make([]common.Address, len(bases)) 513 w.deriveChain = chain 514 } 515 516 // signHash implements accounts.Wallet, however signing arbitrary data is not 517 // supported for hardware wallets, so this method will always return an error. 518 func (w *wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) { 519 return nil, accounts.ErrNotSupported 520 } 521 522 // SignData signs keccak256(data). The mimetype parameter describes the type of data being signed 523 func (w *wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) { 524 return w.signHash(account, crypto.Keccak256(data)) 525 } 526 527 // SignDataWithPassphrase implements accounts.Wallet, attempting to sign the given 528 // data with the given account using passphrase as extra authentication. 529 // Since USB wallets don't rely on passphrases, these are silently ignored. 530 func (w *wallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) { 531 return w.SignData(account, mimeType, data) 532 } 533 534 func (w *wallet) SignText(account accounts.Account, text []byte) ([]byte, error) { 535 return w.signHash(account, accounts.TextHash(text)) 536 } 537 538 // SignTx implements accounts.Wallet. It sends the transaction over to the Ledger 539 // wallet to request a confirmation from the user. It returns either the signed 540 // transaction or a failure if the user denied the transaction. 541 // 542 // Note, if the version of the Ethereum application running on the Ledger wallet is 543 // too old to sign EIP-155 transactions, but such is requested nonetheless, an error 544 // will be returned opposed to silently signing in Homestead mode. 545 func (w *wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { 546 w.stateLock.RLock() // Comms have own mutex, this is for the state fields 547 defer w.stateLock.RUnlock() 548 549 if tx.IsPrivate() { 550 return nil, errors.New("Signing Quorum Private transactions with a USB wallet not yet supported") 551 } 552 553 // If the wallet is closed, abort 554 if w.device == nil { 555 return nil, accounts.ErrWalletClosed 556 } 557 // Make sure the requested account is contained within 558 path, ok := w.paths[account.Address] 559 if !ok { 560 return nil, accounts.ErrUnknownAccount 561 } 562 // All infos gathered and metadata checks out, request signing 563 <-w.commsLock 564 defer func() { w.commsLock <- struct{}{} }() 565 566 // Ensure the device isn't screwed with while user confirmation is pending 567 // TODO(karalabe): remove if hotplug lands on Windows 568 w.hub.commsLock.Lock() 569 w.hub.commsPend++ 570 w.hub.commsLock.Unlock() 571 572 defer func() { 573 w.hub.commsLock.Lock() 574 w.hub.commsPend-- 575 w.hub.commsLock.Unlock() 576 }() 577 // Sign the transaction and verify the sender to avoid hardware fault surprises 578 sender, signed, err := w.driver.SignTx(path, tx, chainID) 579 if err != nil { 580 return nil, err 581 } 582 if sender != account.Address { 583 return nil, fmt.Errorf("signer mismatch: expected %s, got %s", account.Address.Hex(), sender.Hex()) 584 } 585 return signed, nil 586 } 587 588 // SignHashWithPassphrase implements accounts.Wallet, however signing arbitrary 589 // data is not supported for Ledger wallets, so this method will always return 590 // an error. 591 func (w *wallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) { 592 return w.SignText(account, accounts.TextHash(text)) 593 } 594 595 // SignTxWithPassphrase implements accounts.Wallet, attempting to sign the given 596 // transaction with the given account using passphrase as extra authentication. 597 // Since USB wallets don't rely on passphrases, these are silently ignored. 598 func (w *wallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { 599 return w.SignTx(account, tx, chainID) 600 }