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