hub.go 9.5 KB

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