hub.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. "reflect"
  37. "sync"
  38. "time"
  39. "github.com/ebfe/scard"
  40. "github.com/ethereum/go-ethereum/accounts"
  41. "github.com/ethereum/go-ethereum/common"
  42. "github.com/ethereum/go-ethereum/common/hexutil"
  43. "github.com/ethereum/go-ethereum/event"
  44. "github.com/ethereum/go-ethereum/log"
  45. )
  46. // Scheme is the URI prefix for smartcard wallets.
  47. const Scheme = "pcsc"
  48. // refreshCycle is the maximum time between wallet refreshes (if USB hotplug
  49. // notifications don't work).
  50. const refreshCycle = 5 * 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 *scard.Context
  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.Mutex // Protects the internals of the hub from racey access
  74. }
  75. var HubType = reflect.TypeOf(&Hub{})
  76. func (hub *Hub) readPairings() error {
  77. hub.pairings = make(map[string]smartcardPairing)
  78. pairingFile, err := os.Open(hub.datadir + "/smartcards.json")
  79. if err != nil {
  80. if os.IsNotExist(err) {
  81. return nil
  82. }
  83. return err
  84. }
  85. pairingData, err := ioutil.ReadAll(pairingFile)
  86. if err != nil {
  87. return err
  88. }
  89. var pairings []smartcardPairing
  90. if err := json.Unmarshal(pairingData, &pairings); err != nil {
  91. return err
  92. }
  93. for _, pairing := range pairings {
  94. hub.pairings[string(pairing.PublicKey)] = pairing
  95. }
  96. return nil
  97. }
  98. func (hub *Hub) writePairings() error {
  99. pairingFile, err := os.OpenFile(hub.datadir+"/smartcards.json", os.O_RDWR|os.O_CREATE, 0755)
  100. if err != nil {
  101. return err
  102. }
  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 pairingFile.Close()
  115. }
  116. func (hub *Hub) getPairing(wallet *Wallet) *smartcardPairing {
  117. pairing, ok := hub.pairings[string(wallet.PublicKey)]
  118. if ok {
  119. return &pairing
  120. }
  121. return nil
  122. }
  123. func (hub *Hub) setPairing(wallet *Wallet, pairing *smartcardPairing) error {
  124. if pairing == nil {
  125. delete(hub.pairings, string(wallet.PublicKey))
  126. } else {
  127. hub.pairings[string(wallet.PublicKey)] = *pairing
  128. }
  129. return hub.writePairings()
  130. }
  131. // NewHub creates a new hardware wallet manager for smartcards.
  132. func NewHub(scheme string, datadir string) (*Hub, error) {
  133. context, err := scard.EstablishContext()
  134. if err != nil {
  135. return nil, err
  136. }
  137. hub := &Hub{
  138. scheme: scheme,
  139. context: context,
  140. datadir: datadir,
  141. wallets: make(map[string]*Wallet),
  142. quit: make(chan chan error),
  143. }
  144. if err := hub.readPairings(); err != nil {
  145. return nil, err
  146. }
  147. hub.refreshWallets()
  148. return hub, nil
  149. }
  150. // Wallets implements accounts.Backend, returning all the currently tracked
  151. // devices that appear to be hardware wallets.
  152. func (hub *Hub) Wallets() []accounts.Wallet {
  153. // Make sure the list of wallets is up to date
  154. hub.stateLock.Lock()
  155. defer hub.stateLock.Unlock()
  156. hub.refreshWallets()
  157. cpy := make([]accounts.Wallet, 0, len(hub.wallets))
  158. for _, wallet := range hub.wallets {
  159. if wallet != nil {
  160. cpy = append(cpy, wallet)
  161. }
  162. }
  163. return cpy
  164. }
  165. // refreshWallets scans the devices attached to the machine and updates the
  166. // list of wallets based on the found devices.
  167. func (hub *Hub) refreshWallets() {
  168. elapsed := time.Since(hub.refreshed)
  169. if elapsed < refreshThrottling {
  170. return
  171. }
  172. readers, err := hub.context.ListReaders()
  173. if err != nil {
  174. log.Error("Error listing readers", "err", err)
  175. }
  176. events := []accounts.WalletEvent{}
  177. seen := make(map[string]struct{})
  178. for _, reader := range readers {
  179. if wallet, ok := hub.wallets[reader]; ok {
  180. // We already know about this card; check it's still present
  181. if err := wallet.ping(); err != nil {
  182. log.Debug("Got error pinging wallet", "reader", reader, "err", err)
  183. } else {
  184. seen[reader] = struct{}{}
  185. }
  186. continue
  187. }
  188. seen[reader] = struct{}{}
  189. card, err := hub.context.Connect(reader, scard.ShareShared, scard.ProtocolAny)
  190. if err != nil {
  191. log.Debug("Error opening card", "reader", reader, "err", err)
  192. continue
  193. }
  194. wallet := NewWallet(hub, card)
  195. err = wallet.connect()
  196. if err != nil {
  197. log.Debug("Error connecting to wallet", "reader", reader, "err", err)
  198. card.Disconnect(scard.LeaveCard)
  199. continue
  200. }
  201. hub.wallets[reader] = wallet
  202. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
  203. log.Info("Found new smartcard wallet", "reader", reader, "publicKey", hexutil.Encode(wallet.PublicKey[:4]))
  204. }
  205. // Remove any wallets we no longer see
  206. for k, wallet := range hub.wallets {
  207. if _, ok := seen[k]; !ok {
  208. log.Info("Wallet disconnected", "pubkey", hexutil.Encode(wallet.PublicKey[:4]), "reader", k)
  209. wallet.Close()
  210. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
  211. delete(hub.wallets, k)
  212. }
  213. }
  214. for _, event := range events {
  215. hub.updateFeed.Send(event)
  216. }
  217. hub.refreshed = time.Now()
  218. }
  219. // Subscribe implements accounts.Backend, creating an async subscription to
  220. // receive notifications on the addition or removal of wallets.
  221. func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
  222. // We need the mutex to reliably start/stop the update loop
  223. hub.stateLock.Lock()
  224. defer hub.stateLock.Unlock()
  225. // Subscribe the caller and track the subscriber count
  226. sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink))
  227. // Subscribers require an active notification loop, start it
  228. if !hub.updating {
  229. hub.updating = true
  230. go hub.updater()
  231. }
  232. return sub
  233. }
  234. // updater is responsible for maintaining an up-to-date list of wallets managed
  235. // by the hub, and for firing wallet addition/removal events.
  236. func (hub *Hub) updater() {
  237. for {
  238. time.Sleep(refreshCycle)
  239. // Run the wallet refresher
  240. hub.stateLock.Lock()
  241. hub.refreshWallets()
  242. // If all our subscribers left, stop the updater
  243. if hub.updateScope.Count() == 0 {
  244. hub.updating = false
  245. hub.stateLock.Unlock()
  246. return
  247. }
  248. hub.stateLock.Unlock()
  249. }
  250. }