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