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