hub.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. package scwallet
  17. import (
  18. "encoding/json"
  19. "io/ioutil"
  20. "os"
  21. "reflect"
  22. "sync"
  23. "time"
  24. "github.com/ebfe/scard"
  25. "github.com/ethereum/go-ethereum/accounts"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/common/hexutil"
  28. "github.com/ethereum/go-ethereum/event"
  29. "github.com/ethereum/go-ethereum/log"
  30. )
  31. const Scheme = "pcsc"
  32. // refreshCycle is the maximum time between wallet refreshes (if USB hotplug
  33. // notifications don't work).
  34. const refreshCycle = 5 * time.Second
  35. // refreshThrottling is the minimum time between wallet refreshes to avoid thrashing.
  36. const refreshThrottling = 500 * time.Millisecond
  37. // SmartcardPairing contains information about a smart card we have paired with
  38. // or might pair withub.
  39. type SmartcardPairing struct {
  40. PublicKey []byte `json:"publicKey"`
  41. PairingIndex uint8 `json:"pairingIndex"`
  42. PairingKey []byte `json:"pairingKey"`
  43. Accounts map[common.Address]accounts.DerivationPath `json:"accounts"`
  44. }
  45. // Hub is a accounts.Backend that can find and handle generic PC/SC hardware wallets.
  46. type Hub struct {
  47. scheme string // Protocol scheme prefixing account and wallet URLs.
  48. context *scard.Context
  49. datadir string
  50. pairings map[string]SmartcardPairing
  51. refreshed time.Time // Time instance when the list of wallets was last refreshed
  52. wallets map[string]*Wallet // Mapping from reader names to wallet instances
  53. updateFeed event.Feed // Event feed to notify wallet additions/removals
  54. updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
  55. updating bool // Whether the event notification loop is running
  56. quit chan chan error
  57. stateLock sync.Mutex // Protects the internals of the hub from racey access
  58. }
  59. var HubType = reflect.TypeOf(&Hub{})
  60. func (hub *Hub) readPairings() error {
  61. hub.pairings = make(map[string]SmartcardPairing)
  62. pairingFile, err := os.Open(hub.datadir + "/smartcards.json")
  63. if err != nil {
  64. if os.IsNotExist(err) {
  65. return nil
  66. }
  67. return err
  68. }
  69. pairingData, err := ioutil.ReadAll(pairingFile)
  70. if err != nil {
  71. return err
  72. }
  73. var pairings []SmartcardPairing
  74. if err := json.Unmarshal(pairingData, &pairings); err != nil {
  75. return err
  76. }
  77. for _, pairing := range pairings {
  78. hub.pairings[string(pairing.PublicKey)] = pairing
  79. }
  80. return nil
  81. }
  82. func (hub *Hub) writePairings() error {
  83. pairingFile, err := os.OpenFile(hub.datadir+"/smartcards.json", os.O_RDWR|os.O_CREATE, 0755)
  84. if err != nil {
  85. return err
  86. }
  87. pairings := make([]SmartcardPairing, 0, len(hub.pairings))
  88. for _, pairing := range hub.pairings {
  89. pairings = append(pairings, pairing)
  90. }
  91. pairingData, err := json.Marshal(pairings)
  92. if err != nil {
  93. return err
  94. }
  95. if _, err := pairingFile.Write(pairingData); err != nil {
  96. return err
  97. }
  98. return pairingFile.Close()
  99. }
  100. func (hub *Hub) getPairing(wallet *Wallet) *SmartcardPairing {
  101. pairing, ok := hub.pairings[string(wallet.PublicKey)]
  102. if ok {
  103. return &pairing
  104. }
  105. return nil
  106. }
  107. func (hub *Hub) setPairing(wallet *Wallet, pairing *SmartcardPairing) error {
  108. if pairing == nil {
  109. delete(hub.pairings, string(wallet.PublicKey))
  110. } else {
  111. hub.pairings[string(wallet.PublicKey)] = *pairing
  112. }
  113. return hub.writePairings()
  114. }
  115. // NewHub creates a new hardware wallet manager for smartcards.
  116. func NewHub(scheme string, datadir string) (*Hub, error) {
  117. context, err := scard.EstablishContext()
  118. if err != nil {
  119. return nil, err
  120. }
  121. hub := &Hub{
  122. scheme: scheme,
  123. context: context,
  124. datadir: datadir,
  125. wallets: make(map[string]*Wallet),
  126. quit: make(chan chan error),
  127. }
  128. if err := hub.readPairings(); err != nil {
  129. return nil, err
  130. }
  131. hub.refreshWallets()
  132. return hub, nil
  133. }
  134. // Wallets implements accounts.Backend, returning all the currently tracked USB
  135. // devices that appear to be hardware wallets.
  136. func (hub *Hub) Wallets() []accounts.Wallet {
  137. // Make sure the list of wallets is up to date
  138. hub.stateLock.Lock()
  139. defer hub.stateLock.Unlock()
  140. hub.refreshWallets()
  141. cpy := make([]accounts.Wallet, 0, len(hub.wallets))
  142. for _, wallet := range hub.wallets {
  143. if wallet != nil {
  144. cpy = append(cpy, wallet)
  145. }
  146. }
  147. return cpy
  148. }
  149. // refreshWallets scans the USB devices attached to the machine and updates the
  150. // list of wallets based on the found devices.
  151. func (hub *Hub) refreshWallets() {
  152. elapsed := time.Since(hub.refreshed)
  153. if elapsed < refreshThrottling {
  154. return
  155. }
  156. readers, err := hub.context.ListReaders()
  157. if err != nil {
  158. log.Error("Error listing readers", "err", err)
  159. }
  160. events := []accounts.WalletEvent{}
  161. seen := make(map[string]struct{})
  162. for _, reader := range readers {
  163. if wallet, ok := hub.wallets[reader]; ok {
  164. // We already know about this card; check it's still present
  165. if err := wallet.ping(); err != nil {
  166. log.Debug("Got error pinging wallet", "reader", reader, "err", err)
  167. } else {
  168. seen[reader] = struct{}{}
  169. }
  170. continue
  171. }
  172. seen[reader] = struct{}{}
  173. card, err := hub.context.Connect(reader, scard.ShareShared, scard.ProtocolAny)
  174. if err != nil {
  175. log.Debug("Error opening card", "reader", reader, "err", err)
  176. continue
  177. }
  178. wallet := NewWallet(hub, card)
  179. err = wallet.connect()
  180. if err != nil {
  181. log.Debug("Error connecting to wallet", "reader", reader, "err", err)
  182. card.Disconnect(scard.LeaveCard)
  183. continue
  184. }
  185. hub.wallets[reader] = wallet
  186. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
  187. log.Info("Found new smartcard wallet", "reader", reader, "publicKey", hexutil.Encode(wallet.PublicKey[:4]))
  188. }
  189. // Remove any wallets we no longer see
  190. for k, wallet := range hub.wallets {
  191. if _, ok := seen[k]; !ok {
  192. log.Info("Wallet disconnected", "pubkey", hexutil.Encode(wallet.PublicKey[:4]), "reader", k)
  193. wallet.Close()
  194. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
  195. delete(hub.wallets, k)
  196. }
  197. }
  198. for _, event := range events {
  199. hub.updateFeed.Send(event)
  200. }
  201. hub.refreshed = time.Now()
  202. }
  203. // Subscribe implements accounts.Backend, creating an async subscription to
  204. // receive notifications on the addition or removal of wallets.
  205. func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
  206. // We need the mutex to reliably start/stop the update loop
  207. hub.stateLock.Lock()
  208. defer hub.stateLock.Unlock()
  209. // Subscribe the caller and track the subscriber count
  210. sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink))
  211. // Subscribers require an active notification loop, start it
  212. if !hub.updating {
  213. hub.updating = true
  214. go hub.updater()
  215. }
  216. return sub
  217. }
  218. // updater is responsible for maintaining an up-to-date list of wallets managed
  219. // by the hub, and for firing wallet addition/removal events.
  220. func (hub *Hub) updater() {
  221. for {
  222. time.Sleep(refreshCycle)
  223. // Run the wallet refresher
  224. hub.stateLock.Lock()
  225. hub.refreshWallets()
  226. // If all our subscribers left, stop the updater
  227. if hub.updateScope.Count() == 0 {
  228. hub.updating = false
  229. hub.stateLock.Unlock()
  230. return
  231. }
  232. hub.stateLock.Unlock()
  233. }
  234. }