github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/accounts/scwallet/wallet.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 scwallet 18 19 import ( 20 "bytes" 21 "context" 22 "crypto/hmac" 23 "crypto/sha256" 24 "crypto/sha512" 25 "encoding/asn1" 26 "encoding/binary" 27 "errors" 28 "fmt" 29 "math/big" 30 "regexp" 31 "sort" 32 "strings" 33 "sync" 34 "time" 35 36 pcsc "github.com/gballet/go-libpcsclite" 37 "github.com/status-im/keycard-go/derivationpath" 38 39 "github.com/scroll-tech/go-ethereum" 40 "github.com/scroll-tech/go-ethereum/accounts" 41 "github.com/scroll-tech/go-ethereum/common" 42 "github.com/scroll-tech/go-ethereum/core/types" 43 "github.com/scroll-tech/go-ethereum/crypto" 44 "github.com/scroll-tech/go-ethereum/log" 45 ) 46 47 // ErrPairingPasswordNeeded is returned if opening the smart card requires pairing with a pairing 48 // password. In this case, the calling application should request user input to enter 49 // the pairing password and send it back. 50 var ErrPairingPasswordNeeded = errors.New("smartcard: pairing password needed") 51 52 // ErrPINNeeded is returned if opening the smart card requires a PIN code. In 53 // this case, the calling application should request user input to enter the PIN 54 // and send it back. 55 var ErrPINNeeded = errors.New("smartcard: pin needed") 56 57 // ErrPINUnblockNeeded is returned if opening the smart card requires a PIN code, 58 // but all PIN attempts have already been exhausted. In this case the calling 59 // application should request user input for the PUK and a new PIN code to set 60 // fo the card. 61 var ErrPINUnblockNeeded = errors.New("smartcard: pin unblock needed") 62 63 // ErrAlreadyOpen is returned if the smart card is attempted to be opened, but 64 // there is already a paired and unlocked session. 65 var ErrAlreadyOpen = errors.New("smartcard: already open") 66 67 // ErrPubkeyMismatch is returned if the public key recovered from a signature 68 // does not match the one expected by the user. 69 var ErrPubkeyMismatch = errors.New("smartcard: recovered public key mismatch") 70 71 var ( 72 appletAID = []byte{0xA0, 0x00, 0x00, 0x08, 0x04, 0x00, 0x01, 0x01, 0x01} 73 // DerivationSignatureHash is used to derive the public key from the signature of this hash 74 DerivationSignatureHash = sha256.Sum256(common.Hash{}.Bytes()) 75 ) 76 77 // List of APDU command-related constants 78 const ( 79 claISO7816 = 0 80 claSCWallet = 0x80 81 82 insSelect = 0xA4 83 insGetResponse = 0xC0 84 sw1GetResponse = 0x61 85 sw1Ok = 0x90 86 87 insVerifyPin = 0x20 88 insUnblockPin = 0x22 89 insExportKey = 0xC2 90 insSign = 0xC0 91 insLoadKey = 0xD0 92 insDeriveKey = 0xD1 93 insStatus = 0xF2 94 ) 95 96 // List of ADPU command parameters 97 const ( 98 P1DeriveKeyFromMaster = uint8(0x00) 99 P1DeriveKeyFromParent = uint8(0x01) 100 P1DeriveKeyFromCurrent = uint8(0x10) 101 statusP1WalletStatus = uint8(0x00) 102 statusP1Path = uint8(0x01) 103 signP1PrecomputedHash = uint8(0x01) 104 signP2OnlyBlock = uint8(0x81) 105 exportP1Any = uint8(0x00) 106 exportP2Pubkey = uint8(0x01) 107 ) 108 109 // Minimum time to wait between self derivation attempts, even it the user is 110 // requesting accounts like crazy. 111 const selfDeriveThrottling = time.Second 112 113 // Wallet represents a smartcard wallet instance. 114 type Wallet struct { 115 Hub *Hub // A handle to the Hub that instantiated this wallet. 116 PublicKey []byte // The wallet's public key (used for communication and identification, not signing!) 117 118 lock sync.Mutex // Lock that gates access to struct fields and communication with the card 119 card *pcsc.Card // A handle to the smartcard interface for the wallet. 120 session *Session // The secure communication session with the card 121 log log.Logger // Contextual logger to tag the base with its id 122 123 deriveNextPaths []accounts.DerivationPath // Next derivation paths for account auto-discovery (multiple bases supported) 124 deriveNextAddrs []common.Address // Next derived account addresses for auto-discovery (multiple bases supported) 125 deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with 126 deriveReq chan chan struct{} // Channel to request a self-derivation on 127 deriveQuit chan chan error // Channel to terminate the self-deriver with 128 } 129 130 // NewWallet constructs and returns a new Wallet instance. 131 func NewWallet(hub *Hub, card *pcsc.Card) *Wallet { 132 wallet := &Wallet{ 133 Hub: hub, 134 card: card, 135 } 136 return wallet 137 } 138 139 // transmit sends an APDU to the smartcard and receives and decodes the response. 140 // It automatically handles requests by the card to fetch the return data separately, 141 // and returns an error if the response status code is not success. 142 func transmit(card *pcsc.Card, command *commandAPDU) (*responseAPDU, error) { 143 data, err := command.serialize() 144 if err != nil { 145 return nil, err 146 } 147 148 responseData, _, err := card.Transmit(data) 149 if err != nil { 150 return nil, err 151 } 152 153 response := new(responseAPDU) 154 if err = response.deserialize(responseData); err != nil { 155 return nil, err 156 } 157 158 // Are we being asked to fetch the response separately? 159 if response.Sw1 == sw1GetResponse && (command.Cla != claISO7816 || command.Ins != insGetResponse) { 160 return transmit(card, &commandAPDU{ 161 Cla: claISO7816, 162 Ins: insGetResponse, 163 P1: 0, 164 P2: 0, 165 Data: nil, 166 Le: response.Sw2, 167 }) 168 } 169 170 if response.Sw1 != sw1Ok { 171 return nil, fmt.Errorf("unexpected insecure response status Cla=0x%x, Ins=0x%x, Sw=0x%x%x", command.Cla, command.Ins, response.Sw1, response.Sw2) 172 } 173 174 return response, nil 175 } 176 177 // applicationInfo encodes information about the smartcard application - its 178 // instance UID and public key. 179 type applicationInfo struct { 180 InstanceUID []byte `asn1:"tag:15"` 181 PublicKey []byte `asn1:"tag:0"` 182 } 183 184 // connect connects to the wallet application and establishes a secure channel with it. 185 // must be called before any other interaction with the wallet. 186 func (w *Wallet) connect() error { 187 w.lock.Lock() 188 defer w.lock.Unlock() 189 190 appinfo, err := w.doselect() 191 if err != nil { 192 return err 193 } 194 195 channel, err := NewSecureChannelSession(w.card, appinfo.PublicKey) 196 if err != nil { 197 return err 198 } 199 200 w.PublicKey = appinfo.PublicKey 201 w.log = log.New("url", w.URL()) 202 w.session = &Session{ 203 Wallet: w, 204 Channel: channel, 205 } 206 return nil 207 } 208 209 // doselect is an internal (unlocked) function to send a SELECT APDU to the card. 210 func (w *Wallet) doselect() (*applicationInfo, error) { 211 response, err := transmit(w.card, &commandAPDU{ 212 Cla: claISO7816, 213 Ins: insSelect, 214 P1: 4, 215 P2: 0, 216 Data: appletAID, 217 }) 218 if err != nil { 219 return nil, err 220 } 221 222 appinfo := new(applicationInfo) 223 if _, err := asn1.UnmarshalWithParams(response.Data, appinfo, "tag:4"); err != nil { 224 return nil, err 225 } 226 return appinfo, nil 227 } 228 229 // ping checks the card's status and returns an error if unsuccessful. 230 func (w *Wallet) ping() error { 231 w.lock.Lock() 232 defer w.lock.Unlock() 233 234 // We can't ping if not paired 235 if !w.session.paired() { 236 return nil 237 } 238 if _, err := w.session.walletStatus(); err != nil { 239 return err 240 } 241 return nil 242 } 243 244 // release releases any resources held by an open wallet instance. 245 func (w *Wallet) release() error { 246 if w.session != nil { 247 return w.session.release() 248 } 249 return nil 250 } 251 252 // pair is an internal (unlocked) function for establishing a new pairing 253 // with the wallet. 254 func (w *Wallet) pair(puk []byte) error { 255 if w.session.paired() { 256 return fmt.Errorf("wallet already paired") 257 } 258 pairing, err := w.session.pair(puk) 259 if err != nil { 260 return err 261 } 262 if err = w.Hub.setPairing(w, &pairing); err != nil { 263 return err 264 } 265 return w.session.authenticate(pairing) 266 } 267 268 // Unpair deletes an existing wallet pairing. 269 func (w *Wallet) Unpair(pin []byte) error { 270 w.lock.Lock() 271 defer w.lock.Unlock() 272 273 if !w.session.paired() { 274 return fmt.Errorf("wallet %x not paired", w.PublicKey) 275 } 276 if err := w.session.verifyPin(pin); err != nil { 277 return fmt.Errorf("failed to verify pin: %s", err) 278 } 279 if err := w.session.unpair(); err != nil { 280 return fmt.Errorf("failed to unpair: %s", err) 281 } 282 if err := w.Hub.setPairing(w, nil); err != nil { 283 return err 284 } 285 return nil 286 } 287 288 // URL retrieves the canonical path under which this wallet is reachable. It is 289 // user by upper layers to define a sorting order over all wallets from multiple 290 // backends. 291 func (w *Wallet) URL() accounts.URL { 292 return accounts.URL{ 293 Scheme: w.Hub.scheme, 294 Path: fmt.Sprintf("%x", w.PublicKey[1:5]), // Byte #0 isn't unique; 1:5 covers << 64K cards, bump to 1:9 for << 4M 295 } 296 } 297 298 // Status returns a textual status to aid the user in the current state of the 299 // wallet. It also returns an error indicating any failure the wallet might have 300 // encountered. 301 func (w *Wallet) Status() (string, error) { 302 w.lock.Lock() 303 defer w.lock.Unlock() 304 305 // If the card is not paired, we can only wait 306 if !w.session.paired() { 307 return "Unpaired, waiting for pairing password", nil 308 } 309 // Yay, we have an encrypted session, retrieve the actual status 310 status, err := w.session.walletStatus() 311 if err != nil { 312 return fmt.Sprintf("Failed: %v", err), err 313 } 314 switch { 315 case !w.session.verified && status.PinRetryCount == 0 && status.PukRetryCount == 0: 316 return "Bricked, waiting for full wipe", nil 317 case !w.session.verified && status.PinRetryCount == 0: 318 return fmt.Sprintf("Blocked, waiting for PUK (%d attempts left) and new PIN", status.PukRetryCount), nil 319 case !w.session.verified: 320 return fmt.Sprintf("Locked, waiting for PIN (%d attempts left)", status.PinRetryCount), nil 321 case !status.Initialized: 322 return "Empty, waiting for initialization", nil 323 default: 324 return "Online", nil 325 } 326 } 327 328 // Open initializes access to a wallet instance. It is not meant to unlock or 329 // decrypt account keys, rather simply to establish a connection to hardware 330 // wallets and/or to access derivation seeds. 331 // 332 // The passphrase parameter may or may not be used by the implementation of a 333 // particular wallet instance. The reason there is no passwordless open method 334 // is to strive towards a uniform wallet handling, oblivious to the different 335 // backend providers. 336 // 337 // Please note, if you open a wallet, you must close it to release any allocated 338 // resources (especially important when working with hardware wallets). 339 func (w *Wallet) Open(passphrase string) error { 340 w.lock.Lock() 341 defer w.lock.Unlock() 342 343 // If the session is already open, bail out 344 if w.session.verified { 345 return ErrAlreadyOpen 346 } 347 // If the smart card is not yet paired, attempt to do so either from a previous 348 // pairing key or form the supplied PUK code. 349 if !w.session.paired() { 350 // If a previous pairing exists, only ever try to use that 351 if pairing := w.Hub.pairing(w); pairing != nil { 352 if err := w.session.authenticate(*pairing); err != nil { 353 return fmt.Errorf("failed to authenticate card %x: %s", w.PublicKey[:4], err) 354 } 355 // Pairing still ok, fall through to PIN checks 356 } else { 357 // If no passphrase was supplied, request the PUK from the user 358 if passphrase == "" { 359 return ErrPairingPasswordNeeded 360 } 361 // Attempt to pair the smart card with the user supplied PUK 362 if err := w.pair([]byte(passphrase)); err != nil { 363 return err 364 } 365 // Pairing succeeded, fall through to PIN checks. This will of course fail, 366 // but we can't return ErrPINNeeded directly here because we don't know whether 367 // a PIN check or a PIN reset is needed. 368 passphrase = "" 369 } 370 } 371 // The smart card was successfully paired, retrieve its status to check whether 372 // PIN verification or unblocking is needed. 373 status, err := w.session.walletStatus() 374 if err != nil { 375 return err 376 } 377 // Request the appropriate next authentication data, or use the one supplied 378 switch { 379 case passphrase == "" && status.PinRetryCount > 0: 380 return ErrPINNeeded 381 case passphrase == "": 382 return ErrPINUnblockNeeded 383 case status.PinRetryCount > 0: 384 if !regexp.MustCompile(`^[0-9]{6,}$`).MatchString(passphrase) { 385 w.log.Error("PIN needs to be at least 6 digits") 386 return ErrPINNeeded 387 } 388 if err := w.session.verifyPin([]byte(passphrase)); err != nil { 389 return err 390 } 391 default: 392 if !regexp.MustCompile(`^[0-9]{12,}$`).MatchString(passphrase) { 393 w.log.Error("PUK needs to be at least 12 digits") 394 return ErrPINUnblockNeeded 395 } 396 if err := w.session.unblockPin([]byte(passphrase)); err != nil { 397 return err 398 } 399 } 400 // Smart card paired and unlocked, initialize and register 401 w.deriveReq = make(chan chan struct{}) 402 w.deriveQuit = make(chan chan error) 403 404 go w.selfDerive() 405 406 // Notify anyone listening for wallet events that a new device is accessible 407 go w.Hub.updateFeed.Send(accounts.WalletEvent{Wallet: w, Kind: accounts.WalletOpened}) 408 409 return nil 410 } 411 412 // Close stops and closes the wallet, freeing any resources. 413 func (w *Wallet) Close() error { 414 // Ensure the wallet was opened 415 w.lock.Lock() 416 dQuit := w.deriveQuit 417 w.lock.Unlock() 418 419 // Terminate the self-derivations 420 var derr error 421 if dQuit != nil { 422 errc := make(chan error) 423 dQuit <- errc 424 derr = <-errc // Save for later, we *must* close the USB 425 } 426 // Terminate the device connection 427 w.lock.Lock() 428 defer w.lock.Unlock() 429 430 w.deriveQuit = nil 431 w.deriveReq = nil 432 433 if err := w.release(); err != nil { 434 return err 435 } 436 return derr 437 } 438 439 // selfDerive is an account derivation loop that upon request attempts to find 440 // new non-zero accounts. 441 func (w *Wallet) selfDerive() { 442 w.log.Debug("Smart card wallet self-derivation started") 443 defer w.log.Debug("Smart card wallet self-derivation stopped") 444 445 // Execute self-derivations until termination or error 446 var ( 447 reqc chan struct{} 448 errc chan error 449 err error 450 ) 451 for errc == nil && err == nil { 452 // Wait until either derivation or termination is requested 453 select { 454 case errc = <-w.deriveQuit: 455 // Termination requested 456 continue 457 case reqc = <-w.deriveReq: 458 // Account discovery requested 459 } 460 // Derivation needs a chain and device access, skip if either unavailable 461 w.lock.Lock() 462 if w.session == nil || w.deriveChain == nil { 463 w.lock.Unlock() 464 reqc <- struct{}{} 465 continue 466 } 467 pairing := w.Hub.pairing(w) 468 469 // Device lock obtained, derive the next batch of accounts 470 var ( 471 paths []accounts.DerivationPath 472 nextAcc accounts.Account 473 474 nextPaths = append([]accounts.DerivationPath{}, w.deriveNextPaths...) 475 nextAddrs = append([]common.Address{}, w.deriveNextAddrs...) 476 477 context = context.Background() 478 ) 479 for i := 0; i < len(nextAddrs); i++ { 480 for empty := false; !empty; { 481 // Retrieve the next derived Ethereum account 482 if nextAddrs[i] == (common.Address{}) { 483 if nextAcc, err = w.session.derive(nextPaths[i]); err != nil { 484 w.log.Warn("Smartcard wallet account derivation failed", "err", err) 485 break 486 } 487 nextAddrs[i] = nextAcc.Address 488 } 489 // Check the account's status against the current chain state 490 var ( 491 balance *big.Int 492 nonce uint64 493 ) 494 balance, err = w.deriveChain.BalanceAt(context, nextAddrs[i], nil) 495 if err != nil { 496 w.log.Warn("Smartcard wallet balance retrieval failed", "err", err) 497 break 498 } 499 nonce, err = w.deriveChain.NonceAt(context, nextAddrs[i], nil) 500 if err != nil { 501 w.log.Warn("Smartcard wallet nonce retrieval failed", "err", err) 502 break 503 } 504 // If the next account is empty, stop self-derivation, but add for the last base path 505 if balance.Sign() == 0 && nonce == 0 { 506 empty = true 507 if i < len(nextAddrs)-1 { 508 break 509 } 510 } 511 // We've just self-derived a new account, start tracking it locally 512 path := make(accounts.DerivationPath, len(nextPaths[i])) 513 copy(path[:], nextPaths[i][:]) 514 paths = append(paths, path) 515 516 // Display a log message to the user for new (or previously empty accounts) 517 if _, known := pairing.Accounts[nextAddrs[i]]; !known || !empty || nextAddrs[i] != w.deriveNextAddrs[i] { 518 w.log.Info("Smartcard wallet discovered new account", "address", nextAddrs[i], "path", path, "balance", balance, "nonce", nonce) 519 } 520 pairing.Accounts[nextAddrs[i]] = path 521 522 // Fetch the next potential account 523 if !empty { 524 nextAddrs[i] = common.Address{} 525 nextPaths[i][len(nextPaths[i])-1]++ 526 } 527 } 528 } 529 // If there are new accounts, write them out 530 if len(paths) > 0 { 531 err = w.Hub.setPairing(w, pairing) 532 } 533 // Shift the self-derivation forward 534 w.deriveNextAddrs = nextAddrs 535 w.deriveNextPaths = nextPaths 536 537 // Self derivation complete, release device lock 538 w.lock.Unlock() 539 540 // Notify the user of termination and loop after a bit of time (to avoid trashing) 541 reqc <- struct{}{} 542 if err == nil { 543 select { 544 case errc = <-w.deriveQuit: 545 // Termination requested, abort 546 case <-time.After(selfDeriveThrottling): 547 // Waited enough, willing to self-derive again 548 } 549 } 550 } 551 // In case of error, wait for termination 552 if err != nil { 553 w.log.Debug("Smartcard wallet self-derivation failed", "err", err) 554 errc = <-w.deriveQuit 555 } 556 errc <- err 557 } 558 559 // Accounts retrieves the list of signing accounts the wallet is currently aware 560 // of. For hierarchical deterministic wallets, the list will not be exhaustive, 561 // rather only contain the accounts explicitly pinned during account derivation. 562 func (w *Wallet) Accounts() []accounts.Account { 563 // Attempt self-derivation if it's running 564 reqc := make(chan struct{}, 1) 565 select { 566 case w.deriveReq <- reqc: 567 // Self-derivation request accepted, wait for it 568 <-reqc 569 default: 570 // Self-derivation offline, throttled or busy, skip 571 } 572 573 w.lock.Lock() 574 defer w.lock.Unlock() 575 576 if pairing := w.Hub.pairing(w); pairing != nil { 577 ret := make([]accounts.Account, 0, len(pairing.Accounts)) 578 for address, path := range pairing.Accounts { 579 ret = append(ret, w.makeAccount(address, path)) 580 } 581 sort.Sort(accounts.AccountsByURL(ret)) 582 return ret 583 } 584 return nil 585 } 586 587 func (w *Wallet) makeAccount(address common.Address, path accounts.DerivationPath) accounts.Account { 588 return accounts.Account{ 589 Address: address, 590 URL: accounts.URL{ 591 Scheme: w.Hub.scheme, 592 Path: fmt.Sprintf("%x/%s", w.PublicKey[1:3], path.String()), 593 }, 594 } 595 } 596 597 // Contains returns whether an account is part of this particular wallet or not. 598 func (w *Wallet) Contains(account accounts.Account) bool { 599 if pairing := w.Hub.pairing(w); pairing != nil { 600 _, ok := pairing.Accounts[account.Address] 601 return ok 602 } 603 return false 604 } 605 606 // Initialize installs a keypair generated from the provided key into the wallet. 607 func (w *Wallet) Initialize(seed []byte) error { 608 go w.selfDerive() 609 // DO NOT lock at this stage, as the initialize 610 // function relies on Status() 611 return w.session.initialize(seed) 612 } 613 614 // Derive attempts to explicitly derive a hierarchical deterministic account at 615 // the specified derivation path. If requested, the derived account will be added 616 // to the wallet's tracked account list. 617 func (w *Wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) { 618 w.lock.Lock() 619 defer w.lock.Unlock() 620 621 account, err := w.session.derive(path) 622 if err != nil { 623 return accounts.Account{}, err 624 } 625 626 if pin { 627 pairing := w.Hub.pairing(w) 628 pairing.Accounts[account.Address] = path 629 if err := w.Hub.setPairing(w, pairing); err != nil { 630 return accounts.Account{}, err 631 } 632 } 633 634 return account, nil 635 } 636 637 // SelfDerive sets a base account derivation path from which the wallet attempts 638 // to discover non zero accounts and automatically add them to list of tracked 639 // accounts. 640 // 641 // Note, self derivation will increment the last component of the specified path 642 // opposed to decending into a child path to allow discovering accounts starting 643 // from non zero components. 644 // 645 // Some hardware wallets switched derivation paths through their evolution, so 646 // this method supports providing multiple bases to discover old user accounts 647 // too. Only the last base will be used to derive the next empty account. 648 // 649 // You can disable automatic account discovery by calling SelfDerive with a nil 650 // chain state reader. 651 func (w *Wallet) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) { 652 w.lock.Lock() 653 defer w.lock.Unlock() 654 655 w.deriveNextPaths = make([]accounts.DerivationPath, len(bases)) 656 for i, base := range bases { 657 w.deriveNextPaths[i] = make(accounts.DerivationPath, len(base)) 658 copy(w.deriveNextPaths[i][:], base[:]) 659 } 660 w.deriveNextAddrs = make([]common.Address, len(bases)) 661 w.deriveChain = chain 662 } 663 664 // SignData requests the wallet to sign the hash of the given data. 665 // 666 // It looks up the account specified either solely via its address contained within, 667 // or optionally with the aid of any location metadata from the embedded URL field. 668 // 669 // If the wallet requires additional authentication to sign the request (e.g. 670 // a password to decrypt the account, or a PIN code o verify the transaction), 671 // an AuthNeededError instance will be returned, containing infos for the user 672 // about which fields or actions are needed. The user may retry by providing 673 // the needed details via SignDataWithPassphrase, or by other means (e.g. unlock 674 // the account in a keystore). 675 func (w *Wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) { 676 return w.signHash(account, crypto.Keccak256(data)) 677 } 678 679 func (w *Wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) { 680 w.lock.Lock() 681 defer w.lock.Unlock() 682 683 path, err := w.findAccountPath(account) 684 if err != nil { 685 return nil, err 686 } 687 688 return w.session.sign(path, hash) 689 } 690 691 // SignTx requests the wallet to sign the given transaction. 692 // 693 // It looks up the account specified either solely via its address contained within, 694 // or optionally with the aid of any location metadata from the embedded URL field. 695 // 696 // If the wallet requires additional authentication to sign the request (e.g. 697 // a password to decrypt the account, or a PIN code o verify the transaction), 698 // an AuthNeededError instance will be returned, containing infos for the user 699 // about which fields or actions are needed. The user may retry by providing 700 // the needed details via SignTxWithPassphrase, or by other means (e.g. unlock 701 // the account in a keystore). 702 func (w *Wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { 703 signer := types.LatestSignerForChainID(chainID) 704 hash := signer.Hash(tx) 705 sig, err := w.signHash(account, hash[:]) 706 if err != nil { 707 return nil, err 708 } 709 return tx.WithSignature(signer, sig) 710 } 711 712 // SignDataWithPassphrase requests the wallet to sign the given hash with the 713 // given passphrase as extra authentication information. 714 // 715 // It looks up the account specified either solely via its address contained within, 716 // or optionally with the aid of any location metadata from the embedded URL field. 717 func (w *Wallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) { 718 return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(data)) 719 } 720 721 func (w *Wallet) signHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) { 722 if !w.session.verified { 723 if err := w.Open(passphrase); err != nil { 724 return nil, err 725 } 726 } 727 728 return w.signHash(account, hash) 729 } 730 731 // SignText requests the wallet to sign the hash of a given piece of data, prefixed 732 // by the Ethereum prefix scheme 733 // It looks up the account specified either solely via its address contained within, 734 // or optionally with the aid of any location metadata from the embedded URL field. 735 // 736 // If the wallet requires additional authentication to sign the request (e.g. 737 // a password to decrypt the account, or a PIN code o verify the transaction), 738 // an AuthNeededError instance will be returned, containing infos for the user 739 // about which fields or actions are needed. The user may retry by providing 740 // the needed details via SignHashWithPassphrase, or by other means (e.g. unlock 741 // the account in a keystore). 742 func (w *Wallet) SignText(account accounts.Account, text []byte) ([]byte, error) { 743 return w.signHash(account, accounts.TextHash(text)) 744 } 745 746 // SignTextWithPassphrase implements accounts.Wallet, attempting to sign the 747 // given hash with the given account using passphrase as extra authentication 748 func (w *Wallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) { 749 return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(accounts.TextHash(text))) 750 } 751 752 // SignTxWithPassphrase requests the wallet to sign the given transaction, with the 753 // given passphrase as extra authentication information. 754 // 755 // It looks up the account specified either solely via its address contained within, 756 // or optionally with the aid of any location metadata from the embedded URL field. 757 func (w *Wallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { 758 if !w.session.verified { 759 if err := w.Open(passphrase); err != nil { 760 return nil, err 761 } 762 } 763 return w.SignTx(account, tx, chainID) 764 } 765 766 // findAccountPath returns the derivation path for the provided account. 767 // It first checks for the address in the list of pinned accounts, and if it is 768 // not found, attempts to parse the derivation path from the account's URL. 769 func (w *Wallet) findAccountPath(account accounts.Account) (accounts.DerivationPath, error) { 770 pairing := w.Hub.pairing(w) 771 if path, ok := pairing.Accounts[account.Address]; ok { 772 return path, nil 773 } 774 775 // Look for the path in the URL 776 if account.URL.Scheme != w.Hub.scheme { 777 return nil, fmt.Errorf("scheme %s does not match wallet scheme %s", account.URL.Scheme, w.Hub.scheme) 778 } 779 780 parts := strings.SplitN(account.URL.Path, "/", 2) 781 if len(parts) != 2 { 782 return nil, fmt.Errorf("invalid URL format: %s", account.URL) 783 } 784 785 if parts[0] != fmt.Sprintf("%x", w.PublicKey[1:3]) { 786 return nil, fmt.Errorf("URL %s is not for this wallet", account.URL) 787 } 788 789 return accounts.ParseDerivationPath(parts[1]) 790 } 791 792 // Session represents a secured communication session with the wallet. 793 type Session struct { 794 Wallet *Wallet // A handle to the wallet that opened the session 795 Channel *SecureChannelSession // A secure channel for encrypted messages 796 verified bool // Whether the pin has been verified in this session. 797 } 798 799 // pair establishes a new pairing over this channel, using the provided secret. 800 func (s *Session) pair(secret []byte) (smartcardPairing, error) { 801 err := s.Channel.Pair(secret) 802 if err != nil { 803 return smartcardPairing{}, err 804 } 805 806 return smartcardPairing{ 807 PublicKey: s.Wallet.PublicKey, 808 PairingIndex: s.Channel.PairingIndex, 809 PairingKey: s.Channel.PairingKey, 810 Accounts: make(map[common.Address]accounts.DerivationPath), 811 }, nil 812 } 813 814 // unpair deletes an existing pairing. 815 func (s *Session) unpair() error { 816 if !s.verified { 817 return fmt.Errorf("unpair requires that the PIN be verified") 818 } 819 return s.Channel.Unpair() 820 } 821 822 // verifyPin unlocks a wallet with the provided pin. 823 func (s *Session) verifyPin(pin []byte) error { 824 if _, err := s.Channel.transmitEncrypted(claSCWallet, insVerifyPin, 0, 0, pin); err != nil { 825 return err 826 } 827 s.verified = true 828 return nil 829 } 830 831 // unblockPin unblocks a wallet with the provided puk and resets the pin to the 832 // new one specified. 833 func (s *Session) unblockPin(pukpin []byte) error { 834 if _, err := s.Channel.transmitEncrypted(claSCWallet, insUnblockPin, 0, 0, pukpin); err != nil { 835 return err 836 } 837 s.verified = true 838 return nil 839 } 840 841 // release releases resources associated with the channel. 842 func (s *Session) release() error { 843 return s.Wallet.card.Disconnect(pcsc.LeaveCard) 844 } 845 846 // paired returns true if a valid pairing exists. 847 func (s *Session) paired() bool { 848 return s.Channel.PairingKey != nil 849 } 850 851 // authenticate uses an existing pairing to establish a secure channel. 852 func (s *Session) authenticate(pairing smartcardPairing) error { 853 if !bytes.Equal(s.Wallet.PublicKey, pairing.PublicKey) { 854 return fmt.Errorf("cannot pair using another wallet's pairing; %x != %x", s.Wallet.PublicKey, pairing.PublicKey) 855 } 856 s.Channel.PairingKey = pairing.PairingKey 857 s.Channel.PairingIndex = pairing.PairingIndex 858 return s.Channel.Open() 859 } 860 861 // walletStatus describes a smartcard wallet's status information. 862 type walletStatus struct { 863 PinRetryCount int // Number of remaining PIN retries 864 PukRetryCount int // Number of remaining PUK retries 865 Initialized bool // Whether the card has been initialized with a private key 866 } 867 868 // walletStatus fetches the wallet's status from the card. 869 func (s *Session) walletStatus() (*walletStatus, error) { 870 response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1WalletStatus, 0, nil) 871 if err != nil { 872 return nil, err 873 } 874 875 status := new(walletStatus) 876 if _, err := asn1.UnmarshalWithParams(response.Data, status, "tag:3"); err != nil { 877 return nil, err 878 } 879 return status, nil 880 } 881 882 // derivationPath fetches the wallet's current derivation path from the card. 883 //lint:ignore U1000 needs to be added to the console interface 884 func (s *Session) derivationPath() (accounts.DerivationPath, error) { 885 response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1Path, 0, nil) 886 if err != nil { 887 return nil, err 888 } 889 buf := bytes.NewReader(response.Data) 890 path := make(accounts.DerivationPath, len(response.Data)/4) 891 return path, binary.Read(buf, binary.BigEndian, &path) 892 } 893 894 // initializeData contains data needed to initialize the smartcard wallet. 895 type initializeData struct { 896 PublicKey []byte `asn1:"tag:0"` 897 PrivateKey []byte `asn1:"tag:1"` 898 ChainCode []byte `asn1:"tag:2"` 899 } 900 901 // initialize initializes the card with new key data. 902 func (s *Session) initialize(seed []byte) error { 903 // Check that the wallet isn't currently initialized, 904 // otherwise the key would be overwritten. 905 status, err := s.Wallet.Status() 906 if err != nil { 907 return err 908 } 909 if status == "Online" { 910 return fmt.Errorf("card is already initialized, cowardly refusing to proceed") 911 } 912 913 s.Wallet.lock.Lock() 914 defer s.Wallet.lock.Unlock() 915 916 // HMAC the seed to produce the private key and chain code 917 mac := hmac.New(sha512.New, []byte("Bitcoin seed")) 918 mac.Write(seed) 919 seed = mac.Sum(nil) 920 921 key, err := crypto.ToECDSA(seed[:32]) 922 if err != nil { 923 return err 924 } 925 926 id := initializeData{} 927 id.PublicKey = crypto.FromECDSAPub(&key.PublicKey) 928 id.PrivateKey = seed[:32] 929 id.ChainCode = seed[32:] 930 data, err := asn1.Marshal(id) 931 if err != nil { 932 return err 933 } 934 935 // Nasty hack to force the top-level struct tag to be context-specific 936 data[0] = 0xA1 937 938 _, err = s.Channel.transmitEncrypted(claSCWallet, insLoadKey, 0x02, 0, data) 939 return err 940 } 941 942 // derive derives a new HD key path on the card. 943 func (s *Session) derive(path accounts.DerivationPath) (accounts.Account, error) { 944 startingPoint, path, err := derivationpath.Decode(path.String()) 945 if err != nil { 946 return accounts.Account{}, err 947 } 948 949 var p1 uint8 950 switch startingPoint { 951 case derivationpath.StartingPointMaster: 952 p1 = P1DeriveKeyFromMaster 953 case derivationpath.StartingPointParent: 954 p1 = P1DeriveKeyFromParent 955 case derivationpath.StartingPointCurrent: 956 p1 = P1DeriveKeyFromCurrent 957 default: 958 return accounts.Account{}, fmt.Errorf("invalid startingPoint %d", startingPoint) 959 } 960 961 data := new(bytes.Buffer) 962 for _, segment := range path { 963 if err := binary.Write(data, binary.BigEndian, segment); err != nil { 964 return accounts.Account{}, err 965 } 966 } 967 968 _, err = s.Channel.transmitEncrypted(claSCWallet, insDeriveKey, p1, 0, data.Bytes()) 969 if err != nil { 970 return accounts.Account{}, err 971 } 972 973 response, err := s.Channel.transmitEncrypted(claSCWallet, insSign, 0, 0, DerivationSignatureHash[:]) 974 if err != nil { 975 return accounts.Account{}, err 976 } 977 978 sigdata := new(signatureData) 979 if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil { 980 return accounts.Account{}, err 981 } 982 rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes() 983 sig := make([]byte, 65) 984 copy(sig[32-len(rbytes):32], rbytes) 985 copy(sig[64-len(sbytes):64], sbytes) 986 987 if err := confirmPublicKey(sig, sigdata.PublicKey); err != nil { 988 return accounts.Account{}, err 989 } 990 pub, err := crypto.UnmarshalPubkey(sigdata.PublicKey) 991 if err != nil { 992 return accounts.Account{}, err 993 } 994 return s.Wallet.makeAccount(crypto.PubkeyToAddress(*pub), path), nil 995 } 996 997 // keyExport contains information on an exported keypair. 998 //lint:ignore U1000 needs to be added to the console interface 999 type keyExport struct { 1000 PublicKey []byte `asn1:"tag:0"` 1001 PrivateKey []byte `asn1:"tag:1,optional"` 1002 } 1003 1004 // publicKey returns the public key for the current derivation path. 1005 //lint:ignore U1000 needs to be added to the console interface 1006 func (s *Session) publicKey() ([]byte, error) { 1007 response, err := s.Channel.transmitEncrypted(claSCWallet, insExportKey, exportP1Any, exportP2Pubkey, nil) 1008 if err != nil { 1009 return nil, err 1010 } 1011 keys := new(keyExport) 1012 if _, err := asn1.UnmarshalWithParams(response.Data, keys, "tag:1"); err != nil { 1013 return nil, err 1014 } 1015 return keys.PublicKey, nil 1016 } 1017 1018 // signatureData contains information on a signature - the signature itself and 1019 // the corresponding public key. 1020 type signatureData struct { 1021 PublicKey []byte `asn1:"tag:0"` 1022 Signature struct { 1023 R *big.Int 1024 S *big.Int 1025 } 1026 } 1027 1028 // sign asks the card to sign a message, and returns a valid signature after 1029 // recovering the v value. 1030 func (s *Session) sign(path accounts.DerivationPath, hash []byte) ([]byte, error) { 1031 startTime := time.Now() 1032 _, err := s.derive(path) 1033 if err != nil { 1034 return nil, err 1035 } 1036 deriveTime := time.Now() 1037 1038 response, err := s.Channel.transmitEncrypted(claSCWallet, insSign, signP1PrecomputedHash, signP2OnlyBlock, hash) 1039 if err != nil { 1040 return nil, err 1041 } 1042 sigdata := new(signatureData) 1043 if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil { 1044 return nil, err 1045 } 1046 // Serialize the signature 1047 rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes() 1048 sig := make([]byte, 65) 1049 copy(sig[32-len(rbytes):32], rbytes) 1050 copy(sig[64-len(sbytes):64], sbytes) 1051 1052 // Recover the V value. 1053 sig, err = makeRecoverableSignature(hash, sig, sigdata.PublicKey) 1054 if err != nil { 1055 return nil, err 1056 } 1057 log.Debug("Signed using smartcard", "deriveTime", deriveTime.Sub(startTime), "signingTime", time.Since(deriveTime)) 1058 1059 return sig, nil 1060 } 1061 1062 // confirmPublicKey confirms that the given signature belongs to the specified key. 1063 func confirmPublicKey(sig, pubkey []byte) error { 1064 _, err := makeRecoverableSignature(DerivationSignatureHash[:], sig, pubkey) 1065 return err 1066 } 1067 1068 // makeRecoverableSignature uses a signature and an expected public key to 1069 // recover the v value and produce a recoverable signature. 1070 func makeRecoverableSignature(hash, sig, expectedPubkey []byte) ([]byte, error) { 1071 var libraryError error 1072 for v := 0; v < 2; v++ { 1073 sig[64] = byte(v) 1074 if pubkey, err := crypto.Ecrecover(hash, sig); err == nil { 1075 if bytes.Equal(pubkey, expectedPubkey) { 1076 return sig, nil 1077 } 1078 } else { 1079 libraryError = err 1080 } 1081 } 1082 if libraryError != nil { 1083 return nil, libraryError 1084 } 1085 return nil, ErrPubkeyMismatch 1086 }