Repository navigation
Expand file tree
/
Copy pathtrezor_data.go
More file actions
280 lines (272 loc) · 9.76 KB
/
Copy pathtrezor_data.go
File metadata and controls
280 lines (272 loc) · 9.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package usbwallet
import (
"encoding/binary"
"errors"
"fmt"
"math/big"
"reflect"
"github.com/base/usbwallet/trezor"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/signer/core/apitypes"
"google.golang.org/protobuf/proto"
)
func (w *trezorDriver) SignText(path accounts.DerivationPath, text []byte) ([]byte, error) {
if w.device == nil {
return nil, accounts.ErrWalletClosed
}
response := new(trezor.EthereumMessageSignature)
_, err := w.trezorExchange(&trezor.EthereumSignMessage{
AddressN: path,
Message: text,
}, response)
if err != nil {
return nil, err
}
return response.Signature, nil
}
func (w *trezorDriver) SignedTypedData(path accounts.DerivationPath, data apitypes.TypedData) ([]byte, error) {
if w.device == nil {
return nil, accounts.ErrWalletClosed
}
_, hashes, err := apitypes.TypedDataAndHash(data)
if err != nil {
return nil, fmt.Errorf("trezor: error hashing typed data: %w", err)
}
domainHash, messageHash := hashes[2:34], hashes[34:66]
if w.version[0] == 1 {
// legacy Trezor devices don't support typed data; fallback to hash signing:
return w.SignTypedHash(path, []byte(domainHash), []byte(messageHash))
}
if w.version[0] == 2 && (w.version[1] < 9 || (w.version[1] == 9 && w.version[2] == 0)) {
// ShowMessageHash was introduced in Trezor firmware v2.9.1
return nil, fmt.Errorf("trezor: typed data signing requires firmware v2.9.1 or newer")
}
signature := new(trezor.EthereumTypedDataSignature)
structRequest := new(trezor.EthereumTypedDataStructRequest)
valueRequest := new(trezor.EthereumTypedDataValueRequest)
var req proto.Message = &trezor.EthereumSignTypedData{
AddressN: path,
PrimaryType: &data.PrimaryType,
ShowMessageHash: []byte(messageHash),
}
nestedArray := false
for {
n, err := w.trezorExchange(req, signature, structRequest, valueRequest)
if err != nil {
var trezorFailure *TrezorFailure
if nestedArray && errors.As(err, &trezorFailure) &&
trezorFailure.Code != nil && *trezorFailure.Code == trezor.Failure_Failure_FirmwareError {
return nil, fmt.Errorf("trezor: nested arrays are not supported by this firmware version: %w", err)
}
return nil, err
}
nestedArray = false
switch n {
case 0:
// No additional data needed, return the signature
return signature.Signature, nil
case 1:
fields := data.Types[structRequest.GetName()]
if len(fields) == 0 {
return nil, fmt.Errorf("trezor: no fields for struct %s", structRequest.GetName())
}
ack := &trezor.EthereumTypedDataStructAck{
Members: make([]*trezor.EthereumTypedDataStructAck_EthereumStructMember, len(fields)),
}
for i, field := range fields {
dt, name, byteLength, arrays, err := parseType(data, field)
if err != nil {
return nil, err
}
ubyteLength := uint32(byteLength)
t := &trezor.EthereumTypedDataStructAck_EthereumFieldType{}
inner := t
for i := len(arrays) - 1; i >= 0; i-- {
dataType := trezor.EthereumTypedDataStructAck_ARRAY
inner.DataType = &dataType
if arrays[i] != nil {
length := uint32(*arrays[i])
inner.Size = &length
}
inner.EntryType = &trezor.EthereumTypedDataStructAck_EthereumFieldType{}
inner = inner.EntryType
}
var dataType trezor.EthereumTypedDataStructAck_EthereumDataType
switch dt {
case CustomType:
inner.StructName = &name
dataType = trezor.EthereumTypedDataStructAck_STRUCT
members := uint32(len(data.Types[name]))
inner.Size = &members
case IntType:
dataType = trezor.EthereumTypedDataStructAck_INT
inner.Size = &ubyteLength
case UintType:
dataType = trezor.EthereumTypedDataStructAck_UINT
inner.Size = &ubyteLength
case AddressType:
dataType = trezor.EthereumTypedDataStructAck_ADDRESS
case BoolType:
dataType = trezor.EthereumTypedDataStructAck_BOOL
case StringType:
dataType = trezor.EthereumTypedDataStructAck_STRING
case FixedBytesType:
dataType = trezor.EthereumTypedDataStructAck_BYTES
inner.Size = &ubyteLength
case BytesType:
dataType = trezor.EthereumTypedDataStructAck_BYTES
}
inner.DataType = &dataType
ack.Members[i] = &trezor.EthereumTypedDataStructAck_EthereumStructMember{
Name: &field.Name,
Type: t,
}
}
req = ack
case 2:
structType := data.Types[data.PrimaryType]
structValue := data.Message
if valueRequest.MemberPath[0] == 0 {
// populate with domain info
structType = data.Types["EIP712Domain"]
structValue = data.Domain.Map()
}
var value []byte
for i := 1; i < len(valueRequest.MemberPath); i++ {
p := valueRequest.MemberPath[i]
if structType == nil {
return nil, fmt.Errorf("trezor: no struct type for path %v", path)
}
if int(p) >= len(structType) {
return nil, fmt.Errorf("trezor: invalid field index %d for struct %s", p, structRequest.GetName())
}
field := structType[p]
nextValue := structValue[field.Name]
dt, name, byteLength, arrays, err := parseType(data, field)
if err != nil {
return nil, err
}
if len(arrays) > 1 {
nestedArray = true
}
for j := 0; j < len(arrays) && i < len(valueRequest.MemberPath)-1; i, j = i+1, j+1 {
k := reflect.TypeOf(nextValue).Kind()
if !(k == reflect.Array || k == reflect.Slice) {
return nil, fmt.Errorf("trezor: expected array at path %v, got %T", valueRequest.MemberPath[:i+1], nextValue)
}
a := reflect.ValueOf(nextValue)
p = valueRequest.MemberPath[i+1]
if int(p) >= a.Len() {
return nil, fmt.Errorf("trezor: invalid array index %d for path %v", p, valueRequest.MemberPath[:i+1])
}
nextValue = a.Index(int(p)).Interface()
}
k := reflect.TypeOf(nextValue).Kind()
if i < len(valueRequest.MemberPath)-1 {
if reflect.TypeOf(nextValue).Kind() != reflect.Map {
return nil, fmt.Errorf("trezor: expected map at path %v, got %T", valueRequest.MemberPath[:i+1], nextValue)
}
structType = data.Types[name]
structValue = nextValue.(apitypes.TypedDataMessage)
} else if k == reflect.Array || k == reflect.Slice {
// Array value, return length as uint16
value = binary.BigEndian.AppendUint16([]byte{}, uint16(reflect.ValueOf(nextValue).Len()))
} else {
// Last value, encode it as a primitive value
switch dt {
case CustomType:
return nil, fmt.Errorf("trezor: cannot encode custom type %s at path %v", name, valueRequest.MemberPath[:i+1])
case IntType, UintType:
value, err = encodeInteger(nextValue, dt == IntType, byteLength)
if err != nil {
return nil, fmt.Errorf("trezor: value at path %v: %w", valueRequest.MemberPath[:i+1], err)
}
case AddressType, FixedBytesType:
str, ok := nextValue.(string)
if !ok {
return nil, fmt.Errorf("trezor: expected hex string at path %v, got %T", valueRequest.MemberPath[:i+1], nextValue)
}
value = common.FromHex(str)
if len(value) > byteLength {
return nil, fmt.Errorf("trezor: value at path %v is too long (%d bytes, expected %d)", valueRequest.MemberPath[:i+1], len(value), byteLength)
}
for len(value) < byteLength {
value = append([]byte{0}, value...)
}
case BoolType:
if b, ok := nextValue.(bool); ok {
if b {
value = []byte{1}
} else {
value = []byte{0}
}
} else {
return nil, fmt.Errorf("trezor: expected bool at path %v, got %T", valueRequest.MemberPath[:i+1], nextValue)
}
case StringType:
if str, ok := nextValue.(string); ok {
value = []byte(str)
} else {
return nil, fmt.Errorf("trezor: expected string at path %v, got %T", valueRequest.MemberPath[:i+1], nextValue)
}
case BytesType:
if str, ok := nextValue.(string); ok {
value = common.FromHex(str)
} else {
return nil, fmt.Errorf("trezor: expected bytes at path %v, got %T", valueRequest.MemberPath[:i+1], nextValue)
}
}
}
}
req = &trezor.EthereumTypedDataValueAck{
Value: value,
}
default:
return nil, fmt.Errorf("trezor: unexpected reply index %d", n)
}
}
}
// encodeInteger encodes an EIP-712 int/uint value as the big-endian bytes the Trezor expects
// (two's complement for negative ints), padded to byteLength. It accepts the same value types
// go-ethereum's apitypes uses when hashing, so the device receives exactly the values that were
// hashed: *math.HexOrDecimal256 (TypedDataDomain.Map() returns chainId as this), *big.Int,
// decimal or 0x-hex strings, and lossless float64 (JSON numbers). Other types are an error
// rather than an empty value, which would reach the device as 0.
func encodeInteger(v interface{}, signed bool, byteLength int) ([]byte, error) {
var b *big.Int
switch x := v.(type) {
case *math.HexOrDecimal256:
b = (*big.Int)(x)
case *big.Int:
b = x
case string:
var h math.HexOrDecimal256
if err := h.UnmarshalText([]byte(x)); err != nil {
return nil, fmt.Errorf("invalid integer %q: %w", x, err)
}
b = (*big.Int)(&h)
case float64:
if float64(int64(x)) != x {
return nil, fmt.Errorf("invalid integer %v: not representable without loss", x)
}
b = big.NewInt(int64(x))
}
if b == nil {
return nil, fmt.Errorf("unsupported integer value %v of type %T", v, v)
}
bits := uint(byteLength * 8)
if signed {
limit := new(big.Int).Lsh(big.NewInt(1), bits-1)
if b.Cmp(limit) >= 0 || b.Cmp(new(big.Int).Neg(limit)) < 0 {
return nil, fmt.Errorf("integer %s does not fit in int%d", b, bits)
}
if b.Sign() < 0 {
b = new(big.Int).Add(b, new(big.Int).Lsh(big.NewInt(1), bits))
}
} else if b.Sign() < 0 || b.BitLen() > int(bits) {
return nil, fmt.Errorf("integer %s does not fit in uint%d", b, bits)
}
return b.FillBytes(make([]byte, byteLength)), nil
}