hub.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 'PUK'. You can
  24. // pair with an unpaired wallet with `personal.openWallet(URI, PUK)`.
  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. "sort"
  37. "sync"
  38. "time"
  39. "github.com/ethereum/go-ethereum/accounts"
  40. "github.com/ethereum/go-ethereum/common"
  41. "github.com/ethereum/go-ethereum/event"
  42. "github.com/ethereum/go-ethereum/log"
  43. pcsc "github.com/gballet/go-libpcsclite"
  44. )
  45. // Scheme is the URI prefix for smartcard wallets.
  46. const Scheme = "pcsc"
  47. // refreshCycle is the maximum time between wallet refreshes (if USB hotplug
  48. // notifications don't work).
  49. const refreshCycle = time.Second
  50. // refreshThrottling is the minimum time between wallet refreshes to avoid thrashing.
  51. const refreshThrottling = 500 * time.Millisecond
  52. // smartcardPairing contains information about a smart card we have paired with
  53. // or might pair with the hub.
  54. type smartcardPairing struct {
  55. PublicKey []byte `json:"publicKey"`
  56. PairingIndex uint8 `json:"pairingIndex"`
  57. PairingKey []byte `json:"pairingKey"`
  58. Accounts map[common.Address]accounts.DerivationPath `json:"accounts"`
  59. }
  60. // Hub is a accounts.Backend that can find and handle generic PC/SC hardware wallets.
  61. type Hub struct {
  62. scheme string // Protocol scheme prefixing account and wallet URLs.
  63. context *pcsc.Client
  64. datadir string
  65. pairings map[string]smartcardPairing
  66. refreshed time.Time // Time instance when the list of wallets was last refreshed
  67. wallets map[string]*Wallet // Mapping from reader names to wallet instances
  68. updateFeed event.Feed // Event feed to notify wallet additions/removals
  69. updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
  70. updating bool // Whether the event notification loop is running
  71. quit chan chan error
  72. stateLock sync.RWMutex // Protects the internals of the hub from racey access
  73. }
  74. func (hub *Hub) readPairings() error {
  75. hub.pairings = make(map[string]smartcardPairing)
  76. pairingFile, err := os.Open(hub.datadir + "/smartcards.json")
  77. if err != nil {
  78. if os.IsNotExist(err) {
  79. return nil
  80. }
  81. return err
  82. }
  83. pairingData, err := ioutil.ReadAll(pairingFile)
  84. if err != nil {
  85. return err
  86. }
  87. var pairings []smartcardPairing
  88. if err := json.Unmarshal(pairingData, &pairings); err != nil {
  89. return err
  90. }
  91. for _, pairing := range pairings {
  92. hub.pairings[string(pairing.PublicKey)] = pairing
  93. }
  94. return nil
  95. }
  96. func (hub *Hub) writePairings() error {
  97. pairingFile, err := os.OpenFile(hub.datadir+"/smartcards.json", os.O_RDWR|os.O_CREATE, 0755)
  98. if err != nil {
  99. return err
  100. }
  101. pairings := make([]smartcardPairing, 0, len(hub.pairings))
  102. for _, pairing := range hub.pairings {
  103. pairings = append(pairings, pairing)
  104. }
  105. pairingData, err := json.Marshal(pairings)
  106. if err != nil {
  107. return err
  108. }
  109. if _, err := pairingFile.Write(pairingData); err != nil {
  110. return err
  111. }
  112. return pairingFile.Close()
  113. }
  114. func (hub *Hub) pairing(wallet *Wallet) *smartcardPairing {
  115. pairing, ok := hub.pairings[string(wallet.PublicKey)]
  116. if ok {
  117. return &pairing
  118. }
  119. return nil
  120. }
  121. func (hub *Hub) setPairing(wallet *Wallet, pairing *smartcardPairing) error {
  122. if pairing == nil {
  123. delete(hub.pairings, string(wallet.PublicKey))
  124. } else {
  125. hub.pairings[string(wallet.PublicKey)] = *pairing
  126. }
  127. return hub.writePairings()
  128. }
  129. // NewHub creates a new hardware wallet manager for smartcards.
  130. func NewHub(scheme string, datadir string) (*Hub, error) {
  131. context, err := pcsc.EstablishContext(pcsc.ScopeSystem)
  132. if err != nil {
  133. return nil, err
  134. }
  135. hub := &Hub{
  136. scheme: scheme,
  137. context: context,
  138. datadir: datadir,
  139. wallets: make(map[string]*Wallet),
  140. quit: make(chan chan error),
  141. }
  142. if err := hub.readPairings(); err != nil {
  143. return nil, err
  144. }
  145. hub.refreshWallets()
  146. return hub, nil
  147. }
  148. // Wallets implements accounts.Backend, returning all the currently tracked smart
  149. // cards that appear to be hardware wallets.
  150. func (hub *Hub) Wallets() []accounts.Wallet {
  151. // Make sure the list of wallets is up to date
  152. hub.refreshWallets()
  153. hub.stateLock.RLock()
  154. defer hub.stateLock.RUnlock()
  155. cpy := make([]accounts.Wallet, 0, len(hub.wallets))
  156. for _, wallet := range hub.wallets {
  157. cpy = append(cpy, wallet)
  158. }
  159. sort.Sort(accounts.WalletsByURL(cpy))
  160. return cpy
  161. }
  162. // refreshWallets scans the devices attached to the machine and updates the
  163. // list of wallets based on the found devices.
  164. func (hub *Hub) refreshWallets() {
  165. // Don't scan the USB like crazy it the user fetches wallets in a loop
  166. hub.stateLock.RLock()
  167. elapsed := time.Since(hub.refreshed)
  168. hub.stateLock.RUnlock()
  169. if elapsed < refreshThrottling {
  170. return
  171. }
  172. // Retrieve all the smart card reader to check for cards
  173. readers, err := hub.context.ListReaders()
  174. if err != nil {
  175. // This is a perverted hack, the scard library returns an error if no card
  176. // readers are present instead of simply returning an empty list. We don't
  177. // want to fill the user's log with errors, so filter those out.
  178. if err.Error() != "scard: Cannot find a smart card reader." {
  179. log.Error("Failed to enumerate smart card readers", "err", err)
  180. }
  181. }
  182. // Transform the current list of wallets into the new one
  183. hub.stateLock.Lock()
  184. events := []accounts.WalletEvent{}
  185. seen := make(map[string]struct{})
  186. for _, reader := range readers {
  187. // Mark the reader as present
  188. seen[reader] = struct{}{}
  189. // If we alreay know about this card, skip to the next reader, otherwise clean up
  190. if wallet, ok := hub.wallets[reader]; ok {
  191. if err := wallet.ping(); err == nil {
  192. continue
  193. }
  194. wallet.Close()
  195. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
  196. delete(hub.wallets, reader)
  197. }
  198. // New card detected, try to connect to it
  199. card, err := hub.context.Connect(reader, pcsc.ShareShared, pcsc.ProtocolAny)
  200. if err != nil {
  201. log.Debug("Failed to open smart card", "reader", reader, "err", err)
  202. continue
  203. }
  204. wallet := NewWallet(hub, card)
  205. if err = wallet.connect(); err != nil {
  206. log.Debug("Failed to connect to smart card", "reader", reader, "err", err)
  207. card.Disconnect(pcsc.LeaveCard)
  208. continue
  209. }
  210. // Card connected, start tracking in amongs the wallets
  211. hub.wallets[reader] = wallet
  212. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
  213. }
  214. // Remove any wallets no longer present
  215. for reader, wallet := range hub.wallets {
  216. if _, ok := seen[reader]; !ok {
  217. wallet.Close()
  218. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
  219. delete(hub.wallets, reader)
  220. }
  221. }
  222. hub.refreshed = time.Now()
  223. hub.stateLock.Unlock()
  224. for _, event := range events {
  225. hub.updateFeed.Send(event)
  226. }
  227. }
  228. // Subscribe implements accounts.Backend, creating an async subscription to
  229. // receive notifications on the addition or removal of smart card wallets.
  230. func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
  231. // We need the mutex to reliably start/stop the update loop
  232. hub.stateLock.Lock()
  233. defer hub.stateLock.Unlock()
  234. // Subscribe the caller and track the subscriber count
  235. sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink))
  236. // Subscribers require an active notification loop, start it
  237. if !hub.updating {
  238. hub.updating = true
  239. go hub.updater()
  240. }
  241. return sub
  242. }
  243. // updater is responsible for maintaining an up-to-date list of wallets managed
  244. // by the smart card hub, and for firing wallet addition/removal events.
  245. func (hub *Hub) updater() {
  246. for {
  247. // TODO: Wait for a USB hotplug event (not supported yet) or a refresh timeout
  248. // <-hub.changes
  249. time.Sleep(refreshCycle)
  250. // Run the wallet refresher
  251. hub.refreshWallets()
  252. // If all our subscribers left, stop the updater
  253. hub.stateLock.Lock()
  254. if hub.updateScope.Count() == 0 {
  255. hub.updating = false
  256. hub.stateLock.Unlock()
  257. return
  258. }
  259. hub.stateLock.Unlock()
  260. }
  261. }