@@ -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 {
7169type 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-
9087func (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.
180174func (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.
198197func (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.
260269func (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.
278287func (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 ()
0 commit comments