Skip to content

Commit 3869439

Browse files
karalabegballet
authored andcommitted
accounts/scwallet: ordered wallets, tighter events, derivation logs
1 parent 114de0f commit 3869439

2 files changed

Lines changed: 81 additions & 63 deletions

File tree

‎accounts/scwallet/hub.go‎

Lines changed: 56 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,12 @@ import (
3636
"encoding/json"
3737
"io/ioutil"
3838
"os"
39-
"reflect"
4039
"sync"
4140
"time"
4241

4342
"github.com/ebfe/scard"
4443
"github.com/ethereum/go-ethereum/accounts"
4544
"github.com/ethereum/go-ethereum/common"
46-
"github.com/ethereum/go-ethereum/common/hexutil"
4745
"github.com/ethereum/go-ethereum/event"
4846
"github.com/ethereum/go-ethereum/log"
4947
)
@@ -71,9 +69,10 @@ type smartcardPairing struct {
7169
type Hub struct {
7270
scheme string // Protocol scheme prefixing account and wallet URLs.
7371

74-
context *scard.Context
75-
datadir string
76-
pairings map[string]smartcardPairing
72+
context *scard.Context
73+
datadir string
74+
pairings map[string]smartcardPairing
75+
7776
refreshed time.Time // Time instance when the list of wallets was last refreshed
7877
wallets map[string]*Wallet // Mapping from reader names to wallet instances
7978
updateFeed event.Feed // Event feed to notify wallet additions/removals
@@ -82,11 +81,9 @@ type Hub struct {
8281

8382
quit chan chan error
8483

85-
stateLock sync.Mutex // Protects the internals of the hub from racey access
84+
stateLock sync.RWMutex // Protects the internals of the hub from racey access
8685
}
8786

88-
var HubType = reflect.TypeOf(&Hub{})
89-
9087
func (hub *Hub) readPairings() error {
9188
hub.pairings = make(map[string]smartcardPairing)
9289
pairingFile, err := os.Open(hub.datadir + "/smartcards.json")
@@ -158,36 +155,38 @@ func NewHub(scheme string, datadir string) (*Hub, error) {
158155
if err != nil {
159156
return nil, err
160157
}
161-
162158
hub := &Hub{
163159
scheme: scheme,
164160
context: context,
165161
datadir: datadir,
166162
wallets: make(map[string]*Wallet),
167163
quit: make(chan chan error),
168164
}
169-
170165
if err := hub.readPairings(); err != nil {
171166
return nil, err
172167
}
173-
174168
hub.refreshWallets()
175169
return hub, nil
176170
}
177171

178-
// Wallets implements accounts.Backend, returning all the currently tracked
179-
// devices that appear to be hardware wallets.
172+
// Wallets implements accounts.Backend, returning all the currently tracked smart
173+
// cards that appear to be hardware wallets.
180174
func (hub *Hub) Wallets() []accounts.Wallet {
181175
// Make sure the list of wallets is up to date
182-
hub.stateLock.Lock()
183-
defer hub.stateLock.Unlock()
184-
185176
hub.refreshWallets()
186177

178+
hub.stateLock.RLock()
179+
defer hub.stateLock.RUnlock()
180+
187181
cpy := make([]accounts.Wallet, 0, len(hub.wallets))
188182
for _, wallet := range hub.wallets {
189-
if wallet != nil {
190-
cpy = append(cpy, wallet)
183+
cpy = append(cpy, wallet)
184+
}
185+
for i := 0; i < len(cpy); i++ {
186+
for j := i + 1; j < len(cpy); j++ {
187+
if cpy[i].URL().Cmp(cpy[j].URL()) > 0 {
188+
cpy[i], cpy[j] = cpy[j], cpy[i]
189+
}
191190
}
192191
}
193192
return cpy
@@ -196,67 +195,77 @@ func (hub *Hub) Wallets() []accounts.Wallet {
196195
// refreshWallets scans the devices attached to the machine and updates the
197196
// list of wallets based on the found devices.
198197
func (hub *Hub) refreshWallets() {
198+
// Don't scan the USB like crazy it the user fetches wallets in a loop
199+
hub.stateLock.RLock()
199200
elapsed := time.Since(hub.refreshed)
201+
hub.stateLock.RUnlock()
202+
200203
if elapsed < refreshThrottling {
201204
return
202205
}
203-
206+
// Retrieve all the smart card reader to check for cards
204207
readers, err := hub.context.ListReaders()
205208
if err != nil {
206-
log.Error("Error listing readers", "err", err)
209+
// This is a perverted hack, the scard library returns an error if no card
210+
// readers are present instead of simply returning an empty list. We don't
211+
// want to fill the user's log with errors, so filter those out.
212+
if err.Error() != "scard: Cannot find a smart card reader." {
213+
log.Error("Failed to enumerate smart card readers", "err", err)
214+
}
207215
}
216+
// Transform the current list of wallets into the new one
217+
hub.stateLock.Lock()
208218

209219
events := []accounts.WalletEvent{}
210220
seen := make(map[string]struct{})
221+
211222
for _, reader := range readers {
223+
// Mark the reader as present
224+
seen[reader] = struct{}{}
225+
226+
// If we alreay know about this card, skip to the next reader, otherwise clean up
212227
if wallet, ok := hub.wallets[reader]; ok {
213-
// We already know about this card; check it's still present
214-
if err := wallet.ping(); err != nil {
215-
log.Debug("Got error pinging wallet", "reader", reader, "err", err)
216-
} else {
217-
seen[reader] = struct{}{}
228+
if err := wallet.ping(); err == nil {
229+
continue
218230
}
219-
continue
231+
wallet.Close()
232+
events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
233+
delete(hub.wallets, reader)
220234
}
221-
seen[reader] = struct{}{}
222-
235+
// New card detected, try to connect to it
223236
card, err := hub.context.Connect(reader, scard.ShareShared, scard.ProtocolAny)
224237
if err != nil {
225-
log.Debug("Error opening card", "reader", reader, "err", err)
238+
log.Debug("Failed to open smart card", "reader", reader, "err", err)
226239
continue
227240
}
228-
229241
wallet := NewWallet(hub, card)
230-
err = wallet.connect()
231-
if err != nil {
232-
log.Debug("Error connecting to wallet", "reader", reader, "err", err)
242+
if err = wallet.connect(); err != nil {
243+
log.Debug("Failed to connect to smart card", "reader", reader, "err", err)
233244
card.Disconnect(scard.LeaveCard)
234245
continue
235246
}
236-
247+
// Card connected, start tracking in amongs the wallets
237248
hub.wallets[reader] = wallet
238249
events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
239-
log.Info("Found new smartcard wallet", "reader", reader, "publicKey", hexutil.Encode(wallet.PublicKey[:4]))
240250
}
241-
242-
// Remove any wallets we no longer see
243-
for k, wallet := range hub.wallets {
244-
if _, ok := seen[k]; !ok {
245-
log.Info("Wallet disconnected", "pubkey", hexutil.Encode(wallet.PublicKey[:4]), "reader", k)
251+
// Remove any wallets no longer present
252+
for reader, wallet := range hub.wallets {
253+
if _, ok := seen[reader]; !ok {
246254
wallet.Close()
247255
events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
248-
delete(hub.wallets, k)
256+
delete(hub.wallets, reader)
249257
}
250258
}
259+
hub.refreshed = time.Now()
260+
hub.stateLock.Unlock()
251261

252262
for _, event := range events {
253263
hub.updateFeed.Send(event)
254264
}
255-
hub.refreshed = time.Now()
256265
}
257266

258267
// Subscribe implements accounts.Backend, creating an async subscription to
259-
// receive notifications on the addition or removal of wallets.
268+
// receive notifications on the addition or removal of smart card wallets.
260269
func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
261270
// We need the mutex to reliably start/stop the update loop
262271
hub.stateLock.Lock()
@@ -274,16 +283,18 @@ func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
274283
}
275284

276285
// updater is responsible for maintaining an up-to-date list of wallets managed
277-
// by the hub, and for firing wallet addition/removal events.
286+
// by the smart card hub, and for firing wallet addition/removal events.
278287
func (hub *Hub) updater() {
279288
for {
289+
// TODO: Wait for a USB hotplug event (not supported yet) or a refresh timeout
290+
// <-hub.changes
280291
time.Sleep(refreshCycle)
281292

282293
// Run the wallet refresher
283-
hub.stateLock.Lock()
284294
hub.refreshWallets()
285295

286296
// If all our subscribers left, stop the updater
297+
hub.stateLock.Lock()
287298
if hub.updateScope.Count() == 0 {
288299
hub.updating = false
289300
hub.stateLock.Unlock()

‎accounts/scwallet/wallet.go‎

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,11 @@ type Wallet struct {
9393
Hub *Hub // A handle to the Hub that instantiated this wallet.
9494
PublicKey []byte // The wallet's public key (used for communication and identification, not signing!)
9595

96-
lock sync.Mutex // Lock that gates access to struct fields and communication with the card
97-
card *scard.Card // A handle to the smartcard interface for the wallet.
98-
session *Session // The secure communication session with the card
99-
log log.Logger // Contextual logger to tag the base with its id
96+
lock sync.Mutex // Lock that gates access to struct fields and communication with the card
97+
card *scard.Card // A handle to the smartcard interface for the wallet.
98+
session *Session // The secure communication session with the card
99+
log log.Logger // Contextual logger to tag the base with its id
100+
100101
deriveNextPath accounts.DerivationPath // Next derivation path for account auto-discovery
101102
deriveNextAddr common.Address // Next derived account address for auto-discovery
102103
deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with
@@ -273,7 +274,7 @@ func (w *Wallet) Unpair(pin []byte) error {
273274
func (w *Wallet) URL() accounts.URL {
274275
return accounts.URL{
275276
Scheme: w.Hub.scheme,
276-
Path: fmt.Sprintf("%x", w.PublicKey[1:3]),
277+
Path: fmt.Sprintf("%x", w.PublicKey[1:5]), // Byte #0 isn't unique; 1:5 covers << 64K cards, bump to 1:9 for << 4M
277278
}
278279
}
279280

@@ -327,7 +328,7 @@ func (w *Wallet) Open(passphrase string) error {
327328
if err := w.session.authenticate(*pairing); err != nil {
328329
return fmt.Errorf("failed to authenticate card %x: %s", w.PublicKey[:4], err)
329330
}
330-
return nil
331+
return ErrPINNeeded
331332
}
332333
// If no passphrase was supplied, request the PUK from the user
333334
if passphrase == "" {
@@ -389,8 +390,8 @@ func (w *Wallet) Close() error {
389390
// selfDerive is an account derivation loop that upon request attempts to find
390391
// new non-zero accounts.
391392
func (w *Wallet) selfDerive() {
392-
w.log.Debug("Smartcard wallet self-derivation started")
393-
defer w.log.Debug("Smartcard wallet self-derivation stopped")
393+
w.log.Debug("Smart card wallet self-derivation started")
394+
defer w.log.Debug("Smart card wallet self-derivation stopped")
394395

395396
// Execute self-derivations until termination or error
396397
var (
@@ -418,21 +419,22 @@ func (w *Wallet) selfDerive() {
418419

419420
// Device lock obtained, derive the next batch of accounts
420421
var (
421-
paths []accounts.DerivationPath
422-
nextAccount accounts.Account
423-
nextAddr = w.deriveNextAddr
424-
nextPath = w.deriveNextPath
422+
paths []accounts.DerivationPath
423+
nextAcc accounts.Account
424+
425+
nextAddr = w.deriveNextAddr
426+
nextPath = w.deriveNextPath
425427

426428
context = context.Background()
427429
)
428430
for empty := false; !empty; {
429431
// Retrieve the next derived Ethereum account
430432
if nextAddr == (common.Address{}) {
431-
if nextAccount, err = w.session.derive(nextPath); err != nil {
433+
if nextAcc, err = w.session.derive(nextPath); err != nil {
432434
w.log.Warn("Smartcard wallet account derivation failed", "err", err)
433435
break
434436
}
435-
nextAddr = nextAccount.Address
437+
nextAddr = nextAcc.Address
436438
}
437439
// Check the account's status against the current chain state
438440
var (
@@ -459,8 +461,8 @@ func (w *Wallet) selfDerive() {
459461
paths = append(paths, path)
460462

461463
// Display a log message to the user for new (or previously empty accounts)
462-
if _, known := pairing.Accounts[nextAddr]; !known || (!empty && nextAddr == w.deriveNextAddr) {
463-
w.log.Info("Smartcard wallet discovered new account", "address", nextAccount.Address, "path", path, "balance", balance, "nonce", nonce)
464+
if _, known := pairing.Accounts[nextAddr]; !known || !empty || nextAddr != w.deriveNextAddr {
465+
w.log.Info("Smartcard wallet discovered new account", "address", nextAddr, "path", path, "balance", balance, "nonce", nonce)
464466
}
465467
pairing.Accounts[nextAddr] = path
466468

@@ -470,12 +472,10 @@ func (w *Wallet) selfDerive() {
470472
nextPath[len(nextPath)-1]++
471473
}
472474
}
473-
474475
// If there are new accounts, write them out
475476
if len(paths) > 0 {
476477
err = w.Hub.setPairing(w, pairing)
477478
}
478-
479479
// Shift the self-derivation forward
480480
w.deriveNextAddr = nextAddr
481481
w.deriveNextPath = nextPath
@@ -524,6 +524,13 @@ func (w *Wallet) Accounts() []accounts.Account {
524524
for address, path := range pairing.Accounts {
525525
ret = append(ret, w.makeAccount(address, path))
526526
}
527+
for i := 0; i < len(ret); i++ {
528+
for j := i + 1; j < len(ret); j++ {
529+
if ret[i].URL.Cmp(ret[j].URL) > 0 {
530+
ret[i], ret[j] = ret[j], ret[i]
531+
}
532+
}
533+
}
527534
return ret
528535
}
529536
return nil

0 commit comments

Comments
 (0)