trezor.go 12 KB

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