github.com/ApeGame/aac@v1.9.7/accounts/usbwallet/trezor.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 Trezor hardware
    18  // wallets. The wire protocol spec can be found on the SatoshiLabs website:
    19  // https://doc.satoshilabs.com/trezor-tech/api-protobuf.html
    20  
    21  package usbwallet
    22  
    23  import (
    24  	"encoding/binary"
    25  	"errors"
    26  	"fmt"
    27  	"io"
    28  	"math/big"
    29  
    30  	"github.com/ethereum/go-ethereum/accounts"
    31  	"github.com/ethereum/go-ethereum/accounts/usbwallet/trezor"
    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/log"
    36  	"github.com/golang/protobuf/proto"
    37  )
    38  
    39  // ErrTrezorPINNeeded is returned if opening the trezor requires a PIN code. In
    40  // this case, the calling application should display a pinpad and send back the
    41  // encoded passphrase.
    42  var ErrTrezorPINNeeded = errors.New("trezor: pin needed")
    43  
    44  // ErrTrezorPassphraseNeeded is returned if opening the trezor requires a passphrase
    45  var ErrTrezorPassphraseNeeded = errors.New("trezor: passphrase needed")
    46  
    47  // errTrezorReplyInvalidHeader is the error message returned by a Trezor data exchange
    48  // if the device replies with a mismatching header. This usually means the device
    49  // is in browser mode.
    50  var errTrezorReplyInvalidHeader = errors.New("trezor: invalid reply header")
    51  
    52  // trezorDriver implements the communication with a Trezor hardware wallet.
    53  type trezorDriver struct {
    54  	device         io.ReadWriter // USB device connection to communicate through
    55  	version        [3]uint32     // Current version of the Trezor firmware
    56  	label          string        // Current textual label of the Trezor device
    57  	pinwait        bool          // Flags whether the device is waiting for PIN entry
    58  	passphrasewait bool          // Flags whether the device is waiting for passphrase entry
    59  	failure        error         // Any failure that would make the device unusable
    60  	log            log.Logger    // Contextual logger to tag the trezor with its id
    61  }
    62  
    63  // newTrezorDriver creates a new instance of a Trezor USB protocol driver.
    64  func newTrezorDriver(logger log.Logger) driver {
    65  	return &trezorDriver{
    66  		log: logger,
    67  	}
    68  }
    69  
    70  // Status implements accounts.Wallet, always whether the Trezor is opened, closed
    71  // or whether the Ethereum app was not started on it.
    72  func (w *trezorDriver) Status() (string, error) {
    73  	if w.failure != nil {
    74  		return fmt.Sprintf("Failed: %v", w.failure), w.failure
    75  	}
    76  	if w.device == nil {
    77  		return "Closed", w.failure
    78  	}
    79  	if w.pinwait {
    80  		return fmt.Sprintf("Trezor v%d.%d.%d '%s' waiting for PIN", w.version[0], w.version[1], w.version[2], w.label), w.failure
    81  	}
    82  	return fmt.Sprintf("Trezor v%d.%d.%d '%s' online", w.version[0], w.version[1], w.version[2], w.label), w.failure
    83  }
    84  
    85  // Open implements usbwallet.driver, attempting to initialize the connection to
    86  // the Trezor hardware wallet. Initializing the Trezor is a two or three phase operation:
    87  //  * The first phase is to initialize the connection and read the wallet's
    88  //    features. This phase is invoked if the provided passphrase is empty. The
    89  //    device will display the pinpad as a result and will return an appropriate
    90  //    error to notify the user that a second open phase is needed.
    91  //  * The second phase is to unlock access to the Trezor, which is done by the
    92  //    user actually providing a passphrase mapping a keyboard keypad to the pin
    93  //    number of the user (shuffled according to the pinpad displayed).
    94  //  * If needed the device will ask for passphrase which will require calling
    95  //    open again with the actual passphrase (3rd phase)
    96  func (w *trezorDriver) Open(device io.ReadWriter, passphrase string) error {
    97  	w.device, w.failure = device, nil
    98  
    99  	// If phase 1 is requested, init the connection and wait for user callback
   100  	if passphrase == "" && !w.passphrasewait {
   101  		// If we're already waiting for a PIN entry, insta-return
   102  		if w.pinwait {
   103  			return ErrTrezorPINNeeded
   104  		}
   105  		// Initialize a connection to the device
   106  		features := new(trezor.Features)
   107  		if _, err := w.trezorExchange(&trezor.Initialize{}, features); err != nil {
   108  			return err
   109  		}
   110  		w.version = [3]uint32{features.GetMajorVersion(), features.GetMinorVersion(), features.GetPatchVersion()}
   111  		w.label = features.GetLabel()
   112  
   113  		// Do a manual ping, forcing the device to ask for its PIN and Passphrase
   114  		askPin := true
   115  		askPassphrase := true
   116  		res, err := w.trezorExchange(&trezor.Ping{PinProtection: &askPin, PassphraseProtection: &askPassphrase}, new(trezor.PinMatrixRequest), new(trezor.PassphraseRequest), new(trezor.Success))
   117  		if err != nil {
   118  			return err
   119  		}
   120  		// Only return the PIN request if the device wasn't unlocked until now
   121  		switch res {
   122  		case 0:
   123  			w.pinwait = true
   124  			return ErrTrezorPINNeeded
   125  		case 1:
   126  			w.pinwait = false
   127  			w.passphrasewait = true
   128  			return ErrTrezorPassphraseNeeded
   129  		case 2:
   130  			return nil // responded with trezor.Success
   131  		}
   132  	}
   133  	// Phase 2 requested with actual PIN entry
   134  	if w.pinwait {
   135  		w.pinwait = false
   136  		res, err := w.trezorExchange(&trezor.PinMatrixAck{Pin: &passphrase}, new(trezor.Success), new(trezor.PassphraseRequest))
   137  		if err != nil {
   138  			w.failure = err
   139  			return err
   140  		}
   141  		if res == 1 {
   142  			w.passphrasewait = true
   143  			return ErrTrezorPassphraseNeeded
   144  		}
   145  	} else if w.passphrasewait {
   146  		w.passphrasewait = false
   147  		if _, err := w.trezorExchange(&trezor.PassphraseAck{Passphrase: &passphrase}, new(trezor.Success)); err != nil {
   148  			w.failure = err
   149  			return err
   150  		}
   151  	}
   152  
   153  	return nil
   154  }
   155  
   156  // Close implements usbwallet.driver, cleaning up and metadata maintained within
   157  // the Trezor driver.
   158  func (w *trezorDriver) Close() error {
   159  	w.version, w.label, w.pinwait = [3]uint32{}, "", false
   160  	return nil
   161  }
   162  
   163  // Heartbeat implements usbwallet.driver, performing a sanity check against the
   164  // Trezor to see if it's still online.
   165  func (w *trezorDriver) Heartbeat() error {
   166  	if _, err := w.trezorExchange(&trezor.Ping{}, new(trezor.Success)); err != nil {
   167  		w.failure = err
   168  		return err
   169  	}
   170  	return nil
   171  }
   172  
   173  // Derive implements usbwallet.driver, sending a derivation request to the Trezor
   174  // and returning the Ethereum address located on that derivation path.
   175  func (w *trezorDriver) Derive(path accounts.DerivationPath) (common.Address, error) {
   176  	return w.trezorDerive(path)
   177  }
   178  
   179  // SignTx implements usbwallet.driver, sending the transaction to the Trezor and
   180  // waiting for the user to confirm or deny the transaction.
   181  func (w *trezorDriver) SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
   182  	if w.device == nil {
   183  		return common.Address{}, nil, accounts.ErrWalletClosed
   184  	}
   185  	return w.trezorSign(path, tx, chainID)
   186  }
   187  
   188  // trezorDerive sends a derivation request to the Trezor device and returns the
   189  // Ethereum address located on that path.
   190  func (w *trezorDriver) trezorDerive(derivationPath []uint32) (common.Address, error) {
   191  	address := new(trezor.EthereumAddress)
   192  	if _, err := w.trezorExchange(&trezor.EthereumGetAddress{AddressN: derivationPath}, address); err != nil {
   193  		return common.Address{}, err
   194  	}
   195  	if addr := address.GetAddressBin(); len(addr) > 0 { // Older firmwares use binary fomats
   196  		return common.BytesToAddress(addr), nil
   197  	}
   198  	if addr := address.GetAddressHex(); len(addr) > 0 { // Newer firmwares use hexadecimal fomats
   199  		return common.HexToAddress(addr), nil
   200  	}
   201  	return common.Address{}, errors.New("missing derived address")
   202  }
   203  
   204  // trezorSign sends the transaction to the Trezor wallet, and waits for the user
   205  // to confirm or deny the transaction.
   206  func (w *trezorDriver) trezorSign(derivationPath []uint32, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
   207  	// Create the transaction initiation message
   208  	data := tx.Data()
   209  	length := uint32(len(data))
   210  
   211  	request := &trezor.EthereumSignTx{
   212  		AddressN:   derivationPath,
   213  		Nonce:      new(big.Int).SetUint64(tx.Nonce()).Bytes(),
   214  		GasPrice:   tx.GasPrice().Bytes(),
   215  		GasLimit:   new(big.Int).SetUint64(tx.Gas()).Bytes(),
   216  		Value:      tx.Value().Bytes(),
   217  		DataLength: &length,
   218  	}
   219  	if to := tx.To(); to != nil {
   220  		// Non contract deploy, set recipient explicitly
   221  		hex := to.Hex()
   222  		request.ToHex = &hex     // Newer firmwares (old will ignore)
   223  		request.ToBin = (*to)[:] // Older firmwares (new will ignore)
   224  	}
   225  	if length > 1024 { // Send the data chunked if that was requested
   226  		request.DataInitialChunk, data = data[:1024], data[1024:]
   227  	} else {
   228  		request.DataInitialChunk, data = data, nil
   229  	}
   230  	if chainID != nil { // EIP-155 transaction, set chain ID explicitly (only 32 bit is supported!?)
   231  		id := uint32(chainID.Int64())
   232  		request.ChainId = &id
   233  	}
   234  	// Send the initiation message and stream content until a signature is returned
   235  	response := new(trezor.EthereumTxRequest)
   236  	if _, err := w.trezorExchange(request, response); err != nil {
   237  		return common.Address{}, nil, err
   238  	}
   239  	for response.DataLength != nil && int(*response.DataLength) <= len(data) {
   240  		chunk := data[:*response.DataLength]
   241  		data = data[*response.DataLength:]
   242  
   243  		if _, err := w.trezorExchange(&trezor.EthereumTxAck{DataChunk: chunk}, response); err != nil {
   244  			return common.Address{}, nil, err
   245  		}
   246  	}
   247  	// Extract the Ethereum signature and do a sanity validation
   248  	if len(response.GetSignatureR()) == 0 || len(response.GetSignatureS()) == 0 || response.GetSignatureV() == 0 {
   249  		return common.Address{}, nil, errors.New("reply lacks signature")
   250  	}
   251  	signature := append(append(response.GetSignatureR(), response.GetSignatureS()...), byte(response.GetSignatureV()))
   252  
   253  	// Create the correct signer and signature transform based on the chain ID
   254  	var signer types.Signer
   255  	if chainID == nil {
   256  		signer = new(types.HomesteadSigner)
   257  	} else {
   258  		signer = types.NewEIP155Signer(chainID)
   259  		signature[64] -= byte(chainID.Uint64()*2 + 35)
   260  	}
   261  	// Inject the final signature into the transaction and sanity check the sender
   262  	signed, err := tx.WithSignature(signer, signature)
   263  	if err != nil {
   264  		return common.Address{}, nil, err
   265  	}
   266  	sender, err := types.Sender(signer, signed)
   267  	if err != nil {
   268  		return common.Address{}, nil, err
   269  	}
   270  	return sender, signed, nil
   271  }
   272  
   273  // trezorExchange performs a data exchange with the Trezor wallet, sending it a
   274  // message and retrieving the response. If multiple responses are possible, the
   275  // method will also return the index of the destination object used.
   276  func (w *trezorDriver) trezorExchange(req proto.Message, results ...proto.Message) (int, error) {
   277  	// Construct the original message payload to chunk up
   278  	data, err := proto.Marshal(req)
   279  	if err != nil {
   280  		return 0, err
   281  	}
   282  	payload := make([]byte, 8+len(data))
   283  	copy(payload, []byte{0x23, 0x23})
   284  	binary.BigEndian.PutUint16(payload[2:], trezor.Type(req))
   285  	binary.BigEndian.PutUint32(payload[4:], uint32(len(data)))
   286  	copy(payload[8:], data)
   287  
   288  	// Stream all the chunks to the device
   289  	chunk := make([]byte, 64)
   290  	chunk[0] = 0x3f // Report ID magic number
   291  
   292  	for len(payload) > 0 {
   293  		// Construct the new message to stream, padding with zeroes if needed
   294  		if len(payload) > 63 {
   295  			copy(chunk[1:], payload[:63])
   296  			payload = payload[63:]
   297  		} else {
   298  			copy(chunk[1:], payload)
   299  			copy(chunk[1+len(payload):], make([]byte, 63-len(payload)))
   300  			payload = nil
   301  		}
   302  		// Send over to the device
   303  		w.log.Trace("Data chunk sent to the Trezor", "chunk", hexutil.Bytes(chunk))
   304  		if _, err := w.device.Write(chunk); err != nil {
   305  			return 0, err
   306  		}
   307  	}
   308  	// Stream the reply back from the wallet in 64 byte chunks
   309  	var (
   310  		kind  uint16
   311  		reply []byte
   312  	)
   313  	for {
   314  		// Read the next chunk from the Trezor wallet
   315  		if _, err := io.ReadFull(w.device, chunk); err != nil {
   316  			return 0, err
   317  		}
   318  		w.log.Trace("Data chunk received from the Trezor", "chunk", hexutil.Bytes(chunk))
   319  
   320  		// Make sure the transport header matches
   321  		if chunk[0] != 0x3f || (len(reply) == 0 && (chunk[1] != 0x23 || chunk[2] != 0x23)) {
   322  			return 0, errTrezorReplyInvalidHeader
   323  		}
   324  		// If it's the first chunk, retrieve the reply message type and total message length
   325  		var payload []byte
   326  
   327  		if len(reply) == 0 {
   328  			kind = binary.BigEndian.Uint16(chunk[3:5])
   329  			reply = make([]byte, 0, int(binary.BigEndian.Uint32(chunk[5:9])))
   330  			payload = chunk[9:]
   331  		} else {
   332  			payload = chunk[1:]
   333  		}
   334  		// Append to the reply and stop when filled up
   335  		if left := cap(reply) - len(reply); left > len(payload) {
   336  			reply = append(reply, payload...)
   337  		} else {
   338  			reply = append(reply, payload[:left]...)
   339  			break
   340  		}
   341  	}
   342  	// Try to parse the reply into the requested reply message
   343  	if kind == uint16(trezor.MessageType_MessageType_Failure) {
   344  		// Trezor returned a failure, extract and return the message
   345  		failure := new(trezor.Failure)
   346  		if err := proto.Unmarshal(reply, failure); err != nil {
   347  			return 0, err
   348  		}
   349  		return 0, errors.New("trezor: " + failure.GetMessage())
   350  	}
   351  	if kind == uint16(trezor.MessageType_MessageType_ButtonRequest) {
   352  		// Trezor is waiting for user confirmation, ack and wait for the next message
   353  		return w.trezorExchange(&trezor.ButtonAck{}, results...)
   354  	}
   355  	for i, res := range results {
   356  		if trezor.Type(res) == kind {
   357  			return i, proto.Unmarshal(reply, res)
   358  		}
   359  	}
   360  	expected := make([]string, len(results))
   361  	for i, res := range results {
   362  		expected[i] = trezor.Name(trezor.Type(res))
   363  	}
   364  	return 0, fmt.Errorf("trezor: expected reply types %s, got %s", expected, trezor.Name(kind))
   365  }