hub.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // This package implements support for smartcard-based hardware wallets such as
  17. // the one written by Status: https://github.com/status-im/hardware-wallet
  18. //
  19. // This implementation of smartcard wallets have a different interaction process
  20. // to other types of hardware wallet. The process works like this:
  21. //
  22. // 1. (First use with a given client) Establish a pairing between hardware
  23. // wallet and client. This requires a secret value called a 'pairing password'.
  24. // You can pair with an unpaired wallet with `personal.openWallet(URI, pairing password)`.
  25. // 2. (First use only) Initialize the wallet, which generates a keypair, stores
  26. // it on the wallet, and returns it so the user can back it up. You can
  27. // initialize a wallet with `personal.initializeWallet(URI)`.
  28. // 3. Connect to the wallet using the pairing information established in step 1.
  29. // You can connect to a paired wallet with `personal.openWallet(URI, PIN)`.
  30. // 4. Interact with the wallet as normal.
  31. package scwallet
  32. import (
  33. "encoding/json"
  34. "io/ioutil"
  35. "os"
  36. "path/filepath"
  37. "sort"
  38. "sync"
  39. "time"
  40. "github.com/ethereum/go-ethereum/accounts"
  41. "github.com/ethereum/go-ethereum/common"
  42. "github.com/ethereum/go-ethereum/event"
  43. "github.com/ethereum/go-ethereum/log"
  44. pcsc "github.com/gballet/go-libpcsclite"
  45. )
  46. // Scheme is the URI prefix for smartcard wallets.
  47. const Scheme = "keycard"
  48. // refreshCycle is the maximum time between wallet refreshes (if USB hotplug
  49. // notifications don't work).
  50. const refreshCycle = time.Second
  51. // refreshThrottling is the minimum time between wallet refreshes to avoid thrashing.
  52. const refreshThrottling = 500 * time.Millisecond
  53. // smartcardPairing contains information about a smart card we have paired with
  54. // or might pair with the hub.
  55. type smartcardPairing struct {
  56. PublicKey []byte `json:"publicKey"`
  57. PairingIndex uint8 `json:"pairingIndex"`
  58. PairingKey []byte `json:"pairingKey"`
  59. Accounts map[common.Address]accounts.DerivationPath `json:"accounts"`
  60. }
  61. // Hub is a accounts.Backend that can find and handle generic PC/SC hardware wallets.
  62. type Hub struct {
  63. scheme string // Protocol scheme prefixing account and wallet URLs.
  64. context *pcsc.Client
  65. datadir string
  66. pairings map[string]smartcardPairing
  67. refreshed time.Time // Time instance when the list of wallets was last refreshed
  68. wallets map[string]*Wallet // Mapping from reader names to wallet instances
  69. updateFeed event.Feed // Event feed to notify wallet additions/removals
  70. updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
  71. updating bool // Whether the event notification loop is running
  72. quit chan chan error
  73. stateLock sync.RWMutex // Protects the internals of the hub from racey access
  74. }
  75. func (hub *Hub) readPairings() error {
  76. hub.pairings = make(map[string]smartcardPairing)
  77. pairingFile, err := os.Open(filepath.Join(hub.datadir, "smartcards.json"))
  78. if err != nil {
  79. if os.IsNotExist(err) {
  80. return nil
  81. }
  82. return err
  83. }
  84. pairingData, err := ioutil.ReadAll(pairingFile)
  85. if err != nil {
  86. return err
  87. }
  88. var pairings []smartcardPairing
  89. if err := json.Unmarshal(pairingData, &pairings); err != nil {
  90. return err
  91. }
  92. for _, pairing := range pairings {
  93. hub.pairings[string(pairing.PublicKey)] = pairing
  94. }
  95. return nil
  96. }
  97. func (hub *Hub) writePairings() error {
  98. pairingFile, err := os.OpenFile(filepath.Join(hub.datadir, "smartcards.json"), os.O_RDWR|os.O_CREATE, 0755)
  99. if err != nil {
  100. return err
  101. }
  102. defer pairingFile.Close()
  103. pairings := make([]smartcardPairing, 0, len(hub.pairings))
  104. for _, pairing := range hub.pairings {
  105. pairings = append(pairings, pairing)
  106. }
  107. pairingData, err := json.Marshal(pairings)
  108. if err != nil {
  109. return err
  110. }
  111. if _, err := pairingFile.Write(pairingData); err != nil {
  112. return err
  113. }
  114. return nil
  115. }
  116. func (hub *Hub) pairing(wallet *Wallet) *smartcardPairing {
  117. if pairing, ok := hub.pairings[string(wallet.PublicKey)]; ok {
  118. return &pairing
  119. }
  120. return nil
  121. }
  122. func (hub *Hub) setPairing(wallet *Wallet, pairing *smartcardPairing) error {
  123. if pairing == nil {
  124. delete(hub.pairings, string(wallet.PublicKey))
  125. } else {
  126. hub.pairings[string(wallet.PublicKey)] = *pairing
  127. }
  128. return hub.writePairings()
  129. }
  130. // NewHub creates a new hardware wallet manager for smartcards.
  131. func NewHub(daemonPath string, scheme string, datadir string) (*Hub, error) {
  132. context, err := pcsc.EstablishContext(daemonPath, pcsc.ScopeSystem)
  133. if err != nil {
  134. return nil, err
  135. }
  136. hub := &Hub{
  137. scheme: scheme,
  138. context: context,
  139. datadir: datadir,
  140. wallets: make(map[string]*Wallet),
  141. quit: make(chan chan error),
  142. }
  143. if err := hub.readPairings(); err != nil {
  144. return nil, err
  145. }
  146. hub.refreshWallets()
  147. return hub, nil
  148. }
  149. // Wallets implements accounts.Backend, returning all the currently tracked smart
  150. // cards that appear to be hardware wallets.
  151. func (hub *Hub) Wallets() []accounts.Wallet {
  152. // Make sure the list of wallets is up to date
  153. hub.refreshWallets()
  154. hub.stateLock.RLock()
  155. defer hub.stateLock.RUnlock()
  156. cpy := make([]accounts.Wallet, 0, len(hub.wallets))
  157. for _, wallet := range hub.wallets {
  158. cpy = append(cpy, wallet)
  159. }
  160. sort.Sort(accounts.WalletsByURL(cpy))
  161. return cpy
  162. }
  163. // refreshWallets scans the devices attached to the machine and updates the
  164. // list of wallets based on the found devices.
  165. func (hub *Hub) refreshWallets() {
  166. // Don't scan the USB like crazy it the user fetches wallets in a loop
  167. hub.stateLock.RLock()
  168. elapsed := time.Since(hub.refreshed)
  169. hub.stateLock.RUnlock()
  170. if elapsed < refreshThrottling {
  171. return
  172. }
  173. // Retrieve all the smart card reader to check for cards
  174. readers, err := hub.context.ListReaders()
  175. if err != nil {
  176. // This is a perverted hack, the scard library returns an error if no card
  177. // readers are present instead of simply returning an empty list. We don't
  178. // want to fill the user's log with errors, so filter those out.
  179. if err.Error() != "scard: Cannot find a smart card reader." {
  180. log.Error("Failed to enumerate smart card readers", "err", err)
  181. return
  182. }
  183. }
  184. // Transform the current list of wallets into the new one
  185. hub.stateLock.Lock()
  186. events := []accounts.WalletEvent{}
  187. seen := make(map[string]struct{})
  188. for _, reader := range readers {
  189. // Mark the reader as present
  190. seen[reader] = struct{}{}
  191. // If we already know about this card, skip to the next reader, otherwise clean up
  192. if wallet, ok := hub.wallets[reader]; ok {
  193. if err := wallet.ping(); err == nil {
  194. continue
  195. }
  196. wallet.Close()
  197. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
  198. delete(hub.wallets, reader)
  199. }
  200. // New card detected, try to connect to it
  201. card, err := hub.context.Connect(reader, pcsc.ShareShared, pcsc.ProtocolAny)
  202. if err != nil {
  203. log.Debug("Failed to open smart card", "reader", reader, "err", err)
  204. continue
  205. }
  206. wallet := NewWallet(hub, card)
  207. if err = wallet.connect(); err != nil {
  208. log.Debug("Failed to connect to smart card", "reader", reader, "err", err)
  209. card.Disconnect(pcsc.LeaveCard)
  210. continue
  211. }
  212. // Card connected, start tracking in amongs the wallets
  213. hub.wallets[reader] = wallet
  214. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
  215. }
  216. // Remove any wallets no longer present
  217. for reader, wallet := range hub.wallets {
  218. if _, ok := seen[reader]; !ok {
  219. wallet.Close()
  220. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
  221. delete(hub.wallets, reader)
  222. }
  223. }
  224. hub.refreshed = time.Now()
  225. hub.stateLock.Unlock()
  226. for _, event := range events {
  227. hub.updateFeed.Send(event)
  228. }
  229. }
  230. // Subscribe implements accounts.Backend, creating an async subscription to
  231. // receive notifications on the addition or removal of smart card wallets.
  232. func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
  233. // We need the mutex to reliably start/stop the update loop
  234. hub.stateLock.Lock()
  235. defer hub.stateLock.Unlock()
  236. // Subscribe the caller and track the subscriber count
  237. sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink))
  238. // Subscribers require an active notification loop, start it
  239. if !hub.updating {
  240. hub.updating = true
  241. go hub.updater()
  242. }
  243. return sub
  244. }
  245. // updater is responsible for maintaining an up-to-date list of wallets managed
  246. // by the smart card hub, and for firing wallet addition/removal events.
  247. func (hub *Hub) updater() {
  248. for {
  249. // TODO: Wait for a USB hotplug event (not supported yet) or a refresh timeout
  250. // <-hub.changes
  251. time.Sleep(refreshCycle)
  252. // Run the wallet refresher
  253. hub.refreshWallets()
  254. // If all our subscribers left, stop the updater
  255. hub.stateLock.Lock()
  256. if hub.updateScope.Count() == 0 {
  257. hub.updating = false
  258. hub.stateLock.Unlock()
  259. return
  260. }
  261. hub.stateLock.Unlock()
  262. }
  263. }