Skip to content

Commit dcaabfe

Browse files
authored
Clef: USB hw wallet support (#17756)
* signer: implement USB interaction with hw wallets * signer: fix failing testcases
1 parent 2c110c8 commit dcaabfe

7 files changed

Lines changed: 169 additions & 3 deletions

File tree

‎cmd/clef/intapi_changelog.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
11
### Changelog for internal API (ui-api)
22

3+
### 2.1.0
4+
5+
* Add `OnInputRequired(info UserInputRequest)` to internal API. This method is used when Clef needs user input, e.g. passwords.
6+
7+
The following structures are used:
8+
```golang
9+
UserInputRequest struct {
10+
Prompt string `json:"prompt"`
11+
Title string `json:"title"`
12+
IsPassword bool `json:"isPassword"`
13+
}
14+
UserInputResponse struct {
15+
Text string `json:"text"`
16+
}
17+
```
18+
319
### 2.0.0
420

521
* Modify how `call_info` on a transaction is conveyed. New format:

‎signer/core/api.go‎

Lines changed: 104 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ import (
3636
"github.com/ethereum/go-ethereum/rlp"
3737
)
3838

39+
// numberOfAccountsToDerive For hardware wallets, the number of accounts to derive
40+
const numberOfAccountsToDerive = 10
41+
3942
// ExternalAPI defines the external API through which signing requests are made.
4043
type ExternalAPI interface {
4144
// List available accounts
@@ -79,6 +82,9 @@ type SignerUI interface {
7982
// OnSignerStartup is invoked when the signer boots, and tells the UI info about external API location and version
8083
// information
8184
OnSignerStartup(info StartupInfo)
85+
// OnInputRequried is invoked when clef requires user input, for example master password or
86+
// pin-code for unlocking hardware wallets
87+
OnInputRequired(info UserInputRequest) (UserInputResponse, error)
8288
}
8389

8490
// SignerAPI defines the actual implementation of ExternalAPI
@@ -194,6 +200,14 @@ type (
194200
StartupInfo struct {
195201
Info map[string]interface{} `json:"info"`
196202
}
203+
UserInputRequest struct {
204+
Prompt string `json:"prompt"`
205+
Title string `json:"title"`
206+
IsPassword bool `json:"isPassword"`
207+
}
208+
UserInputResponse struct {
209+
Text string `json:"text"`
210+
}
197211
)
198212

199213
var ErrRequestDenied = errors.New("Request denied")
@@ -215,6 +229,9 @@ func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abi
215229
if len(ksLocation) > 0 {
216230
backends = append(backends, keystore.NewKeyStore(ksLocation, n, p))
217231
}
232+
if advancedMode {
233+
log.Info("Clef is in advanced mode: will warn instead of reject")
234+
}
218235
if !noUSB {
219236
// Start a USB hub for Ledger hardware wallets
220237
if ledgerhub, err := usbwallet.NewLedgerHub(); err != nil {
@@ -231,10 +248,94 @@ func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abi
231248
log.Debug("Trezor support enabled")
232249
}
233250
}
234-
if advancedMode {
235-
log.Info("Clef is in advanced mode: will warn instead of reject")
251+
signer := &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb), !advancedMode}
252+
if !noUSB {
253+
signer.startUSBListener()
254+
}
255+
return signer
256+
}
257+
func (api *SignerAPI) openTrezor(url accounts.URL) {
258+
resp, err := api.UI.OnInputRequired(UserInputRequest{
259+
Prompt: "Pin required to open Trezor wallet\n" +
260+
"Look at the device for number positions\n\n" +
261+
"7 | 8 | 9\n" +
262+
"--+---+--\n" +
263+
"4 | 5 | 6\n" +
264+
"--+---+--\n" +
265+
"1 | 2 | 3\n\n",
266+
IsPassword: true,
267+
Title: "Trezor unlock",
268+
})
269+
if err != nil {
270+
log.Warn("failed getting trezor pin", "err", err)
271+
return
272+
}
273+
// We're using the URL instead of the pointer to the
274+
// Wallet -- perhaps it is not actually present anymore
275+
w, err := api.am.Wallet(url.String())
276+
if err != nil {
277+
log.Warn("wallet unavailable", "url", url)
278+
return
279+
}
280+
err = w.Open(resp.Text)
281+
if err != nil {
282+
log.Warn("failed to open wallet", "wallet", url, "err", err)
283+
return
236284
}
237-
return &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb), !advancedMode}
285+
286+
}
287+
288+
// startUSBListener starts a listener for USB events, for hardware wallet interaction
289+
func (api *SignerAPI) startUSBListener() {
290+
events := make(chan accounts.WalletEvent, 16)
291+
am := api.am
292+
am.Subscribe(events)
293+
go func() {
294+
295+
// Open any wallets already attached
296+
for _, wallet := range am.Wallets() {
297+
if err := wallet.Open(""); err != nil {
298+
log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
299+
if err == usbwallet.ErrTrezorPINNeeded {
300+
go api.openTrezor(wallet.URL())
301+
}
302+
}
303+
}
304+
// Listen for wallet event till termination
305+
for event := range events {
306+
switch event.Kind {
307+
case accounts.WalletArrived:
308+
if err := event.Wallet.Open(""); err != nil {
309+
log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
310+
if err == usbwallet.ErrTrezorPINNeeded {
311+
go api.openTrezor(event.Wallet.URL())
312+
}
313+
}
314+
case accounts.WalletOpened:
315+
status, _ := event.Wallet.Status()
316+
log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
317+
318+
derivationPath := accounts.DefaultBaseDerivationPath
319+
if event.Wallet.URL().Scheme == "ledger" {
320+
derivationPath = accounts.DefaultLedgerBaseDerivationPath
321+
}
322+
var nextPath = derivationPath
323+
// Derive first N accounts, hardcoded for now
324+
for i := 0; i < numberOfAccountsToDerive; i++ {
325+
acc, err := event.Wallet.Derive(nextPath, true)
326+
if err != nil {
327+
log.Warn("account derivation failed", "error", err)
328+
} else {
329+
log.Info("derived account", "address", acc.Address)
330+
}
331+
nextPath[len(nextPath)-1]++
332+
}
333+
case accounts.WalletDropped:
334+
log.Info("Old wallet dropped", "url", event.Wallet.URL())
335+
event.Wallet.Close()
336+
}
337+
}
338+
}()
238339
}
239340

240341
// List returns the set of wallet this signer manages. Each wallet can contain

‎signer/core/api_test.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package core
1919
import (
2020
"bytes"
2121
"context"
22+
"errors"
2223
"fmt"
2324
"io/ioutil"
2425
"math/big"
@@ -41,6 +42,10 @@ type HeadlessUI struct {
4142
controller chan string
4243
}
4344

45+
func (ui *HeadlessUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) {
46+
return UserInputResponse{}, errors.New("not implemented")
47+
}
48+
4449
func (ui *HeadlessUI) OnSignerStartup(info StartupInfo) {
4550
}
4651

‎signer/core/cliui.go‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,22 @@ func (ui *CommandlineUI) readPasswordText(inputstring string) string {
8383
return string(text)
8484
}
8585

86+
func (ui *CommandlineUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) {
87+
fmt.Println(info.Title)
88+
fmt.Println(info.Prompt)
89+
if info.IsPassword {
90+
text, err := terminal.ReadPassword(int(os.Stdin.Fd()))
91+
if err != nil {
92+
log.Error("Failed to read password", "err", err)
93+
}
94+
fmt.Println("-----------------------")
95+
return UserInputResponse{string(text)}, err
96+
}
97+
text := ui.readString()
98+
fmt.Println("-----------------------")
99+
return UserInputResponse{text}, nil
100+
}
101+
86102
// confirm returns true if user enters 'Yes', otherwise false
87103
func (ui *CommandlineUI) confirm() bool {
88104
fmt.Printf("Approve? [y/N]:\n")

‎signer/core/stdioui.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,11 @@ func (ui *StdIOUI) OnSignerStartup(info StartupInfo) {
111111
log.Info("Error calling 'OnSignerStartup'", "exc", err.Error(), "info", info)
112112
}
113113
}
114+
func (ui *StdIOUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) {
115+
var result UserInputResponse
116+
err := ui.dispatch("OnInputRequired", info, &result)
117+
if err != nil {
118+
log.Info("Error calling 'OnInputRequired'", "exc", err.Error(), "info", info)
119+
}
120+
return result, err
121+
}

‎signer/rules/rules.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,11 @@ func (r *rulesetUI) ApproveImport(request *core.ImportRequest) (core.ImportRespo
194194
return r.next.ApproveImport(request)
195195
}
196196

197+
// OnInputRequired not handled by rules
198+
func (r *rulesetUI) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) {
199+
return r.next.OnInputRequired(info)
200+
}
201+
197202
func (r *rulesetUI) ApproveListing(request *core.ListRequest) (core.ListResponse, error) {
198203
jsonreq, err := json.Marshal(request)
199204
approved, err := r.checkApproval("ApproveListing", jsonreq, err)
@@ -222,6 +227,7 @@ func (r *rulesetUI) ShowInfo(message string) {
222227
log.Info(message)
223228
r.next.ShowInfo(message)
224229
}
230+
225231
func (r *rulesetUI) OnSignerStartup(info core.StartupInfo) {
226232
jsonInfo, err := json.Marshal(info)
227233
if err != nil {

‎signer/rules/rules_test.go‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ func mixAddr(a string) (*common.MixedcaseAddress, error) {
7474

7575
type alwaysDenyUI struct{}
7676

77+
func (alwaysDenyUI) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) {
78+
return core.UserInputResponse{}, nil
79+
}
80+
7781
func (alwaysDenyUI) OnSignerStartup(info core.StartupInfo) {
7882
}
7983

@@ -200,6 +204,11 @@ type dummyUI struct {
200204
calls []string
201205
}
202206

207+
func (d *dummyUI) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) {
208+
d.calls = append(d.calls, "OnInputRequired")
209+
return core.UserInputResponse{}, nil
210+
}
211+
203212
func (d *dummyUI) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) {
204213
d.calls = append(d.calls, "ApproveTx")
205214
return core.SignTxResponse{}, core.ErrRequestDenied
@@ -509,6 +518,11 @@ type dontCallMe struct {
509518
t *testing.T
510519
}
511520

521+
func (d *dontCallMe) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) {
522+
d.t.Fatalf("Did not expect next-handler to be called")
523+
return core.UserInputResponse{}, nil
524+
}
525+
512526
func (d *dontCallMe) OnSignerStartup(info core.StartupInfo) {
513527
}
514528

0 commit comments

Comments
 (0)