github.com/nitinawathare/ethereumassignment3@v0.0.0-20211021213010-f07344c2b868/go-ethereum/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  	"sort"
    31  	"strings"
    32  	"sync"
    33  	"time"
    34  
    35  	ethereum "github.com/ethereum/go-ethereum"
    36  	"github.com/ethereum/go-ethereum/accounts"
    37  	"github.com/ethereum/go-ethereum/common"
    38  	"github.com/ethereum/go-ethereum/core/types"
    39  	"github.com/ethereum/go-ethereum/crypto"
    40  	"github.com/ethereum/go-ethereum/crypto/secp256k1"
    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  	deriveNextPath accounts.DerivationPath   // Next derivation path for account auto-discovery
   123  	deriveNextAddr common.Address            // Next derived account address for auto-discovery
   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:
   315  		return fmt.Sprintf("Blocked, waiting for PUK and new PIN"), nil
   316  	case !w.session.verified:
   317  		return fmt.Sprintf("Locked, waiting for PIN (%d attempts left)", status.PinRetryCount), nil
   318  	case !status.Initialized:
   319  		return fmt.Sprintf("Empty, waiting for initialization"), nil
   320  	default:
   321  		return fmt.Sprintf("Online"), nil
   322  	}
   323  }
   324  
   325  // Open initializes access to a wallet instance. It is not meant to unlock or
   326  // decrypt account keys, rather simply to establish a connection to hardware
   327  // wallets and/or to access derivation seeds.
   328  //
   329  // The passphrase parameter may or may not be used by the implementation of a
   330  // particular wallet instance. The reason there is no passwordless open method
   331  // is to strive towards a uniform wallet handling, oblivious to the different
   332  // backend providers.
   333  //
   334  // Please note, if you open a wallet, you must close it to release any allocated
   335  // resources (especially important when working with hardware wallets).
   336  func (w *Wallet) Open(passphrase string) error {
   337  	w.lock.Lock()
   338  	defer w.lock.Unlock()
   339  
   340  	// If the session is already open, bail out
   341  	if w.session.verified {
   342  		return ErrAlreadyOpen
   343  	}
   344  	// If the smart card is not yet paired, attempt to do so either from a previous
   345  	// pairing key or form the supplied PUK code.
   346  	if !w.session.paired() {
   347  		// If a previous pairing exists, only ever try to use that
   348  		if pairing := w.Hub.pairing(w); pairing != nil {
   349  			if err := w.session.authenticate(*pairing); err != nil {
   350  				return fmt.Errorf("failed to authenticate card %x: %s", w.PublicKey[:4], err)
   351  			}
   352  			// Pairing still ok, fall through to PIN checks
   353  		} else {
   354  			// If no passphrase was supplied, request the PUK from the user
   355  			if passphrase == "" {
   356  				return ErrPairingPasswordNeeded
   357  			}
   358  			// Attempt to pair the smart card with the user supplied PUK
   359  			if err := w.pair([]byte(passphrase)); err != nil {
   360  				return err
   361  			}
   362  			// Pairing succeeded, fall through to PIN checks. This will of course fail,
   363  			// but we can't return ErrPINNeeded directly here becase we don't know whether
   364  			// a PIN check or a PIN reset is needed.
   365  			passphrase = ""
   366  		}
   367  	}
   368  	// The smart card was successfully paired, retrieve its status to check whether
   369  	// PIN verification or unblocking is needed.
   370  	status, err := w.session.walletStatus()
   371  	if err != nil {
   372  		return err
   373  	}
   374  	// Request the appropriate next authentication data, or use the one supplied
   375  	switch {
   376  	case passphrase == "" && status.PinRetryCount > 0:
   377  		return ErrPINNeeded
   378  	case passphrase == "":
   379  		return ErrPINUnblockNeeded
   380  	case status.PinRetryCount > 0:
   381  		if err := w.session.verifyPin([]byte(passphrase)); err != nil {
   382  			return err
   383  		}
   384  	default:
   385  		if err := w.session.unblockPin([]byte(passphrase)); err != nil {
   386  			return err
   387  		}
   388  	}
   389  	// Smart card paired and unlocked, initialize and register
   390  	w.deriveReq = make(chan chan struct{})
   391  	w.deriveQuit = make(chan chan error)
   392  
   393  	go w.selfDerive(0)
   394  
   395  	// Notify anyone listening for wallet events that a new device is accessible
   396  	go w.Hub.updateFeed.Send(accounts.WalletEvent{Wallet: w, Kind: accounts.WalletOpened})
   397  
   398  	return nil
   399  }
   400  
   401  // Close stops and closes the wallet, freeing any resources.
   402  func (w *Wallet) Close() error {
   403  	// Ensure the wallet was opened
   404  	w.lock.Lock()
   405  	dQuit := w.deriveQuit
   406  	w.lock.Unlock()
   407  
   408  	// Terminate the self-derivations
   409  	var derr error
   410  	if dQuit != nil {
   411  		errc := make(chan error)
   412  		dQuit <- errc
   413  		derr = <-errc // Save for later, we *must* close the USB
   414  	}
   415  	// Terminate the device connection
   416  	w.lock.Lock()
   417  	defer w.lock.Unlock()
   418  
   419  	w.deriveQuit = nil
   420  	w.deriveReq = nil
   421  
   422  	if err := w.release(); err != nil {
   423  		return err
   424  	}
   425  	return derr
   426  }
   427  
   428  // selfDerive is an account derivation loop that upon request attempts to find
   429  // new non-zero accounts. maxEmpty specifies the number of empty accounts that
   430  // should be derived once an initial empty account has been found.
   431  func (w *Wallet) selfDerive(maxEmpty int) {
   432  	w.log.Debug("Smart card wallet self-derivation started")
   433  	defer w.log.Debug("Smart card wallet self-derivation stopped")
   434  
   435  	// Execute self-derivations until termination or error
   436  	var (
   437  		reqc chan struct{}
   438  		errc chan error
   439  		err  error
   440  	)
   441  	for errc == nil && err == nil {
   442  		// Wait until either derivation or termination is requested
   443  		select {
   444  		case errc = <-w.deriveQuit:
   445  			// Termination requested
   446  			continue
   447  		case reqc = <-w.deriveReq:
   448  			// Account discovery requested
   449  		}
   450  		// Derivation needs a chain and device access, skip if either unavailable
   451  		w.lock.Lock()
   452  		if w.session == nil || w.deriveChain == nil {
   453  			w.lock.Unlock()
   454  			reqc <- struct{}{}
   455  			continue
   456  		}
   457  		pairing := w.Hub.pairing(w)
   458  
   459  		// Device lock obtained, derive the next batch of accounts
   460  		var (
   461  			paths   []accounts.DerivationPath
   462  			nextAcc accounts.Account
   463  
   464  			nextAddr = w.deriveNextAddr
   465  			nextPath = w.deriveNextPath
   466  
   467  			context = context.Background()
   468  		)
   469  		for empty, emptyCount := false, maxEmpty+1; !empty || emptyCount > 0; {
   470  			// Retrieve the next derived Ethereum account
   471  			if nextAddr == (common.Address{}) {
   472  				if nextAcc, err = w.session.derive(nextPath); err != nil {
   473  					w.log.Warn("Smartcard wallet account derivation failed", "err", err)
   474  					break
   475  				}
   476  				nextAddr = nextAcc.Address
   477  			}
   478  			// Check the account's status against the current chain state
   479  			var (
   480  				balance *big.Int
   481  				nonce   uint64
   482  			)
   483  			balance, err = w.deriveChain.BalanceAt(context, nextAddr, nil)
   484  			if err != nil {
   485  				w.log.Warn("Smartcard wallet balance retrieval failed", "err", err)
   486  				break
   487  			}
   488  			nonce, err = w.deriveChain.NonceAt(context, nextAddr, nil)
   489  			if err != nil {
   490  				w.log.Warn("Smartcard wallet nonce retrieval failed", "err", err)
   491  				break
   492  			}
   493  			// If the next account is empty and no more empty accounts are
   494  			// allowed, stop self-derivation. Add the current one nonetheless.
   495  			if balance.Sign() == 0 && nonce == 0 {
   496  				empty = true
   497  				emptyCount--
   498  			}
   499  			// We've just self-derived a new account, start tracking it locally
   500  			path := make(accounts.DerivationPath, len(nextPath))
   501  			copy(path[:], nextPath[:])
   502  			paths = append(paths, path)
   503  
   504  			// Display a log message to the user for new (or previously empty accounts)
   505  			if _, known := pairing.Accounts[nextAddr]; !known || !empty || nextAddr != w.deriveNextAddr {
   506  				w.log.Info("Smartcard wallet discovered new account", "address", nextAddr, "path", path, "balance", balance, "nonce", nonce)
   507  			}
   508  			pairing.Accounts[nextAddr] = path
   509  
   510  			// Fetch the next potential account
   511  			if !empty || emptyCount > 0 {
   512  				nextAddr = common.Address{}
   513  				nextPath[len(nextPath)-1]++
   514  			}
   515  		}
   516  		// If there are new accounts, write them out
   517  		if len(paths) > 0 {
   518  			err = w.Hub.setPairing(w, pairing)
   519  		}
   520  		// Shift the self-derivation forward
   521  		w.deriveNextAddr = nextAddr
   522  		w.deriveNextPath = nextPath
   523  
   524  		// Self derivation complete, release device lock
   525  		w.lock.Unlock()
   526  
   527  		// Notify the user of termination and loop after a bit of time (to avoid trashing)
   528  		reqc <- struct{}{}
   529  		if err == nil {
   530  			select {
   531  			case errc = <-w.deriveQuit:
   532  				// Termination requested, abort
   533  			case <-time.After(selfDeriveThrottling):
   534  				// Waited enough, willing to self-derive again
   535  			}
   536  		}
   537  	}
   538  	// In case of error, wait for termination
   539  	if err != nil {
   540  		w.log.Debug("Smartcard wallet self-derivation failed", "err", err)
   541  		errc = <-w.deriveQuit
   542  	}
   543  	errc <- err
   544  }
   545  
   546  // Accounts retrieves the list of signing accounts the wallet is currently aware
   547  // of. For hierarchical deterministic wallets, the list will not be exhaustive,
   548  // rather only contain the accounts explicitly pinned during account derivation.
   549  func (w *Wallet) Accounts() []accounts.Account {
   550  	// Attempt self-derivation if it's running
   551  	reqc := make(chan struct{}, 1)
   552  	select {
   553  	case w.deriveReq <- reqc:
   554  		// Self-derivation request accepted, wait for it
   555  		<-reqc
   556  	default:
   557  		// Self-derivation offline, throttled or busy, skip
   558  	}
   559  
   560  	w.lock.Lock()
   561  	defer w.lock.Unlock()
   562  
   563  	if pairing := w.Hub.pairing(w); pairing != nil {
   564  		ret := make([]accounts.Account, 0, len(pairing.Accounts))
   565  		for address, path := range pairing.Accounts {
   566  			ret = append(ret, w.makeAccount(address, path))
   567  		}
   568  		sort.Sort(accounts.AccountsByURL(ret))
   569  		return ret
   570  	}
   571  	return nil
   572  }
   573  
   574  func (w *Wallet) makeAccount(address common.Address, path accounts.DerivationPath) accounts.Account {
   575  	return accounts.Account{
   576  		Address: address,
   577  		URL: accounts.URL{
   578  			Scheme: w.Hub.scheme,
   579  			Path:   fmt.Sprintf("%x/%s", w.PublicKey[1:3], path.String()),
   580  		},
   581  	}
   582  }
   583  
   584  // Contains returns whether an account is part of this particular wallet or not.
   585  func (w *Wallet) Contains(account accounts.Account) bool {
   586  	if pairing := w.Hub.pairing(w); pairing != nil {
   587  		_, ok := pairing.Accounts[account.Address]
   588  		return ok
   589  	}
   590  	return false
   591  }
   592  
   593  // Initialize installs a keypair generated from the provided key into the wallet.
   594  func (w *Wallet) Initialize(seed []byte) error {
   595  	go w.selfDerive(0)
   596  	// DO NOT lock at this stage, as the initialize
   597  	// function relies on Status()
   598  	return w.session.initialize(seed)
   599  }
   600  
   601  // Derive attempts to explicitly derive a hierarchical deterministic account at
   602  // the specified derivation path. If requested, the derived account will be added
   603  // to the wallet's tracked account list.
   604  func (w *Wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
   605  	w.lock.Lock()
   606  	defer w.lock.Unlock()
   607  
   608  	account, err := w.session.derive(path)
   609  	if err != nil {
   610  		return accounts.Account{}, err
   611  	}
   612  
   613  	if pin {
   614  		pairing := w.Hub.pairing(w)
   615  		pairing.Accounts[account.Address] = path
   616  		if err := w.Hub.setPairing(w, pairing); err != nil {
   617  			return accounts.Account{}, err
   618  		}
   619  	}
   620  
   621  	return account, nil
   622  }
   623  
   624  // SelfDerive sets a base account derivation path from which the wallet attempts
   625  // to discover non zero accounts and automatically add them to list of tracked
   626  // accounts.
   627  //
   628  // Note, self derivaton will increment the last component of the specified path
   629  // opposed to decending into a child path to allow discovering accounts starting
   630  // from non zero components.
   631  //
   632  // You can disable automatic account discovery by calling SelfDerive with a nil
   633  // chain state reader.
   634  func (w *Wallet) SelfDerive(base accounts.DerivationPath, chain ethereum.ChainStateReader) {
   635  	w.lock.Lock()
   636  	defer w.lock.Unlock()
   637  
   638  	w.deriveNextPath = make(accounts.DerivationPath, len(base))
   639  	copy(w.deriveNextPath[:], base[:])
   640  
   641  	w.deriveNextAddr = common.Address{}
   642  	w.deriveChain = chain
   643  }
   644  
   645  // SignData requests the wallet to sign the hash of the given data.
   646  //
   647  // It looks up the account specified either solely via its address contained within,
   648  // or optionally with the aid of any location metadata from the embedded URL field.
   649  //
   650  // If the wallet requires additional authentication to sign the request (e.g.
   651  // a password to decrypt the account, or a PIN code o verify the transaction),
   652  // an AuthNeededError instance will be returned, containing infos for the user
   653  // about which fields or actions are needed. The user may retry by providing
   654  // the needed details via SignDataWithPassphrase, or by other means (e.g. unlock
   655  // the account in a keystore).
   656  func (w *Wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
   657  	return w.signHash(account, crypto.Keccak256(data))
   658  }
   659  
   660  func (w *Wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
   661  	w.lock.Lock()
   662  	defer w.lock.Unlock()
   663  
   664  	path, err := w.findAccountPath(account)
   665  	if err != nil {
   666  		return nil, err
   667  	}
   668  
   669  	return w.session.sign(path, hash)
   670  }
   671  
   672  // SignTx requests the wallet to sign the given transaction.
   673  //
   674  // It looks up the account specified either solely via its address contained within,
   675  // or optionally with the aid of any location metadata from the embedded URL field.
   676  //
   677  // If the wallet requires additional authentication to sign the request (e.g.
   678  // a password to decrypt the account, or a PIN code o verify the transaction),
   679  // an AuthNeededError instance will be returned, containing infos for the user
   680  // about which fields or actions are needed. The user may retry by providing
   681  // the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
   682  // the account in a keystore).
   683  func (w *Wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   684  	signer := types.NewEIP155Signer(chainID)
   685  	hash := signer.Hash(tx)
   686  	sig, err := w.signHash(account, hash[:])
   687  	if err != nil {
   688  		return nil, err
   689  	}
   690  	return tx.WithSignature(signer, sig)
   691  }
   692  
   693  // SignDataWithPassphrase requests the wallet to sign the given hash with the
   694  // given passphrase as extra authentication information.
   695  //
   696  // It looks up the account specified either solely via its address contained within,
   697  // or optionally with the aid of any location metadata from the embedded URL field.
   698  func (w *Wallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
   699  	return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(data))
   700  }
   701  
   702  func (w *Wallet) signHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) {
   703  	if !w.session.verified {
   704  		if err := w.Open(passphrase); err != nil {
   705  			return nil, err
   706  		}
   707  	}
   708  
   709  	return w.signHash(account, hash)
   710  }
   711  
   712  // SignText requests the wallet to sign the hash of a given piece of data, prefixed
   713  // by the Ethereum prefix scheme
   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  //
   717  // If the wallet requires additional authentication to sign the request (e.g.
   718  // a password to decrypt the account, or a PIN code o verify the transaction),
   719  // an AuthNeededError instance will be returned, containing infos for the user
   720  // about which fields or actions are needed. The user may retry by providing
   721  // the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
   722  // the account in a keystore).
   723  func (w *Wallet) SignText(account accounts.Account, text []byte) ([]byte, error) {
   724  	return w.signHash(account, accounts.TextHash(text))
   725  }
   726  
   727  // SignTextWithPassphrase implements accounts.Wallet, attempting to sign the
   728  // given hash with the given account using passphrase as extra authentication
   729  func (w *Wallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
   730  	return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(accounts.TextHash(text)))
   731  }
   732  
   733  // SignTxWithPassphrase requests the wallet to sign the given transaction, with the
   734  // given passphrase as extra authentication information.
   735  //
   736  // It looks up the account specified either solely via its address contained within,
   737  // or optionally with the aid of any location metadata from the embedded URL field.
   738  func (w *Wallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   739  	if !w.session.verified {
   740  		if err := w.Open(passphrase); err != nil {
   741  			return nil, err
   742  		}
   743  	}
   744  	return w.SignTx(account, tx, chainID)
   745  }
   746  
   747  // findAccountPath returns the derivation path for the provided account.
   748  // It first checks for the address in the list of pinned accounts, and if it is
   749  // not found, attempts to parse the derivation path from the account's URL.
   750  func (w *Wallet) findAccountPath(account accounts.Account) (accounts.DerivationPath, error) {
   751  	pairing := w.Hub.pairing(w)
   752  	if path, ok := pairing.Accounts[account.Address]; ok {
   753  		return path, nil
   754  	}
   755  
   756  	// Look for the path in the URL
   757  	if account.URL.Scheme != w.Hub.scheme {
   758  		return nil, fmt.Errorf("Scheme %s does not match wallet scheme %s", account.URL.Scheme, w.Hub.scheme)
   759  	}
   760  
   761  	parts := strings.SplitN(account.URL.Path, "/", 2)
   762  	if len(parts) != 2 {
   763  		return nil, fmt.Errorf("Invalid URL format: %s", account.URL)
   764  	}
   765  
   766  	if parts[0] != fmt.Sprintf("%x", w.PublicKey[1:3]) {
   767  		return nil, fmt.Errorf("URL %s is not for this wallet", account.URL)
   768  	}
   769  
   770  	return accounts.ParseDerivationPath(parts[1])
   771  }
   772  
   773  // Session represents a secured communication session with the wallet.
   774  type Session struct {
   775  	Wallet   *Wallet               // A handle to the wallet that opened the session
   776  	Channel  *SecureChannelSession // A secure channel for encrypted messages
   777  	verified bool                  // Whether the pin has been verified in this session.
   778  }
   779  
   780  // pair establishes a new pairing over this channel, using the provided secret.
   781  func (s *Session) pair(secret []byte) (smartcardPairing, error) {
   782  	err := s.Channel.Pair(secret)
   783  	if err != nil {
   784  		return smartcardPairing{}, err
   785  	}
   786  
   787  	return smartcardPairing{
   788  		PublicKey:    s.Wallet.PublicKey,
   789  		PairingIndex: s.Channel.PairingIndex,
   790  		PairingKey:   s.Channel.PairingKey,
   791  		Accounts:     make(map[common.Address]accounts.DerivationPath),
   792  	}, nil
   793  }
   794  
   795  // unpair deletes an existing pairing.
   796  func (s *Session) unpair() error {
   797  	if !s.verified {
   798  		return fmt.Errorf("Unpair requires that the PIN be verified")
   799  	}
   800  	return s.Channel.Unpair()
   801  }
   802  
   803  // verifyPin unlocks a wallet with the provided pin.
   804  func (s *Session) verifyPin(pin []byte) error {
   805  	if _, err := s.Channel.transmitEncrypted(claSCWallet, insVerifyPin, 0, 0, pin); err != nil {
   806  		return err
   807  	}
   808  	s.verified = true
   809  	return nil
   810  }
   811  
   812  // unblockPin unblocks a wallet with the provided puk and resets the pin to the
   813  // new one specified.
   814  func (s *Session) unblockPin(pukpin []byte) error {
   815  	if _, err := s.Channel.transmitEncrypted(claSCWallet, insUnblockPin, 0, 0, pukpin); err != nil {
   816  		return err
   817  	}
   818  	s.verified = true
   819  	return nil
   820  }
   821  
   822  // release releases resources associated with the channel.
   823  func (s *Session) release() error {
   824  	return s.Wallet.card.Disconnect(pcsc.LeaveCard)
   825  }
   826  
   827  // paired returns true if a valid pairing exists.
   828  func (s *Session) paired() bool {
   829  	return s.Channel.PairingKey != nil
   830  }
   831  
   832  // authenticate uses an existing pairing to establish a secure channel.
   833  func (s *Session) authenticate(pairing smartcardPairing) error {
   834  	if !bytes.Equal(s.Wallet.PublicKey, pairing.PublicKey) {
   835  		return fmt.Errorf("Cannot pair using another wallet's pairing; %x != %x", s.Wallet.PublicKey, pairing.PublicKey)
   836  	}
   837  	s.Channel.PairingKey = pairing.PairingKey
   838  	s.Channel.PairingIndex = pairing.PairingIndex
   839  	return s.Channel.Open()
   840  }
   841  
   842  // walletStatus describes a smartcard wallet's status information.
   843  type walletStatus struct {
   844  	PinRetryCount int  // Number of remaining PIN retries
   845  	PukRetryCount int  // Number of remaining PUK retries
   846  	Initialized   bool // Whether the card has been initialized with a private key
   847  }
   848  
   849  // walletStatus fetches the wallet's status from the card.
   850  func (s *Session) walletStatus() (*walletStatus, error) {
   851  	response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1WalletStatus, 0, nil)
   852  	if err != nil {
   853  		return nil, err
   854  	}
   855  
   856  	status := new(walletStatus)
   857  	if _, err := asn1.UnmarshalWithParams(response.Data, status, "tag:3"); err != nil {
   858  		return nil, err
   859  	}
   860  	return status, nil
   861  }
   862  
   863  // derivationPath fetches the wallet's current derivation path from the card.
   864  func (s *Session) derivationPath() (accounts.DerivationPath, error) {
   865  	response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1Path, 0, nil)
   866  	if err != nil {
   867  		return nil, err
   868  	}
   869  	buf := bytes.NewReader(response.Data)
   870  	path := make(accounts.DerivationPath, len(response.Data)/4)
   871  	return path, binary.Read(buf, binary.BigEndian, &path)
   872  }
   873  
   874  // initializeData contains data needed to initialize the smartcard wallet.
   875  type initializeData struct {
   876  	PublicKey  []byte `asn1:"tag:0"`
   877  	PrivateKey []byte `asn1:"tag:1"`
   878  	ChainCode  []byte `asn1:"tag:2"`
   879  }
   880  
   881  // initialize initializes the card with new key data.
   882  func (s *Session) initialize(seed []byte) error {
   883  	// Check that the wallet isn't currently initialized,
   884  	// otherwise the key would be overwritten.
   885  	status, err := s.Wallet.Status()
   886  	if err != nil {
   887  		return err
   888  	}
   889  	if status == "Online" {
   890  		return fmt.Errorf("card is already initialized, cowardly refusing to proceed")
   891  	}
   892  
   893  	s.Wallet.lock.Lock()
   894  	defer s.Wallet.lock.Unlock()
   895  
   896  	// HMAC the seed to produce the private key and chain code
   897  	mac := hmac.New(sha512.New, []byte("Bitcoin seed"))
   898  	mac.Write(seed)
   899  	seed = mac.Sum(nil)
   900  
   901  	key, err := crypto.ToECDSA(seed[:32])
   902  	if err != nil {
   903  		return err
   904  	}
   905  
   906  	id := initializeData{}
   907  	id.PublicKey = crypto.FromECDSAPub(&key.PublicKey)
   908  	id.PrivateKey = seed[:32]
   909  	id.ChainCode = seed[32:]
   910  	data, err := asn1.Marshal(id)
   911  	if err != nil {
   912  		return err
   913  	}
   914  
   915  	// Nasty hack to force the top-level struct tag to be context-specific
   916  	data[0] = 0xA1
   917  
   918  	_, err = s.Channel.transmitEncrypted(claSCWallet, insLoadKey, 0x02, 0, data)
   919  	return err
   920  }
   921  
   922  // derive derives a new HD key path on the card.
   923  func (s *Session) derive(path accounts.DerivationPath) (accounts.Account, error) {
   924  	startingPoint, path, err := derivationpath.Decode(path.String())
   925  	if err != nil {
   926  		return accounts.Account{}, err
   927  	}
   928  
   929  	var p1 uint8
   930  	switch startingPoint {
   931  	case derivationpath.StartingPointMaster:
   932  		p1 = P1DeriveKeyFromMaster
   933  	case derivationpath.StartingPointParent:
   934  		p1 = P1DeriveKeyFromParent
   935  	case derivationpath.StartingPointCurrent:
   936  		p1 = P1DeriveKeyFromCurrent
   937  	default:
   938  		return accounts.Account{}, fmt.Errorf("invalid startingPoint %d", startingPoint)
   939  	}
   940  
   941  	data := new(bytes.Buffer)
   942  	for _, segment := range path {
   943  		if err := binary.Write(data, binary.BigEndian, segment); err != nil {
   944  			return accounts.Account{}, err
   945  		}
   946  	}
   947  
   948  	_, err = s.Channel.transmitEncrypted(claSCWallet, insDeriveKey, p1, 0, data.Bytes())
   949  	if err != nil {
   950  		return accounts.Account{}, err
   951  	}
   952  
   953  	response, err := s.Channel.transmitEncrypted(claSCWallet, insSign, 0, 0, DerivationSignatureHash[:])
   954  	if err != nil {
   955  		return accounts.Account{}, err
   956  	}
   957  
   958  	sigdata := new(signatureData)
   959  	if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil {
   960  		return accounts.Account{}, err
   961  	}
   962  	rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes()
   963  	sig := make([]byte, 65)
   964  	copy(sig[32-len(rbytes):32], rbytes)
   965  	copy(sig[64-len(sbytes):64], sbytes)
   966  
   967  	pubkey, err := determinePublicKey(sig, sigdata.PublicKey)
   968  	if err != nil {
   969  		return accounts.Account{}, err
   970  	}
   971  
   972  	pub, err := crypto.UnmarshalPubkey(pubkey)
   973  	if err != nil {
   974  		return accounts.Account{}, err
   975  	}
   976  	return s.Wallet.makeAccount(crypto.PubkeyToAddress(*pub), path), nil
   977  }
   978  
   979  // keyExport contains information on an exported keypair.
   980  type keyExport struct {
   981  	PublicKey  []byte `asn1:"tag:0"`
   982  	PrivateKey []byte `asn1:"tag:1,optional"`
   983  }
   984  
   985  // publicKey returns the public key for the current derivation path.
   986  func (s *Session) publicKey() ([]byte, error) {
   987  	response, err := s.Channel.transmitEncrypted(claSCWallet, insExportKey, exportP1Any, exportP2Pubkey, nil)
   988  	if err != nil {
   989  		return nil, err
   990  	}
   991  	keys := new(keyExport)
   992  	if _, err := asn1.UnmarshalWithParams(response.Data, keys, "tag:1"); err != nil {
   993  		return nil, err
   994  	}
   995  	return keys.PublicKey, nil
   996  }
   997  
   998  // signatureData contains information on a signature - the signature itself and
   999  // the corresponding public key.
  1000  type signatureData struct {
  1001  	PublicKey []byte `asn1:"tag:0"`
  1002  	Signature struct {
  1003  		R *big.Int
  1004  		S *big.Int
  1005  	}
  1006  }
  1007  
  1008  // sign asks the card to sign a message, and returns a valid signature after
  1009  // recovering the v value.
  1010  func (s *Session) sign(path accounts.DerivationPath, hash []byte) ([]byte, error) {
  1011  	startTime := time.Now()
  1012  	_, err := s.derive(path)
  1013  	if err != nil {
  1014  		return nil, err
  1015  	}
  1016  	deriveTime := time.Now()
  1017  
  1018  	response, err := s.Channel.transmitEncrypted(claSCWallet, insSign, signP1PrecomputedHash, signP2OnlyBlock, hash)
  1019  	if err != nil {
  1020  		return nil, err
  1021  	}
  1022  	sigdata := new(signatureData)
  1023  	if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil {
  1024  		return nil, err
  1025  	}
  1026  	// Serialize the signature
  1027  	rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes()
  1028  	sig := make([]byte, 65)
  1029  	copy(sig[32-len(rbytes):32], rbytes)
  1030  	copy(sig[64-len(sbytes):64], sbytes)
  1031  
  1032  	// Recover the V value.
  1033  	sig, err = makeRecoverableSignature(hash, sig, sigdata.PublicKey)
  1034  	if err != nil {
  1035  		return nil, err
  1036  	}
  1037  	log.Debug("Signed using smartcard", "deriveTime", deriveTime.Sub(startTime), "signingTime", time.Since(deriveTime))
  1038  
  1039  	return sig, nil
  1040  }
  1041  
  1042  // determinePublicKey uses a signature and the X component of a public key to
  1043  // recover the entire public key.
  1044  func determinePublicKey(sig, pubkeyX []byte) ([]byte, error) {
  1045  	for v := 0; v < 2; v++ {
  1046  		sig[64] = byte(v)
  1047  		pubkey, err := crypto.Ecrecover(DerivationSignatureHash[:], sig)
  1048  		if err == nil {
  1049  			if bytes.Equal(pubkey, pubkeyX) {
  1050  				return pubkey, nil
  1051  			}
  1052  		} else if v == 1 || err != secp256k1.ErrRecoverFailed {
  1053  			return nil, err
  1054  		}
  1055  	}
  1056  	return nil, ErrPubkeyMismatch
  1057  }
  1058  
  1059  // makeRecoverableSignature uses a signature and an expected public key to
  1060  // recover the v value and produce a recoverable signature.
  1061  func makeRecoverableSignature(hash, sig, expectedPubkey []byte) ([]byte, error) {
  1062  	for v := 0; v < 2; v++ {
  1063  		sig[64] = byte(v)
  1064  		pubkey, err := crypto.Ecrecover(hash, sig)
  1065  		if err == nil {
  1066  			if bytes.Equal(pubkey, expectedPubkey) {
  1067  				return sig, nil
  1068  			}
  1069  		} else if v == 1 || err != secp256k1.ErrRecoverFailed {
  1070  			return nil, err
  1071  		}
  1072  	}
  1073  	return nil, ErrPubkeyMismatch
  1074  }