github.com/luckypickle/go-ethereum-vet@v1.14.2/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://raw.githubusercontent.com/LedgerHQ/blue-app-eth/master/doc/ethapp.asc
    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/luckypickle/go-ethereum-vet/accounts"
    32  	"github.com/luckypickle/go-ethereum-vet/common"
    33  	"github.com/luckypickle/go-ethereum-vet/common/hexutil"
    34  	"github.com/luckypickle/go-ethereum-vet/core/types"
    35  	"github.com/luckypickle/go-ethereum-vet/log"
    36  	"github.com/luckypickle/go-ethereum-vet/rlp"
    37  )
    38  
    39  // ledgerOpcode is an enumeration encoding the supported Ledger opcodes.
    40  type ledgerOpcode byte
    41  
    42  // ledgerParam1 is an enumeration encoding the supported Ledger parameters for
    43  // specific opcodes. The same parameter values may be reused between opcodes.
    44  type ledgerParam1 byte
    45  
    46  // ledgerParam2 is an enumeration encoding the supported Ledger parameters for
    47  // specific opcodes. The same parameter values may be reused between opcodes.
    48  type ledgerParam2 byte
    49  
    50  const (
    51  	ledgerOpRetrieveAddress  ledgerOpcode = 0x02 // Returns the public key and Ethereum address for a given BIP 32 path
    52  	ledgerOpSignTransaction  ledgerOpcode = 0x04 // Signs an Ethereum transaction after having the user validate the parameters
    53  	ledgerOpGetConfiguration ledgerOpcode = 0x06 // Returns specific wallet application configuration
    54  
    55  	ledgerP1DirectlyFetchAddress    ledgerParam1 = 0x00 // Return address directly from the wallet
    56  	ledgerP1InitTransactionData     ledgerParam1 = 0x00 // First transaction data block for signing
    57  	ledgerP1ContTransactionData     ledgerParam1 = 0x80 // Subsequent transaction data block for signing
    58  	ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address
    59  )
    60  
    61  // errLedgerReplyInvalidHeader is the error message returned by a Ledger data exchange
    62  // if the device replies with a mismatching header. This usually means the device
    63  // is in browser mode.
    64  var errLedgerReplyInvalidHeader = errors.New("ledger: invalid reply header")
    65  
    66  // errLedgerInvalidVersionReply is the error message returned by a Ledger version retrieval
    67  // when a response does arrive, but it does not contain the expected data.
    68  var errLedgerInvalidVersionReply = errors.New("ledger: invalid version reply")
    69  
    70  // ledgerDriver implements the communication with a Ledger hardware wallet.
    71  type ledgerDriver struct {
    72  	device  io.ReadWriter // USB device connection to communicate through
    73  	version [3]byte       // Current version of the Ledger firmware (zero if app is offline)
    74  	browser bool          // Flag whether the Ledger is in browser mode (reply channel mismatch)
    75  	failure error         // Any failure that would make the device unusable
    76  	log     log.Logger    // Contextual logger to tag the ledger with its id
    77  }
    78  
    79  // newLedgerDriver creates a new instance of a Ledger USB protocol driver.
    80  func newLedgerDriver(logger log.Logger) driver {
    81  	return &ledgerDriver{
    82  		log: logger,
    83  	}
    84  }
    85  
    86  // Status implements usbwallet.driver, returning various states the Ledger can
    87  // currently be in.
    88  func (w *ledgerDriver) Status() (string, error) {
    89  	if w.failure != nil {
    90  		return fmt.Sprintf("Failed: %v", w.failure), w.failure
    91  	}
    92  	if w.browser {
    93  		return "Ethereum app in browser mode", w.failure
    94  	}
    95  	if w.offline() {
    96  		return "Ethereum app offline", w.failure
    97  	}
    98  	return fmt.Sprintf("Ethereum app v%d.%d.%d online", w.version[0], w.version[1], w.version[2]), w.failure
    99  }
   100  
   101  // offline returns whether the wallet and the Ethereum app is offline or not.
   102  //
   103  // The method assumes that the state lock is held!
   104  func (w *ledgerDriver) offline() bool {
   105  	return w.version == [3]byte{0, 0, 0}
   106  }
   107  
   108  // Open implements usbwallet.driver, attempting to initialize the connection to the
   109  // Ledger hardware wallet. The Ledger does not require a user passphrase, so that
   110  // parameter is silently discarded.
   111  func (w *ledgerDriver) Open(device io.ReadWriter, passphrase string) error {
   112  	w.device, w.failure = device, nil
   113  
   114  	_, err := w.ledgerDerive(accounts.DefaultBaseDerivationPath)
   115  	if err != nil {
   116  		// Ethereum app is not running or in browser mode, nothing more to do, return
   117  		if err == errLedgerReplyInvalidHeader {
   118  			w.browser = true
   119  		}
   120  		return nil
   121  	}
   122  	// Try to resolve the Ethereum app's version, will fail prior to v1.0.2
   123  	if w.version, err = w.ledgerVersion(); err != nil {
   124  		w.version = [3]byte{1, 0, 0} // Assume worst case, can't verify if v1.0.0 or v1.0.1
   125  	}
   126  	return nil
   127  }
   128  
   129  // Close implements usbwallet.driver, cleaning up and metadata maintained within
   130  // the Ledger driver.
   131  func (w *ledgerDriver) Close() error {
   132  	w.browser, w.version = false, [3]byte{}
   133  	return nil
   134  }
   135  
   136  // Heartbeat implements usbwallet.driver, performing a sanity check against the
   137  // Ledger to see if it's still online.
   138  func (w *ledgerDriver) Heartbeat() error {
   139  	if _, err := w.ledgerVersion(); err != nil && err != errLedgerInvalidVersionReply {
   140  		w.failure = err
   141  		return err
   142  	}
   143  	return nil
   144  }
   145  
   146  // Derive implements usbwallet.driver, sending a derivation request to the Ledger
   147  // and returning the Ethereum address located on that derivation path.
   148  func (w *ledgerDriver) Derive(path accounts.DerivationPath) (common.Address, error) {
   149  	return w.ledgerDerive(path)
   150  }
   151  
   152  // SignTx implements usbwallet.driver, sending the transaction to the Ledger and
   153  // waiting for the user to confirm or deny the transaction.
   154  //
   155  // Note, if the version of the Ethereum application running on the Ledger wallet is
   156  // too old to sign EIP-155 transactions, but such is requested nonetheless, an error
   157  // will be returned opposed to silently signing in Homestead mode.
   158  func (w *ledgerDriver) SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
   159  	// If the Ethereum app doesn't run, abort
   160  	if w.offline() {
   161  		return common.Address{}, nil, accounts.ErrWalletClosed
   162  	}
   163  	// Ensure the wallet is capable of signing the given transaction
   164  	if chainID != nil && w.version[0] <= 1 && w.version[1] <= 0 && w.version[2] <= 2 {
   165  		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])
   166  	}
   167  	// All infos gathered and metadata checks out, request signing
   168  	return w.ledgerSign(path, tx, chainID)
   169  }
   170  
   171  // ledgerVersion retrieves the current version of the Ethereum wallet app running
   172  // on the Ledger wallet.
   173  //
   174  // The version retrieval protocol is defined as follows:
   175  //
   176  //	CLA | INS | P1 | P2 | Lc | Le
   177  //	----+-----+----+----+----+---
   178  //	 E0 | 06  | 00 | 00 | 00 | 04
   179  //
   180  // With no input data, and the output data being:
   181  //
   182  //	Description                                        | Length
   183  //	---------------------------------------------------+--------
   184  //	Flags 01: arbitrary data signature enabled by user | 1 byte
   185  //	Application major version                          | 1 byte
   186  //	Application minor version                          | 1 byte
   187  //	Application patch version                          | 1 byte
   188  func (w *ledgerDriver) ledgerVersion() ([3]byte, error) {
   189  	// Send the request and wait for the response
   190  	reply, err := w.ledgerExchange(ledgerOpGetConfiguration, 0, 0, nil)
   191  	if err != nil {
   192  		return [3]byte{}, err
   193  	}
   194  	if len(reply) != 4 {
   195  		return [3]byte{}, errLedgerInvalidVersionReply
   196  	}
   197  	// Cache the version for future reference
   198  	var version [3]byte
   199  	copy(version[:], reply[1:])
   200  	return version, nil
   201  }
   202  
   203  // ledgerDerive retrieves the currently active Ethereum address from a Ledger
   204  // wallet at the specified derivation path.
   205  //
   206  // The address derivation protocol is defined as follows:
   207  //
   208  //	CLA | INS | P1 | P2 | Lc  | Le
   209  //	----+-----+----+----+-----+---
   210  //	 E0 | 02  | 00 return address
   211  //	            01 display address and confirm before returning
   212  //	               | 00: do not return the chain code
   213  //	               | 01: return the chain code
   214  //	                    | var | 00
   215  //
   216  // Where the input data is:
   217  //
   218  //	Description                                      | Length
   219  //	-------------------------------------------------+--------
   220  //	Number of BIP 32 derivations to perform (max 10) | 1 byte
   221  //	First derivation index (big endian)              | 4 bytes
   222  //	...                                              | 4 bytes
   223  //	Last derivation index (big endian)               | 4 bytes
   224  //
   225  // And the output data is:
   226  //
   227  //	Description             | Length
   228  //	------------------------+-------------------
   229  //	Public Key length       | 1 byte
   230  //	Uncompressed Public Key | arbitrary
   231  //	Ethereum address length | 1 byte
   232  //	Ethereum address        | 40 bytes hex ascii
   233  //	Chain code if requested | 32 bytes
   234  func (w *ledgerDriver) ledgerDerive(derivationPath []uint32) (common.Address, error) {
   235  	// Flatten the derivation path into the Ledger request
   236  	path := make([]byte, 1+4*len(derivationPath))
   237  	path[0] = byte(len(derivationPath))
   238  	for i, component := range derivationPath {
   239  		binary.BigEndian.PutUint32(path[1+4*i:], component)
   240  	}
   241  	// Send the request and wait for the response
   242  	reply, err := w.ledgerExchange(ledgerOpRetrieveAddress, ledgerP1DirectlyFetchAddress, ledgerP2DiscardAddressChainCode, path)
   243  	if err != nil {
   244  		return common.Address{}, err
   245  	}
   246  	// Discard the public key, we don't need that for now
   247  	if len(reply) < 1 || len(reply) < 1+int(reply[0]) {
   248  		return common.Address{}, errors.New("reply lacks public key entry")
   249  	}
   250  	reply = reply[1+int(reply[0]):]
   251  
   252  	// Extract the Ethereum hex address string
   253  	if len(reply) < 1 || len(reply) < 1+int(reply[0]) {
   254  		return common.Address{}, errors.New("reply lacks address entry")
   255  	}
   256  	hexstr := reply[1 : 1+int(reply[0])]
   257  
   258  	// Decode the hex sting into an Ethereum address and return
   259  	var address common.Address
   260  	hex.Decode(address[:], hexstr)
   261  	return address, nil
   262  }
   263  
   264  // ledgerSign sends the transaction to the Ledger wallet, and waits for the user
   265  // to confirm or deny the transaction.
   266  //
   267  // The transaction signing protocol is defined as follows:
   268  //
   269  //	CLA | INS | P1 | P2 | Lc  | Le
   270  //	----+-----+----+----+-----+---
   271  //	 E0 | 04  | 00: first transaction data block
   272  //	            80: subsequent transaction data block
   273  //	               | 00 | variable | variable
   274  //
   275  // Where the input for the first transaction block (first 255 bytes) is:
   276  //
   277  //	Description                                      | Length
   278  //	-------------------------------------------------+----------
   279  //	Number of BIP 32 derivations to perform (max 10) | 1 byte
   280  //	First derivation index (big endian)              | 4 bytes
   281  //	...                                              | 4 bytes
   282  //	Last derivation index (big endian)               | 4 bytes
   283  //	RLP transaction chunk                            | arbitrary
   284  //
   285  // And the input for subsequent transaction blocks (first 255 bytes) are:
   286  //
   287  //	Description           | Length
   288  //	----------------------+----------
   289  //	RLP transaction chunk | arbitrary
   290  //
   291  // And the output data is:
   292  //
   293  //	Description | Length
   294  //	------------+---------
   295  //	signature V | 1 byte
   296  //	signature R | 32 bytes
   297  //	signature S | 32 bytes
   298  func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
   299  	// Flatten the derivation path into the Ledger request
   300  	path := make([]byte, 1+4*len(derivationPath))
   301  	path[0] = byte(len(derivationPath))
   302  	for i, component := range derivationPath {
   303  		binary.BigEndian.PutUint32(path[1+4*i:], component)
   304  	}
   305  	// Create the transaction RLP based on whether legacy or EIP155 signing was requested
   306  	var (
   307  		txrlp []byte
   308  		err   error
   309  	)
   310  	if chainID == nil {
   311  		if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data()}); err != nil {
   312  			return common.Address{}, nil, err
   313  		}
   314  	} else {
   315  		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 {
   316  			return common.Address{}, nil, err
   317  		}
   318  	}
   319  	payload := append(path, txrlp...)
   320  
   321  	// Send the request and wait for the response
   322  	var (
   323  		op    = ledgerP1InitTransactionData
   324  		reply []byte
   325  	)
   326  	for len(payload) > 0 {
   327  		// Calculate the size of the next data chunk
   328  		chunk := 255
   329  		if chunk > len(payload) {
   330  			chunk = len(payload)
   331  		}
   332  		// Send the chunk over, ensuring it's processed correctly
   333  		reply, err = w.ledgerExchange(ledgerOpSignTransaction, op, 0, payload[:chunk])
   334  		if err != nil {
   335  			return common.Address{}, nil, err
   336  		}
   337  		// Shift the payload and ensure subsequent chunks are marked as such
   338  		payload = payload[chunk:]
   339  		op = ledgerP1ContTransactionData
   340  	}
   341  	// Extract the Ethereum signature and do a sanity validation
   342  	if len(reply) != 65 {
   343  		return common.Address{}, nil, errors.New("reply lacks signature")
   344  	}
   345  	signature := append(reply[1:], reply[0])
   346  
   347  	// Create the correct signer and signature transform based on the chain ID
   348  	var signer types.Signer
   349  	if chainID == nil {
   350  		signer = new(types.HomesteadSigner)
   351  	} else {
   352  		signer = types.NewEIP155Signer(chainID)
   353  		signature[64] = signature[64] - byte(chainID.Uint64()*2+35)
   354  	}
   355  	signed, err := tx.WithSignature(signer, signature)
   356  	if err != nil {
   357  		return common.Address{}, nil, err
   358  	}
   359  	sender, err := types.Sender(signer, signed)
   360  	if err != nil {
   361  		return common.Address{}, nil, err
   362  	}
   363  	return sender, signed, nil
   364  }
   365  
   366  // ledgerExchange performs a data exchange with the Ledger wallet, sending it a
   367  // message and retrieving the response.
   368  //
   369  // The common transport header is defined as follows:
   370  //
   371  //	Description                           | Length
   372  //	--------------------------------------+----------
   373  //	Communication channel ID (big endian) | 2 bytes
   374  //	Command tag                           | 1 byte
   375  //	Packet sequence index (big endian)    | 2 bytes
   376  //	Payload                               | arbitrary
   377  //
   378  // The Communication channel ID allows commands multiplexing over the same
   379  // physical link. It is not used for the time being, and should be set to 0101
   380  // to avoid compatibility issues with implementations ignoring a leading 00 byte.
   381  //
   382  // The Command tag describes the message content. Use TAG_APDU (0x05) for standard
   383  // APDU payloads, or TAG_PING (0x02) for a simple link test.
   384  //
   385  // The Packet sequence index describes the current sequence for fragmented payloads.
   386  // The first fragment index is 0x00.
   387  //
   388  // APDU Command payloads are encoded as follows:
   389  //
   390  //	Description              | Length
   391  //	-----------------------------------
   392  //	APDU length (big endian) | 2 bytes
   393  //	APDU CLA                 | 1 byte
   394  //	APDU INS                 | 1 byte
   395  //	APDU P1                  | 1 byte
   396  //	APDU P2                  | 1 byte
   397  //	APDU length              | 1 byte
   398  //	Optional APDU data       | arbitrary
   399  func (w *ledgerDriver) ledgerExchange(opcode ledgerOpcode, p1 ledgerParam1, p2 ledgerParam2, data []byte) ([]byte, error) {
   400  	// Construct the message payload, possibly split into multiple chunks
   401  	apdu := make([]byte, 2, 7+len(data))
   402  
   403  	binary.BigEndian.PutUint16(apdu, uint16(5+len(data)))
   404  	apdu = append(apdu, []byte{0xe0, byte(opcode), byte(p1), byte(p2), byte(len(data))}...)
   405  	apdu = append(apdu, data...)
   406  
   407  	// Stream all the chunks to the device
   408  	header := []byte{0x01, 0x01, 0x05, 0x00, 0x00} // Channel ID and command tag appended
   409  	chunk := make([]byte, 64)
   410  	space := len(chunk) - len(header)
   411  
   412  	for i := 0; len(apdu) > 0; i++ {
   413  		// Construct the new message to stream
   414  		chunk = append(chunk[:0], header...)
   415  		binary.BigEndian.PutUint16(chunk[3:], uint16(i))
   416  
   417  		if len(apdu) > space {
   418  			chunk = append(chunk, apdu[:space]...)
   419  			apdu = apdu[space:]
   420  		} else {
   421  			chunk = append(chunk, apdu...)
   422  			apdu = nil
   423  		}
   424  		// Send over to the device
   425  		w.log.Trace("Data chunk sent to the Ledger", "chunk", hexutil.Bytes(chunk))
   426  		if _, err := w.device.Write(chunk); err != nil {
   427  			return nil, err
   428  		}
   429  	}
   430  	// Stream the reply back from the wallet in 64 byte chunks
   431  	var reply []byte
   432  	chunk = chunk[:64] // Yeah, we surely have enough space
   433  	for {
   434  		// Read the next chunk from the Ledger wallet
   435  		if _, err := io.ReadFull(w.device, chunk); err != nil {
   436  			return nil, err
   437  		}
   438  		w.log.Trace("Data chunk received from the Ledger", "chunk", hexutil.Bytes(chunk))
   439  
   440  		// Make sure the transport header matches
   441  		if chunk[0] != 0x01 || chunk[1] != 0x01 || chunk[2] != 0x05 {
   442  			return nil, errLedgerReplyInvalidHeader
   443  		}
   444  		// If it's the first chunk, retrieve the total message length
   445  		var payload []byte
   446  
   447  		if chunk[3] == 0x00 && chunk[4] == 0x00 {
   448  			reply = make([]byte, 0, int(binary.BigEndian.Uint16(chunk[5:7])))
   449  			payload = chunk[7:]
   450  		} else {
   451  			payload = chunk[5:]
   452  		}
   453  		// Append to the reply and stop when filled up
   454  		if left := cap(reply) - len(reply); left > len(payload) {
   455  			reply = append(reply, payload...)
   456  		} else {
   457  			reply = append(reply, payload[:left]...)
   458  			break
   459  		}
   460  	}
   461  	return reply[:len(reply)-2], nil
   462  }