github.com/aquanetwork/aquachain@v1.7.8/aqua/accounts/usbwallet/ledger.go (about)

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