github.com/ethereum/go-ethereum@v1.16.1/accounts/usbwallet/ledger.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // This file contains the implementation for interacting with the Ledger hardware
    18  // wallets. The wire protocol spec can be found in the Ledger Blue GitHub repo:
    19  // https://github.com/LedgerHQ/app-ethereum/blob/develop/doc/ethapp.adoc
    20  
    21  package usbwallet
    22  
    23  import (
    24  	"encoding/binary"
    25  	"encoding/hex"
    26  	"errors"
    27  	"fmt"
    28  	"io"
    29  	"math/big"
    30  
    31  	"github.com/ethereum/go-ethereum/accounts"
    32  	"github.com/ethereum/go-ethereum/common"
    33  	"github.com/ethereum/go-ethereum/common/hexutil"
    34  	"github.com/ethereum/go-ethereum/core/types"
    35  	"github.com/ethereum/go-ethereum/crypto"
    36  	"github.com/ethereum/go-ethereum/log"
    37  	"github.com/ethereum/go-ethereum/rlp"
    38  )
    39  
    40  // ledgerOpcode is an enumeration encoding the supported Ledger opcodes.
    41  type ledgerOpcode byte
    42  
    43  // ledgerParam1 is an enumeration encoding the supported Ledger parameters for
    44  // specific opcodes. The same parameter values may be reused between opcodes.
    45  type ledgerParam1 byte
    46  
    47  // ledgerParam2 is an enumeration encoding the supported Ledger parameters for
    48  // specific opcodes. The same parameter values may be reused between opcodes.
    49  type ledgerParam2 byte
    50  
    51  const (
    52  	ledgerOpRetrieveAddress  ledgerOpcode = 0x02 // Returns the public key and Ethereum address for a given BIP 32 path
    53  	ledgerOpSignTransaction  ledgerOpcode = 0x04 // Signs an Ethereum transaction after having the user validate the parameters
    54  	ledgerOpGetConfiguration ledgerOpcode = 0x06 // Returns specific wallet application configuration
    55  	ledgerOpSignTypedMessage ledgerOpcode = 0x0c // Signs an Ethereum message following the EIP 712 specification
    56  
    57  	ledgerP1DirectlyFetchAddress    ledgerParam1 = 0x00 // Return address directly from the wallet
    58  	ledgerP1InitTypedMessageData    ledgerParam1 = 0x00 // First chunk of Typed Message data
    59  	ledgerP1InitTransactionData     ledgerParam1 = 0x00 // First transaction data block for signing
    60  	ledgerP1ContTransactionData     ledgerParam1 = 0x80 // Subsequent transaction data block for signing
    61  	ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address
    62  
    63  	ledgerEip155Size int = 3 // Size of the EIP-155 chain_id,r,s in unsigned transactions
    64  )
    65  
    66  // errLedgerReplyInvalidHeader is the error message returned by a Ledger data exchange
    67  // if the device replies with a mismatching header. This usually means the device
    68  // is in browser mode.
    69  var errLedgerReplyInvalidHeader = errors.New("ledger: invalid reply header")
    70  
    71  // errLedgerInvalidVersionReply is the error message returned by a Ledger version retrieval
    72  // when a response does arrive, but it does not contain the expected data.
    73  var errLedgerInvalidVersionReply = errors.New("ledger: invalid version reply")
    74  
    75  // ledgerDriver implements the communication with a Ledger hardware wallet.
    76  type ledgerDriver struct {
    77  	device  io.ReadWriter // USB device connection to communicate through
    78  	version [3]byte       // Current version of the Ledger firmware (zero if app is offline)
    79  	browser bool          // Flag whether the Ledger is in browser mode (reply channel mismatch)
    80  	failure error         // Any failure that would make the device unusable
    81  	log     log.Logger    // Contextual logger to tag the ledger with its id
    82  }
    83  
    84  // newLedgerDriver creates a new instance of a Ledger USB protocol driver.
    85  func newLedgerDriver(logger log.Logger) driver {
    86  	return &ledgerDriver{
    87  		log: logger,
    88  	}
    89  }
    90  
    91  // Status implements usbwallet.driver, returning various states the Ledger can
    92  // currently be in.
    93  func (w *ledgerDriver) Status() (string, error) {
    94  	if w.failure != nil {
    95  		return fmt.Sprintf("Failed: %v", w.failure), w.failure
    96  	}
    97  	if w.browser {
    98  		return "Ethereum app in browser mode", w.failure
    99  	}
   100  	if w.offline() {
   101  		return "Ethereum app offline", w.failure
   102  	}
   103  	return fmt.Sprintf("Ethereum app v%d.%d.%d online", w.version[0], w.version[1], w.version[2]), w.failure
   104  }
   105  
   106  // offline returns whether the wallet and the Ethereum app is offline or not.
   107  //
   108  // The method assumes that the state lock is held!
   109  func (w *ledgerDriver) offline() bool {
   110  	return w.version == [3]byte{0, 0, 0}
   111  }
   112  
   113  // Open implements usbwallet.driver, attempting to initialize the connection to the
   114  // Ledger hardware wallet. The Ledger does not require a user passphrase, so that
   115  // parameter is silently discarded.
   116  func (w *ledgerDriver) Open(device io.ReadWriter, passphrase string) error {
   117  	w.device, w.failure = device, nil
   118  
   119  	_, err := w.ledgerDerive(accounts.DefaultBaseDerivationPath)
   120  	if err != nil {
   121  		// Ethereum app is not running or in browser mode, nothing more to do, return
   122  		if err == errLedgerReplyInvalidHeader {
   123  			w.browser = true
   124  		}
   125  		return nil
   126  	}
   127  	// Try to resolve the Ethereum app's version, will fail prior to v1.0.2
   128  	if w.version, err = w.ledgerVersion(); err != nil {
   129  		w.version = [3]byte{1, 0, 0} // Assume worst case, can't verify if v1.0.0 or v1.0.1
   130  	}
   131  	return nil
   132  }
   133  
   134  // Close implements usbwallet.driver, cleaning up and metadata maintained within
   135  // the Ledger driver.
   136  func (w *ledgerDriver) Close() error {
   137  	w.browser, w.version = false, [3]byte{}
   138  	return nil
   139  }
   140  
   141  // Heartbeat implements usbwallet.driver, performing a sanity check against the
   142  // Ledger to see if it's still online.
   143  func (w *ledgerDriver) Heartbeat() error {
   144  	if _, err := w.ledgerVersion(); err != nil && err != errLedgerInvalidVersionReply {
   145  		w.failure = err
   146  		return err
   147  	}
   148  	return nil
   149  }
   150  
   151  // Derive implements usbwallet.driver, sending a derivation request to the Ledger
   152  // and returning the Ethereum address located on that derivation path.
   153  func (w *ledgerDriver) Derive(path accounts.DerivationPath) (common.Address, error) {
   154  	return w.ledgerDerive(path)
   155  }
   156  
   157  // SignTx implements usbwallet.driver, sending the transaction to the Ledger and
   158  // waiting for the user to confirm or deny the transaction.
   159  //
   160  // Note, if the version of the Ethereum application running on the Ledger wallet is
   161  // too old to sign EIP-155 transactions, but such is requested nonetheless, an error
   162  // will be returned opposed to silently signing in Homestead mode.
   163  func (w *ledgerDriver) SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
   164  	// If the Ethereum app doesn't run, abort
   165  	if w.offline() {
   166  		return common.Address{}, nil, accounts.ErrWalletClosed
   167  	}
   168  	// Ensure the wallet is capable of signing the given transaction
   169  	if chainID != nil && w.version[0] <= 1 && w.version[1] <= 0 && w.version[2] <= 2 {
   170  		//lint:ignore ST1005 brand name displayed on the console
   171  		return common.Address{}, nil, fmt.Errorf("Ledger v%d.%d.%d doesn't support signing this transaction, please update to v1.0.3 at least", w.version[0], w.version[1], w.version[2])
   172  	}
   173  	// All infos gathered and metadata checks out, request signing
   174  	return w.ledgerSign(path, tx, chainID)
   175  }
   176  
   177  // SignTypedMessage implements usbwallet.driver, sending the message to the Ledger and
   178  // waiting for the user to sign or deny the transaction.
   179  //
   180  // Note: this was introduced in the ledger 1.5.0 firmware
   181  func (w *ledgerDriver) SignTypedMessage(path accounts.DerivationPath, domainHash []byte, messageHash []byte) ([]byte, error) {
   182  	// If the Ethereum app doesn't run, abort
   183  	if w.offline() {
   184  		return nil, accounts.ErrWalletClosed
   185  	}
   186  	// Ensure the wallet is capable of signing the given transaction
   187  	if w.version[0] < 1 && w.version[1] < 5 {
   188  		//lint:ignore ST1005 brand name displayed on the console
   189  		return nil, fmt.Errorf("Ledger version >= 1.5.0 required for EIP-712 signing (found version v%d.%d.%d)", w.version[0], w.version[1], w.version[2])
   190  	}
   191  	// All infos gathered and metadata checks out, request signing
   192  	return w.ledgerSignTypedMessage(path, domainHash, messageHash)
   193  }
   194  
   195  // ledgerVersion retrieves the current version of the Ethereum wallet app running
   196  // on the Ledger wallet.
   197  //
   198  // The version retrieval protocol is defined as follows:
   199  //
   200  //	CLA | INS | P1 | P2 | Lc | Le
   201  //	----+-----+----+----+----+---
   202  //	 E0 | 06  | 00 | 00 | 00 | 04
   203  //
   204  // With no input data, and the output data being:
   205  //
   206  //	Description                                        | Length
   207  //	---------------------------------------------------+--------
   208  //	Flags 01: arbitrary data signature enabled by user | 1 byte
   209  //	Application major version                          | 1 byte
   210  //	Application minor version                          | 1 byte
   211  //	Application patch version                          | 1 byte
   212  func (w *ledgerDriver) ledgerVersion() ([3]byte, error) {
   213  	// Send the request and wait for the response
   214  	reply, err := w.ledgerExchange(ledgerOpGetConfiguration, 0, 0, nil)
   215  	if err != nil {
   216  		return [3]byte{}, err
   217  	}
   218  	if len(reply) != 4 {
   219  		return [3]byte{}, errLedgerInvalidVersionReply
   220  	}
   221  	// Cache the version for future reference
   222  	var version [3]byte
   223  	copy(version[:], reply[1:])
   224  	return version, nil
   225  }
   226  
   227  // ledgerDerive retrieves the currently active Ethereum address from a Ledger
   228  // wallet at the specified derivation path.
   229  //
   230  // The address derivation protocol is defined as follows:
   231  //
   232  //	CLA | INS | P1 | P2 | Lc  | Le
   233  //	----+-----+----+----+-----+---
   234  //	 E0 | 02  | 00 return address
   235  //	            01 display address and confirm before returning
   236  //	               | 00: do not return the chain code
   237  //	               | 01: return the chain code
   238  //	                    | var | 00
   239  //
   240  // Where the input data is:
   241  //
   242  //	Description                                      | Length
   243  //	-------------------------------------------------+--------
   244  //	Number of BIP 32 derivations to perform (max 10) | 1 byte
   245  //	First derivation index (big endian)              | 4 bytes
   246  //	...                                              | 4 bytes
   247  //	Last derivation index (big endian)               | 4 bytes
   248  //
   249  // And the output data is:
   250  //
   251  //	Description             | Length
   252  //	------------------------+-------------------
   253  //	Public Key length       | 1 byte
   254  //	Uncompressed Public Key | arbitrary
   255  //	Ethereum address length | 1 byte
   256  //	Ethereum address        | 40 bytes hex ascii
   257  //	Chain code if requested | 32 bytes
   258  func (w *ledgerDriver) ledgerDerive(derivationPath []uint32) (common.Address, error) {
   259  	// Flatten the derivation path into the Ledger request
   260  	path := make([]byte, 1+4*len(derivationPath))
   261  	path[0] = byte(len(derivationPath))
   262  	for i, component := range derivationPath {
   263  		binary.BigEndian.PutUint32(path[1+4*i:], component)
   264  	}
   265  	// Send the request and wait for the response
   266  	reply, err := w.ledgerExchange(ledgerOpRetrieveAddress, ledgerP1DirectlyFetchAddress, ledgerP2DiscardAddressChainCode, path)
   267  	if err != nil {
   268  		return common.Address{}, err
   269  	}
   270  	// Discard the public key, we don't need that for now
   271  	if len(reply) < 1 || len(reply) < 1+int(reply[0]) {
   272  		return common.Address{}, errors.New("reply lacks public key entry")
   273  	}
   274  	reply = reply[1+int(reply[0]):]
   275  
   276  	// Extract the Ethereum hex address string
   277  	if len(reply) < 1 || len(reply) < 1+int(reply[0]) {
   278  		return common.Address{}, errors.New("reply lacks address entry")
   279  	}
   280  	hexstr := reply[1 : 1+int(reply[0])]
   281  
   282  	// Decode the hex string into an Ethereum address and return
   283  	var address common.Address
   284  	if _, err = hex.Decode(address[:], hexstr); err != nil {
   285  		return common.Address{}, err
   286  	}
   287  	return address, nil
   288  }
   289  
   290  // ledgerSign sends the transaction to the Ledger wallet, and waits for the user
   291  // to confirm or deny the transaction.
   292  //
   293  // The transaction signing protocol is defined as follows:
   294  //
   295  //	CLA | INS | P1 | P2 | Lc  | Le
   296  //	----+-----+----+----+-----+---
   297  //	 E0 | 04  | 00: first transaction data block
   298  //	            80: subsequent transaction data block
   299  //	               | 00 | variable | variable
   300  //
   301  // Where the input for the first transaction block (first 255 bytes) is:
   302  //
   303  //	Description                                      | Length
   304  //	-------------------------------------------------+----------
   305  //	Number of BIP 32 derivations to perform (max 10) | 1 byte
   306  //	First derivation index (big endian)              | 4 bytes
   307  //	...                                              | 4 bytes
   308  //	Last derivation index (big endian)               | 4 bytes
   309  //	RLP transaction chunk                            | arbitrary
   310  //
   311  // And the input for subsequent transaction blocks (first 255 bytes) are:
   312  //
   313  //	Description           | Length
   314  //	----------------------+----------
   315  //	RLP transaction chunk | arbitrary
   316  //
   317  // And the output data is:
   318  //
   319  //	Description | Length
   320  //	------------+---------
   321  //	signature V | 1 byte
   322  //	signature R | 32 bytes
   323  //	signature S | 32 bytes
   324  func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
   325  	// Flatten the derivation path into the Ledger request
   326  	path := make([]byte, 1+4*len(derivationPath))
   327  	path[0] = byte(len(derivationPath))
   328  	for i, component := range derivationPath {
   329  		binary.BigEndian.PutUint32(path[1+4*i:], component)
   330  	}
   331  	// Create the transaction RLP based on whether legacy or EIP155 signing was requested
   332  	var (
   333  		txrlp []byte
   334  		err   error
   335  	)
   336  	if chainID == nil {
   337  		if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data()}); err != nil {
   338  			return common.Address{}, nil, err
   339  		}
   340  	} else {
   341  		if tx.Type() == types.DynamicFeeTxType {
   342  			if txrlp, err = rlp.EncodeToBytes([]interface{}{chainID, tx.Nonce(), tx.GasTipCap(), tx.GasFeeCap(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), tx.AccessList()}); err != nil {
   343  				return common.Address{}, nil, err
   344  			}
   345  			// append type to transaction
   346  			txrlp = append([]byte{tx.Type()}, txrlp...)
   347  		} else if tx.Type() == types.AccessListTxType {
   348  			if txrlp, err = rlp.EncodeToBytes([]interface{}{chainID, tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), tx.AccessList()}); err != nil {
   349  				return common.Address{}, nil, err
   350  			}
   351  			// append type to transaction
   352  			txrlp = append([]byte{tx.Type()}, txrlp...)
   353  		} else if tx.Type() == types.LegacyTxType {
   354  			if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), chainID, big.NewInt(0), big.NewInt(0)}); err != nil {
   355  				return common.Address{}, nil, err
   356  			}
   357  		}
   358  	}
   359  	payload := append(path, txrlp...)
   360  
   361  	// Send the request and wait for the response
   362  	var (
   363  		op    = ledgerP1InitTransactionData
   364  		reply []byte
   365  	)
   366  
   367  	// Chunk size selection to mitigate an underlying RLP deserialization issue on the ledger app.
   368  	// https://github.com/LedgerHQ/app-ethereum/issues/409
   369  	chunk := 255
   370  	if tx.Type() == types.LegacyTxType {
   371  		for ; len(payload)%chunk <= ledgerEip155Size; chunk-- {
   372  		}
   373  	}
   374  
   375  	for len(payload) > 0 {
   376  		// Calculate the size of the next data chunk
   377  		if chunk > len(payload) {
   378  			chunk = len(payload)
   379  		}
   380  		// Send the chunk over, ensuring it's processed correctly
   381  		reply, err = w.ledgerExchange(ledgerOpSignTransaction, op, 0, payload[:chunk])
   382  		if err != nil {
   383  			return common.Address{}, nil, err
   384  		}
   385  		// Shift the payload and ensure subsequent chunks are marked as such
   386  		payload = payload[chunk:]
   387  		op = ledgerP1ContTransactionData
   388  	}
   389  	// Extract the Ethereum signature and do a sanity validation
   390  	if len(reply) != crypto.SignatureLength {
   391  		return common.Address{}, nil, errors.New("reply lacks signature")
   392  	}
   393  	signature := append(reply[1:], reply[0])
   394  
   395  	// Create the correct signer and signature transform based on the chain ID
   396  	var signer types.Signer
   397  	if chainID == nil {
   398  		signer = new(types.HomesteadSigner)
   399  	} else {
   400  		signer = types.LatestSignerForChainID(chainID)
   401  		// For non-legacy transactions, V is 0 or 1, no need to subtract here.
   402  		if tx.Type() == types.LegacyTxType {
   403  			signature[64] -= byte(chainID.Uint64()*2 + 35)
   404  		}
   405  	}
   406  	signed, err := tx.WithSignature(signer, signature)
   407  	if err != nil {
   408  		return common.Address{}, nil, err
   409  	}
   410  	sender, err := types.Sender(signer, signed)
   411  	if err != nil {
   412  		return common.Address{}, nil, err
   413  	}
   414  	return sender, signed, nil
   415  }
   416  
   417  // ledgerSignTypedMessage sends the transaction to the Ledger wallet, and waits for the user
   418  // to confirm or deny the transaction.
   419  //
   420  // The signing protocol is defined as follows:
   421  //
   422  //	CLA | INS | P1 | P2                          | Lc  | Le
   423  //	----+-----+----+-----------------------------+-----+---
   424  //	 E0 | 0C  | 00 | implementation version : 00 | variable | variable
   425  //
   426  // Where the input is:
   427  //
   428  //	Description                                      | Length
   429  //	-------------------------------------------------+----------
   430  //	Number of BIP 32 derivations to perform (max 10) | 1 byte
   431  //	First derivation index (big endian)              | 4 bytes
   432  //	...                                              | 4 bytes
   433  //	Last derivation index (big endian)               | 4 bytes
   434  //	domain hash                                      | 32 bytes
   435  //	message hash                                     | 32 bytes
   436  //
   437  // And the output data is:
   438  //
   439  //	Description | Length
   440  //	------------+---------
   441  //	signature V | 1 byte
   442  //	signature R | 32 bytes
   443  //	signature S | 32 bytes
   444  func (w *ledgerDriver) ledgerSignTypedMessage(derivationPath []uint32, domainHash []byte, messageHash []byte) ([]byte, error) {
   445  	// Flatten the derivation path into the Ledger request
   446  	path := make([]byte, 1+4*len(derivationPath))
   447  	path[0] = byte(len(derivationPath))
   448  	for i, component := range derivationPath {
   449  		binary.BigEndian.PutUint32(path[1+4*i:], component)
   450  	}
   451  	// Create the 712 message
   452  	payload := append(path, domainHash...)
   453  	payload = append(payload, messageHash...)
   454  
   455  	// Send the request and wait for the response
   456  	var (
   457  		op    = ledgerP1InitTypedMessageData
   458  		reply []byte
   459  		err   error
   460  	)
   461  
   462  	// Send the message over, ensuring it's processed correctly
   463  	reply, err = w.ledgerExchange(ledgerOpSignTypedMessage, op, 0, payload)
   464  
   465  	if err != nil {
   466  		return nil, err
   467  	}
   468  
   469  	// Extract the Ethereum signature and do a sanity validation
   470  	if len(reply) != crypto.SignatureLength {
   471  		return nil, errors.New("reply lacks signature")
   472  	}
   473  	signature := append(reply[1:], reply[0])
   474  	return signature, nil
   475  }
   476  
   477  // ledgerExchange performs a data exchange with the Ledger wallet, sending it a
   478  // message and retrieving the response.
   479  //
   480  // The common transport header is defined as follows:
   481  //
   482  //	Description                           | Length
   483  //	--------------------------------------+----------
   484  //	Communication channel ID (big endian) | 2 bytes
   485  //	Command tag                           | 1 byte
   486  //	Packet sequence index (big endian)    | 2 bytes
   487  //	Payload                               | arbitrary
   488  //
   489  // The Communication channel ID allows commands multiplexing over the same
   490  // physical link. It is not used for the time being, and should be set to 0101
   491  // to avoid compatibility issues with implementations ignoring a leading 00 byte.
   492  //
   493  // The Command tag describes the message content. Use TAG_APDU (0x05) for standard
   494  // APDU payloads, or TAG_PING (0x02) for a simple link test.
   495  //
   496  // The Packet sequence index describes the current sequence for fragmented payloads.
   497  // The first fragment index is 0x00.
   498  //
   499  // APDU Command payloads are encoded as follows:
   500  //
   501  //	Description              | Length
   502  //	-----------------------------------
   503  //	APDU length (big endian) | 2 bytes
   504  //	APDU CLA                 | 1 byte
   505  //	APDU INS                 | 1 byte
   506  //	APDU P1                  | 1 byte
   507  //	APDU P2                  | 1 byte
   508  //	APDU length              | 1 byte
   509  //	Optional APDU data       | arbitrary
   510  func (w *ledgerDriver) ledgerExchange(opcode ledgerOpcode, p1 ledgerParam1, p2 ledgerParam2, data []byte) ([]byte, error) {
   511  	// Construct the message payload, possibly split into multiple chunks
   512  	apdu := make([]byte, 2, 7+len(data))
   513  
   514  	binary.BigEndian.PutUint16(apdu, uint16(5+len(data)))
   515  	apdu = append(apdu, []byte{0xe0, byte(opcode), byte(p1), byte(p2), byte(len(data))}...)
   516  	apdu = append(apdu, data...)
   517  
   518  	// Stream all the chunks to the device
   519  	header := []byte{0x01, 0x01, 0x05, 0x00, 0x00} // Channel ID and command tag appended
   520  	chunk := make([]byte, 64)
   521  	space := len(chunk) - len(header)
   522  
   523  	for i := 0; len(apdu) > 0; i++ {
   524  		// Construct the new message to stream
   525  		chunk = append(chunk[:0], header...)
   526  		binary.BigEndian.PutUint16(chunk[3:], uint16(i))
   527  
   528  		if len(apdu) > space {
   529  			chunk = append(chunk, apdu[:space]...)
   530  			apdu = apdu[space:]
   531  		} else {
   532  			chunk = append(chunk, apdu...)
   533  			apdu = nil
   534  		}
   535  		// Send over to the device
   536  		w.log.Trace("Data chunk sent to the Ledger", "chunk", hexutil.Bytes(chunk))
   537  		if _, err := w.device.Write(chunk); err != nil {
   538  			return nil, err
   539  		}
   540  	}
   541  	// Stream the reply back from the wallet in 64 byte chunks
   542  	var reply []byte
   543  	chunk = chunk[:64] // Yeah, we surely have enough space
   544  	for {
   545  		// Read the next chunk from the Ledger wallet
   546  		if _, err := io.ReadFull(w.device, chunk); err != nil {
   547  			return nil, err
   548  		}
   549  		w.log.Trace("Data chunk received from the Ledger", "chunk", hexutil.Bytes(chunk))
   550  
   551  		// Make sure the transport header matches
   552  		if chunk[0] != 0x01 || chunk[1] != 0x01 || chunk[2] != 0x05 {
   553  			return nil, errLedgerReplyInvalidHeader
   554  		}
   555  		// If it's the first chunk, retrieve the total message length
   556  		var payload []byte
   557  
   558  		if chunk[3] == 0x00 && chunk[4] == 0x00 {
   559  			reply = make([]byte, 0, int(binary.BigEndian.Uint16(chunk[5:7])))
   560  			payload = chunk[7:]
   561  		} else {
   562  			payload = chunk[5:]
   563  		}
   564  		// Append to the reply and stop when filled up
   565  		if left := cap(reply) - len(reply); left > len(payload) {
   566  			reply = append(reply, payload...)
   567  		} else {
   568  			reply = append(reply, payload[:left]...)
   569  			break
   570  		}
   571  	}
   572  	return reply[:len(reply)-2], nil
   573  }