/
keystore.go
332 lines (314 loc) · 10.2 KB
/
keystore.go
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright 2018 Shift Devices AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bitbox02
import (
"bytes"
"math/big"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/digitalbitbox/bitbox-wallet-app/backend/coins/btc"
"github.com/digitalbitbox/bitbox-wallet-app/backend/coins/coin"
coinpkg "github.com/digitalbitbox/bitbox-wallet-app/backend/coins/coin"
"github.com/digitalbitbox/bitbox-wallet-app/backend/coins/eth"
"github.com/digitalbitbox/bitbox-wallet-app/backend/coins/ltc"
"github.com/digitalbitbox/bitbox-wallet-app/backend/devices/bitbox02/api"
"github.com/digitalbitbox/bitbox-wallet-app/backend/devices/bitbox02/api/messages"
keystorePkg "github.com/digitalbitbox/bitbox-wallet-app/backend/keystore"
"github.com/digitalbitbox/bitbox-wallet-app/backend/signing"
"github.com/digitalbitbox/bitbox-wallet-app/util/errp"
"github.com/sirupsen/logrus"
)
type keystore struct {
device *Device
configuration *signing.Configuration
cosignerIndex int
log *logrus.Entry
}
// CosignerIndex implements keystore.Keystore.
func (keystore *keystore) CosignerIndex() int {
return keystore.cosignerIndex
}
// SupportsAccount implements keystore.Keystore.
func (keystore *keystore) SupportsAccount(
coin coin.Coin, multisig bool, meta interface{}) bool {
switch coin.(type) {
case *btc.Coin:
if (coin.Code() == "ltc" || coin.Code() == "tltc") && !keystore.device.SupportsLTC() {
return false
}
scriptType := meta.(signing.ScriptType)
return !multisig && scriptType != signing.ScriptTypeP2PKH
case *eth.Coin:
return keystore.device.SupportsETH(coin.Code())
default:
return false
}
}
// CanVerifyAddress implements keystore.Keystore.
func (keystore *keystore) CanVerifyAddress(configuration *signing.Configuration, coin coinpkg.Coin) (bool, bool, error) {
optional := false
switch coin.(type) {
case *btc.Coin:
_, ok := btcMsgCoinMap[coin.Code()]
return ok, optional, nil
case *eth.Coin:
_, ok := ethMsgCoinMap[coin.Code()]
return ok, optional, nil
}
return false, false, nil
}
// VerifyAddress implements keystore.Keystore.
func (keystore *keystore) VerifyAddress(
configuration *signing.Configuration, coin coinpkg.Coin) error {
canVerifyAddress, _, err := keystore.CanVerifyAddress(configuration, coin)
if err != nil {
return err
}
if !canVerifyAddress {
panic("CanVerifyAddress must be true")
}
switch specificCoin := coin.(type) {
case *btc.Coin:
msgScriptType, ok := map[signing.ScriptType]messages.BTCScriptType{
signing.ScriptTypeP2PKH: messages.BTCScriptType_SCRIPT_P2PKH,
signing.ScriptTypeP2WPKHP2SH: messages.BTCScriptType_SCRIPT_P2WPKH_P2SH,
signing.ScriptTypeP2WPKH: messages.BTCScriptType_SCRIPT_P2WPKH,
}[configuration.ScriptType()]
if !ok {
panic("unsupported script type")
}
_, err = keystore.device.BTCPub(
btcMsgCoinMap[coin.Code()], configuration.AbsoluteKeypath().ToUInt32(),
messages.BTCPubRequest_ADDRESS, msgScriptType, true)
case *eth.Coin:
msgCoin, ok := ethMsgCoinMap[coin.Code()]
if !ok {
return errp.New("unsupported coin")
}
// No contract address, displays 'Ethereum' etc. depending on `msgCoin`.
contractAddress := []byte{}
if specificCoin.ERC20Token() != nil {
// Displays the erc20 unit based on the contract.
contractAddress = specificCoin.ERC20Token().ContractAddress().Bytes()
}
_, err := keystore.device.ETHPub(
msgCoin, configuration.AbsoluteKeypath().ToUInt32(),
messages.ETHPubRequest_ADDRESS, true, contractAddress)
if err != nil {
return err
}
default:
return errp.New("unsupported coin")
}
return err
}
// CanVerifyExtendedPublicKey implements keystore.Keystore.
func (keystore *keystore) CanVerifyExtendedPublicKey() bool {
return true
}
func (keystore *keystore) VerifyExtendedPublicKey(
coin coinpkg.Coin, keyPath signing.AbsoluteKeypath, configuration *signing.Configuration) error {
if !keystore.CanVerifyExtendedPublicKey() {
panic("CanVerifyExtendedPublicKey must be true")
}
switch specificCoin := coin.(type) {
case *btc.Coin:
msgCoin, ok := btcMsgCoinMap[coin.Code()]
if !ok {
return errp.New("unsupported coin")
}
var msgOutputType messages.BTCPubRequest_OutputType
switch specificCoin.Net().Net {
case chaincfg.MainNetParams.Net, ltc.MainNetParams.Net:
msgOutputTypes := map[signing.ScriptType]messages.BTCPubRequest_OutputType{
signing.ScriptTypeP2PKH: messages.BTCPubRequest_XPUB,
signing.ScriptTypeP2WPKHP2SH: messages.BTCPubRequest_YPUB,
signing.ScriptTypeP2WPKH: messages.BTCPubRequest_ZPUB,
}
msgOutputType, ok = msgOutputTypes[configuration.ScriptType()]
if !ok {
msgOutputType = messages.BTCPubRequest_XPUB
}
case chaincfg.TestNet3Params.Net, ltc.TestNet4Params.Net:
msgOutputType = messages.BTCPubRequest_TPUB
default:
msgOutputType = messages.BTCPubRequest_XPUB
}
_, err := keystore.device.BTCPub(
msgCoin, keyPath.ToUInt32(), msgOutputType, messages.BTCScriptType_SCRIPT_UNKNOWN, true)
if err != nil {
return err
}
case *eth.Coin:
return errp.New("unsupported operation")
}
return nil
}
// ExtendedPublicKey implements keystore.Keystore.
func (keystore *keystore) ExtendedPublicKey(
coin coinpkg.Coin, keyPath signing.AbsoluteKeypath) (*hdkeychain.ExtendedKey, error) {
switch coin.(type) {
case *btc.Coin:
msgCoin, ok := btcMsgCoinMap[coin.Code()]
if !ok {
return nil, errp.New("unsupported coin")
}
xpubStr, err := keystore.device.BTCPub(
msgCoin, keyPath.ToUInt32(),
messages.BTCPubRequest_XPUB, messages.BTCScriptType_SCRIPT_UNKNOWN, false)
if err != nil {
return nil, err
}
return hdkeychain.NewKeyFromString(xpubStr)
case *eth.Coin:
msgCoin, ok := ethMsgCoinMap[coin.Code()]
if !ok {
return nil, errp.New("unsupported coin")
}
xpubStr, err := keystore.device.ETHPub(
msgCoin, keyPath.ToUInt32(), messages.ETHPubRequest_XPUB, false, []byte{})
if err != nil {
return nil, err
}
return hdkeychain.NewKeyFromString(xpubStr)
default:
return nil, errp.New("unsupported coin")
}
}
func (keystore *keystore) signBTCTransaction(btcProposedTx *btc.ProposedTransaction) error {
tx := btcProposedTx.TXProposal.Transaction
scriptType := btcProposedTx.TXProposal.AccountConfiguration.ScriptType()
msgScriptType, ok := btcMsgScriptTypeMap[scriptType]
if !ok {
return errp.Newf("Unsupported script type %s", scriptType)
}
coin := btcProposedTx.TXProposal.Coin.(*btc.Coin)
msgCoin, ok := btcMsgCoinMap[coin.Code()]
if !ok {
return errp.Newf("coin not supported: %s", coin.Code())
}
// account #0
// TODO: check that all inputs and change are the same account, and use that one.
bip44Account := uint32(hdkeychain.HardenedKeyStart)
inputs := make([]*messages.BTCSignInputRequest, len(tx.TxIn))
for inputIndex, txIn := range tx.TxIn {
prevOut := btcProposedTx.PreviousOutputs[txIn.PreviousOutPoint]
inputs[inputIndex] = &messages.BTCSignInputRequest{
PrevOutHash: txIn.PreviousOutPoint.Hash[:],
PrevOutIndex: txIn.PreviousOutPoint.Index,
PrevOutValue: uint64(prevOut.Value),
Sequence: txIn.Sequence,
Keypath: btcProposedTx.GetAddress(prevOut.ScriptHashHex()).
Configuration.AbsoluteKeypath().ToUInt32(),
}
}
outputs := make([]*messages.BTCSignOutputRequest, len(tx.TxOut))
for index, txOut := range tx.TxOut {
scriptClass, addresses, _, err := txscript.ExtractPkScriptAddrs(txOut.PkScript, coin.Net())
if err != nil {
return errp.WithStack(err)
}
if len(addresses) != 1 {
return errp.New("couldn't parse pkScript")
}
msgOutputType, ok := btcMsgOutputTypeMap[scriptClass]
if !ok {
return errp.Newf("unsupported output type: %d", scriptClass)
}
changeAddress := btcProposedTx.TXProposal.ChangeAddress
isChange := changeAddress != nil && bytes.Equal(
changeAddress.PubkeyScript(),
txOut.PkScript,
)
var keypath []uint32
if isChange {
keypath = changeAddress.Configuration.AbsoluteKeypath().ToUInt32()
}
outputs[index] = &messages.BTCSignOutputRequest{
Ours: isChange,
Type: msgOutputType,
Value: uint64(txOut.Value),
Hash: addresses[0].ScriptAddress(),
Keypath: keypath,
}
}
signatures, err := keystore.device.BTCSign(
msgCoin,
msgScriptType,
bip44Account,
inputs,
outputs,
uint32(tx.Version),
tx.LockTime,
)
if api.IsErrorAbort(err) {
return errp.WithStack(keystorePkg.ErrSigningAborted)
}
if err != nil {
return err
}
for index, signature := range signatures {
btcProposedTx.Signatures[index][keystore.CosignerIndex()] = &btcec.Signature{
R: big.NewInt(0).SetBytes(signature[:32]),
S: big.NewInt(0).SetBytes(signature[32:]),
}
}
return nil
}
func (keystore *keystore) signETHTransaction(txProposal *eth.TxProposal) error {
msgCoin, ok := ethMsgCoinMap[txProposal.Coin.Code()]
if !ok {
return errp.New("unsupported coin")
}
tx := txProposal.Tx
recipient := tx.To()
if recipient == nil {
return errp.New("contract creation not supported")
}
signature, err := keystore.device.ETHSign(
msgCoin,
txProposal.Keypath.ToUInt32(),
tx.Nonce(),
tx.GasPrice(),
tx.Gas(),
*recipient,
tx.Value(),
tx.Data(),
)
if api.IsErrorAbort(err) {
return errp.WithStack(keystorePkg.ErrSigningAborted)
}
if err != nil {
return err
}
signedTx, err := txProposal.Tx.WithSignature(txProposal.Signer, signature)
if err != nil {
return err
}
txProposal.Tx = signedTx
return nil
}
// SignTransaction implements keystore.Keystore.
func (keystore *keystore) SignTransaction(proposedTx interface{}) error {
switch specificProposedTx := proposedTx.(type) {
case *btc.ProposedTransaction:
return keystore.signBTCTransaction(specificProposedTx)
case *eth.TxProposal:
return keystore.signETHTransaction(specificProposedTx)
default:
panic("unknown proposal type")
}
}