wallet.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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. "bytes"
  19. "context"
  20. "crypto/hmac"
  21. "crypto/sha256"
  22. "crypto/sha512"
  23. "encoding/asn1"
  24. "encoding/binary"
  25. "errors"
  26. "fmt"
  27. "math/big"
  28. "regexp"
  29. "sort"
  30. "strings"
  31. "sync"
  32. "time"
  33. "github.com/ethereum/go-ethereum"
  34. "github.com/ethereum/go-ethereum/accounts"
  35. "github.com/ethereum/go-ethereum/common"
  36. "github.com/ethereum/go-ethereum/core/types"
  37. "github.com/ethereum/go-ethereum/crypto"
  38. "github.com/ethereum/go-ethereum/log"
  39. pcsc "github.com/gballet/go-libpcsclite"
  40. "github.com/status-im/keycard-go/derivationpath"
  41. )
  42. // ErrPairingPasswordNeeded is returned if opening the smart card requires pairing with a pairing
  43. // password. In this case, the calling application should request user input to enter
  44. // the pairing password and send it back.
  45. var ErrPairingPasswordNeeded = errors.New("smartcard: pairing password needed")
  46. // ErrPINNeeded is returned if opening the smart card requires a PIN code. In
  47. // this case, the calling application should request user input to enter the PIN
  48. // and send it back.
  49. var ErrPINNeeded = errors.New("smartcard: pin needed")
  50. // ErrPINUnblockNeeded is returned if opening the smart card requires a PIN code,
  51. // but all PIN attempts have already been exhausted. In this case the calling
  52. // application should request user input for the PUK and a new PIN code to set
  53. // fo the card.
  54. var ErrPINUnblockNeeded = errors.New("smartcard: pin unblock needed")
  55. // ErrAlreadyOpen is returned if the smart card is attempted to be opened, but
  56. // there is already a paired and unlocked session.
  57. var ErrAlreadyOpen = errors.New("smartcard: already open")
  58. // ErrPubkeyMismatch is returned if the public key recovered from a signature
  59. // does not match the one expected by the user.
  60. var ErrPubkeyMismatch = errors.New("smartcard: recovered public key mismatch")
  61. var (
  62. appletAID = []byte{0xA0, 0x00, 0x00, 0x08, 0x04, 0x00, 0x01, 0x01, 0x01}
  63. // DerivationSignatureHash is used to derive the public key from the signature of this hash
  64. DerivationSignatureHash = sha256.Sum256(common.Hash{}.Bytes())
  65. )
  66. // List of APDU command-related constants
  67. const (
  68. claISO7816 = 0
  69. claSCWallet = 0x80
  70. insSelect = 0xA4
  71. insGetResponse = 0xC0
  72. sw1GetResponse = 0x61
  73. sw1Ok = 0x90
  74. insVerifyPin = 0x20
  75. insUnblockPin = 0x22
  76. insExportKey = 0xC2
  77. insSign = 0xC0
  78. insLoadKey = 0xD0
  79. insDeriveKey = 0xD1
  80. insStatus = 0xF2
  81. )
  82. // List of ADPU command parameters
  83. const (
  84. P1DeriveKeyFromMaster = uint8(0x00)
  85. P1DeriveKeyFromParent = uint8(0x01)
  86. P1DeriveKeyFromCurrent = uint8(0x10)
  87. statusP1WalletStatus = uint8(0x00)
  88. statusP1Path = uint8(0x01)
  89. signP1PrecomputedHash = uint8(0x01)
  90. signP2OnlyBlock = uint8(0x81)
  91. exportP1Any = uint8(0x00)
  92. exportP2Pubkey = uint8(0x01)
  93. )
  94. // Minimum time to wait between self derivation attempts, even it the user is
  95. // requesting accounts like crazy.
  96. const selfDeriveThrottling = time.Second
  97. // Wallet represents a smartcard wallet instance.
  98. type Wallet struct {
  99. Hub *Hub // A handle to the Hub that instantiated this wallet.
  100. PublicKey []byte // The wallet's public key (used for communication and identification, not signing!)
  101. lock sync.Mutex // Lock that gates access to struct fields and communication with the card
  102. card *pcsc.Card // A handle to the smartcard interface for the wallet.
  103. session *Session // The secure communication session with the card
  104. log log.Logger // Contextual logger to tag the base with its id
  105. deriveNextPaths []accounts.DerivationPath // Next derivation paths for account auto-discovery (multiple bases supported)
  106. deriveNextAddrs []common.Address // Next derived account addresses for auto-discovery (multiple bases supported)
  107. deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with
  108. deriveReq chan chan struct{} // Channel to request a self-derivation on
  109. deriveQuit chan chan error // Channel to terminate the self-deriver with
  110. }
  111. // NewWallet constructs and returns a new Wallet instance.
  112. func NewWallet(hub *Hub, card *pcsc.Card) *Wallet {
  113. wallet := &Wallet{
  114. Hub: hub,
  115. card: card,
  116. }
  117. return wallet
  118. }
  119. // transmit sends an APDU to the smartcard and receives and decodes the response.
  120. // It automatically handles requests by the card to fetch the return data separately,
  121. // and returns an error if the response status code is not success.
  122. func transmit(card *pcsc.Card, command *commandAPDU) (*responseAPDU, error) {
  123. data, err := command.serialize()
  124. if err != nil {
  125. return nil, err
  126. }
  127. responseData, _, err := card.Transmit(data)
  128. if err != nil {
  129. return nil, err
  130. }
  131. response := new(responseAPDU)
  132. if err = response.deserialize(responseData); err != nil {
  133. return nil, err
  134. }
  135. // Are we being asked to fetch the response separately?
  136. if response.Sw1 == sw1GetResponse && (command.Cla != claISO7816 || command.Ins != insGetResponse) {
  137. return transmit(card, &commandAPDU{
  138. Cla: claISO7816,
  139. Ins: insGetResponse,
  140. P1: 0,
  141. P2: 0,
  142. Data: nil,
  143. Le: response.Sw2,
  144. })
  145. }
  146. if response.Sw1 != sw1Ok {
  147. return nil, fmt.Errorf("unexpected insecure response status Cla=0x%x, Ins=0x%x, Sw=0x%x%x", command.Cla, command.Ins, response.Sw1, response.Sw2)
  148. }
  149. return response, nil
  150. }
  151. // applicationInfo encodes information about the smartcard application - its
  152. // instance UID and public key.
  153. type applicationInfo struct {
  154. InstanceUID []byte `asn1:"tag:15"`
  155. PublicKey []byte `asn1:"tag:0"`
  156. }
  157. // connect connects to the wallet application and establishes a secure channel with it.
  158. // must be called before any other interaction with the wallet.
  159. func (w *Wallet) connect() error {
  160. w.lock.Lock()
  161. defer w.lock.Unlock()
  162. appinfo, err := w.doselect()
  163. if err != nil {
  164. return err
  165. }
  166. channel, err := NewSecureChannelSession(w.card, appinfo.PublicKey)
  167. if err != nil {
  168. return err
  169. }
  170. w.PublicKey = appinfo.PublicKey
  171. w.log = log.New("url", w.URL())
  172. w.session = &Session{
  173. Wallet: w,
  174. Channel: channel,
  175. }
  176. return nil
  177. }
  178. // doselect is an internal (unlocked) function to send a SELECT APDU to the card.
  179. func (w *Wallet) doselect() (*applicationInfo, error) {
  180. response, err := transmit(w.card, &commandAPDU{
  181. Cla: claISO7816,
  182. Ins: insSelect,
  183. P1: 4,
  184. P2: 0,
  185. Data: appletAID,
  186. })
  187. if err != nil {
  188. return nil, err
  189. }
  190. appinfo := new(applicationInfo)
  191. if _, err := asn1.UnmarshalWithParams(response.Data, appinfo, "tag:4"); err != nil {
  192. return nil, err
  193. }
  194. return appinfo, nil
  195. }
  196. // ping checks the card's status and returns an error if unsuccessful.
  197. func (w *Wallet) ping() error {
  198. w.lock.Lock()
  199. defer w.lock.Unlock()
  200. // We can't ping if not paired
  201. if !w.session.paired() {
  202. return nil
  203. }
  204. if _, err := w.session.walletStatus(); err != nil {
  205. return err
  206. }
  207. return nil
  208. }
  209. // release releases any resources held by an open wallet instance.
  210. func (w *Wallet) release() error {
  211. if w.session != nil {
  212. return w.session.release()
  213. }
  214. return nil
  215. }
  216. // pair is an internal (unlocked) function for establishing a new pairing
  217. // with the wallet.
  218. func (w *Wallet) pair(puk []byte) error {
  219. if w.session.paired() {
  220. return fmt.Errorf("wallet already paired")
  221. }
  222. pairing, err := w.session.pair(puk)
  223. if err != nil {
  224. return err
  225. }
  226. if err = w.Hub.setPairing(w, &pairing); err != nil {
  227. return err
  228. }
  229. return w.session.authenticate(pairing)
  230. }
  231. // Unpair deletes an existing wallet pairing.
  232. func (w *Wallet) Unpair(pin []byte) error {
  233. w.lock.Lock()
  234. defer w.lock.Unlock()
  235. if !w.session.paired() {
  236. return fmt.Errorf("wallet %x not paired", w.PublicKey)
  237. }
  238. if err := w.session.verifyPin(pin); err != nil {
  239. return fmt.Errorf("failed to verify pin: %s", err)
  240. }
  241. if err := w.session.unpair(); err != nil {
  242. return fmt.Errorf("failed to unpair: %s", err)
  243. }
  244. if err := w.Hub.setPairing(w, nil); err != nil {
  245. return err
  246. }
  247. return nil
  248. }
  249. // URL retrieves the canonical path under which this wallet is reachable. It is
  250. // user by upper layers to define a sorting order over all wallets from multiple
  251. // backends.
  252. func (w *Wallet) URL() accounts.URL {
  253. return accounts.URL{
  254. Scheme: w.Hub.scheme,
  255. Path: fmt.Sprintf("%x", w.PublicKey[1:5]), // Byte #0 isn't unique; 1:5 covers << 64K cards, bump to 1:9 for << 4M
  256. }
  257. }
  258. // Status returns a textual status to aid the user in the current state of the
  259. // wallet. It also returns an error indicating any failure the wallet might have
  260. // encountered.
  261. func (w *Wallet) Status() (string, error) {
  262. w.lock.Lock()
  263. defer w.lock.Unlock()
  264. // If the card is not paired, we can only wait
  265. if !w.session.paired() {
  266. return "Unpaired, waiting for pairing password", nil
  267. }
  268. // Yay, we have an encrypted session, retrieve the actual status
  269. status, err := w.session.walletStatus()
  270. if err != nil {
  271. return fmt.Sprintf("Failed: %v", err), err
  272. }
  273. switch {
  274. case !w.session.verified && status.PinRetryCount == 0 && status.PukRetryCount == 0:
  275. return "Bricked, waiting for full wipe", nil
  276. case !w.session.verified && status.PinRetryCount == 0:
  277. return fmt.Sprintf("Blocked, waiting for PUK (%d attempts left) and new PIN", status.PukRetryCount), nil
  278. case !w.session.verified:
  279. return fmt.Sprintf("Locked, waiting for PIN (%d attempts left)", status.PinRetryCount), nil
  280. case !status.Initialized:
  281. return "Empty, waiting for initialization", nil
  282. default:
  283. return "Online", nil
  284. }
  285. }
  286. // Open initializes access to a wallet instance. It is not meant to unlock or
  287. // decrypt account keys, rather simply to establish a connection to hardware
  288. // wallets and/or to access derivation seeds.
  289. //
  290. // The passphrase parameter may or may not be used by the implementation of a
  291. // particular wallet instance. The reason there is no passwordless open method
  292. // is to strive towards a uniform wallet handling, oblivious to the different
  293. // backend providers.
  294. //
  295. // Please note, if you open a wallet, you must close it to release any allocated
  296. // resources (especially important when working with hardware wallets).
  297. func (w *Wallet) Open(passphrase string) error {
  298. w.lock.Lock()
  299. defer w.lock.Unlock()
  300. // If the session is already open, bail out
  301. if w.session.verified {
  302. return ErrAlreadyOpen
  303. }
  304. // If the smart card is not yet paired, attempt to do so either from a previous
  305. // pairing key or form the supplied PUK code.
  306. if !w.session.paired() {
  307. // If a previous pairing exists, only ever try to use that
  308. if pairing := w.Hub.pairing(w); pairing != nil {
  309. if err := w.session.authenticate(*pairing); err != nil {
  310. return fmt.Errorf("failed to authenticate card %x: %s", w.PublicKey[:4], err)
  311. }
  312. // Pairing still ok, fall through to PIN checks
  313. } else {
  314. // If no passphrase was supplied, request the PUK from the user
  315. if passphrase == "" {
  316. return ErrPairingPasswordNeeded
  317. }
  318. // Attempt to pair the smart card with the user supplied PUK
  319. if err := w.pair([]byte(passphrase)); err != nil {
  320. return err
  321. }
  322. // Pairing succeeded, fall through to PIN checks. This will of course fail,
  323. // but we can't return ErrPINNeeded directly here because we don't know whether
  324. // a PIN check or a PIN reset is needed.
  325. passphrase = ""
  326. }
  327. }
  328. // The smart card was successfully paired, retrieve its status to check whether
  329. // PIN verification or unblocking is needed.
  330. status, err := w.session.walletStatus()
  331. if err != nil {
  332. return err
  333. }
  334. // Request the appropriate next authentication data, or use the one supplied
  335. switch {
  336. case passphrase == "" && status.PinRetryCount > 0:
  337. return ErrPINNeeded
  338. case passphrase == "":
  339. return ErrPINUnblockNeeded
  340. case status.PinRetryCount > 0:
  341. if !regexp.MustCompile(`^[0-9]{6,}$`).MatchString(passphrase) {
  342. w.log.Error("PIN needs to be at least 6 digits")
  343. return ErrPINNeeded
  344. }
  345. if err := w.session.verifyPin([]byte(passphrase)); err != nil {
  346. return err
  347. }
  348. default:
  349. if !regexp.MustCompile(`^[0-9]{12,}$`).MatchString(passphrase) {
  350. w.log.Error("PUK needs to be at least 12 digits")
  351. return ErrPINUnblockNeeded
  352. }
  353. if err := w.session.unblockPin([]byte(passphrase)); err != nil {
  354. return err
  355. }
  356. }
  357. // Smart card paired and unlocked, initialize and register
  358. w.deriveReq = make(chan chan struct{})
  359. w.deriveQuit = make(chan chan error)
  360. go w.selfDerive()
  361. // Notify anyone listening for wallet events that a new device is accessible
  362. go w.Hub.updateFeed.Send(accounts.WalletEvent{Wallet: w, Kind: accounts.WalletOpened})
  363. return nil
  364. }
  365. // Close stops and closes the wallet, freeing any resources.
  366. func (w *Wallet) Close() error {
  367. // Ensure the wallet was opened
  368. w.lock.Lock()
  369. dQuit := w.deriveQuit
  370. w.lock.Unlock()
  371. // Terminate the self-derivations
  372. var derr error
  373. if dQuit != nil {
  374. errc := make(chan error)
  375. dQuit <- errc
  376. derr = <-errc // Save for later, we *must* close the USB
  377. }
  378. // Terminate the device connection
  379. w.lock.Lock()
  380. defer w.lock.Unlock()
  381. w.deriveQuit = nil
  382. w.deriveReq = nil
  383. if err := w.release(); err != nil {
  384. return err
  385. }
  386. return derr
  387. }
  388. // selfDerive is an account derivation loop that upon request attempts to find
  389. // new non-zero accounts.
  390. func (w *Wallet) selfDerive() {
  391. w.log.Debug("Smart card wallet self-derivation started")
  392. defer w.log.Debug("Smart card wallet self-derivation stopped")
  393. // Execute self-derivations until termination or error
  394. var (
  395. reqc chan struct{}
  396. errc chan error
  397. err error
  398. )
  399. for errc == nil && err == nil {
  400. // Wait until either derivation or termination is requested
  401. select {
  402. case errc = <-w.deriveQuit:
  403. // Termination requested
  404. continue
  405. case reqc = <-w.deriveReq:
  406. // Account discovery requested
  407. }
  408. // Derivation needs a chain and device access, skip if either unavailable
  409. w.lock.Lock()
  410. if w.session == nil || w.deriveChain == nil {
  411. w.lock.Unlock()
  412. reqc <- struct{}{}
  413. continue
  414. }
  415. pairing := w.Hub.pairing(w)
  416. // Device lock obtained, derive the next batch of accounts
  417. var (
  418. paths []accounts.DerivationPath
  419. nextAcc accounts.Account
  420. nextPaths = append([]accounts.DerivationPath{}, w.deriveNextPaths...)
  421. nextAddrs = append([]common.Address{}, w.deriveNextAddrs...)
  422. context = context.Background()
  423. )
  424. for i := 0; i < len(nextAddrs); i++ {
  425. for empty := false; !empty; {
  426. // Retrieve the next derived Ethereum account
  427. if nextAddrs[i] == (common.Address{}) {
  428. if nextAcc, err = w.session.derive(nextPaths[i]); err != nil {
  429. w.log.Warn("Smartcard wallet account derivation failed", "err", err)
  430. break
  431. }
  432. nextAddrs[i] = nextAcc.Address
  433. }
  434. // Check the account's status against the current chain state
  435. var (
  436. balance *big.Int
  437. nonce uint64
  438. )
  439. balance, err = w.deriveChain.BalanceAt(context, nextAddrs[i], nil)
  440. if err != nil {
  441. w.log.Warn("Smartcard wallet balance retrieval failed", "err", err)
  442. break
  443. }
  444. nonce, err = w.deriveChain.NonceAt(context, nextAddrs[i], nil)
  445. if err != nil {
  446. w.log.Warn("Smartcard wallet nonce retrieval failed", "err", err)
  447. break
  448. }
  449. // If the next account is empty, stop self-derivation, but add for the last base path
  450. if balance.Sign() == 0 && nonce == 0 {
  451. empty = true
  452. if i < len(nextAddrs)-1 {
  453. break
  454. }
  455. }
  456. // We've just self-derived a new account, start tracking it locally
  457. path := make(accounts.DerivationPath, len(nextPaths[i]))
  458. copy(path[:], nextPaths[i][:])
  459. paths = append(paths, path)
  460. // Display a log message to the user for new (or previously empty accounts)
  461. if _, known := pairing.Accounts[nextAddrs[i]]; !known || !empty || nextAddrs[i] != w.deriveNextAddrs[i] {
  462. w.log.Info("Smartcard wallet discovered new account", "address", nextAddrs[i], "path", path, "balance", balance, "nonce", nonce)
  463. }
  464. pairing.Accounts[nextAddrs[i]] = path
  465. // Fetch the next potential account
  466. if !empty {
  467. nextAddrs[i] = common.Address{}
  468. nextPaths[i][len(nextPaths[i])-1]++
  469. }
  470. }
  471. }
  472. // If there are new accounts, write them out
  473. if len(paths) > 0 {
  474. err = w.Hub.setPairing(w, pairing)
  475. }
  476. // Shift the self-derivation forward
  477. w.deriveNextAddrs = nextAddrs
  478. w.deriveNextPaths = nextPaths
  479. // Self derivation complete, release device lock
  480. w.lock.Unlock()
  481. // Notify the user of termination and loop after a bit of time (to avoid trashing)
  482. reqc <- struct{}{}
  483. if err == nil {
  484. select {
  485. case errc = <-w.deriveQuit:
  486. // Termination requested, abort
  487. case <-time.After(selfDeriveThrottling):
  488. // Waited enough, willing to self-derive again
  489. }
  490. }
  491. }
  492. // In case of error, wait for termination
  493. if err != nil {
  494. w.log.Debug("Smartcard wallet self-derivation failed", "err", err)
  495. errc = <-w.deriveQuit
  496. }
  497. errc <- err
  498. }
  499. // Accounts retrieves the list of signing accounts the wallet is currently aware
  500. // of. For hierarchical deterministic wallets, the list will not be exhaustive,
  501. // rather only contain the accounts explicitly pinned during account derivation.
  502. func (w *Wallet) Accounts() []accounts.Account {
  503. // Attempt self-derivation if it's running
  504. reqc := make(chan struct{}, 1)
  505. select {
  506. case w.deriveReq <- reqc:
  507. // Self-derivation request accepted, wait for it
  508. <-reqc
  509. default:
  510. // Self-derivation offline, throttled or busy, skip
  511. }
  512. w.lock.Lock()
  513. defer w.lock.Unlock()
  514. if pairing := w.Hub.pairing(w); pairing != nil {
  515. ret := make([]accounts.Account, 0, len(pairing.Accounts))
  516. for address, path := range pairing.Accounts {
  517. ret = append(ret, w.makeAccount(address, path))
  518. }
  519. sort.Sort(accounts.AccountsByURL(ret))
  520. return ret
  521. }
  522. return nil
  523. }
  524. func (w *Wallet) makeAccount(address common.Address, path accounts.DerivationPath) accounts.Account {
  525. return accounts.Account{
  526. Address: address,
  527. URL: accounts.URL{
  528. Scheme: w.Hub.scheme,
  529. Path: fmt.Sprintf("%x/%s", w.PublicKey[1:3], path.String()),
  530. },
  531. }
  532. }
  533. // Contains returns whether an account is part of this particular wallet or not.
  534. func (w *Wallet) Contains(account accounts.Account) bool {
  535. if pairing := w.Hub.pairing(w); pairing != nil {
  536. _, ok := pairing.Accounts[account.Address]
  537. return ok
  538. }
  539. return false
  540. }
  541. // Initialize installs a keypair generated from the provided key into the wallet.
  542. func (w *Wallet) Initialize(seed []byte) error {
  543. go w.selfDerive()
  544. // DO NOT lock at this stage, as the initialize
  545. // function relies on Status()
  546. return w.session.initialize(seed)
  547. }
  548. // Derive attempts to explicitly derive a hierarchical deterministic account at
  549. // the specified derivation path. If requested, the derived account will be added
  550. // to the wallet's tracked account list.
  551. func (w *Wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
  552. w.lock.Lock()
  553. defer w.lock.Unlock()
  554. account, err := w.session.derive(path)
  555. if err != nil {
  556. return accounts.Account{}, err
  557. }
  558. if pin {
  559. pairing := w.Hub.pairing(w)
  560. pairing.Accounts[account.Address] = path
  561. if err := w.Hub.setPairing(w, pairing); err != nil {
  562. return accounts.Account{}, err
  563. }
  564. }
  565. return account, nil
  566. }
  567. // SelfDerive sets a base account derivation path from which the wallet attempts
  568. // to discover non zero accounts and automatically add them to list of tracked
  569. // accounts.
  570. //
  571. // Note, self derivation will increment the last component of the specified path
  572. // opposed to decending into a child path to allow discovering accounts starting
  573. // from non zero components.
  574. //
  575. // Some hardware wallets switched derivation paths through their evolution, so
  576. // this method supports providing multiple bases to discover old user accounts
  577. // too. Only the last base will be used to derive the next empty account.
  578. //
  579. // You can disable automatic account discovery by calling SelfDerive with a nil
  580. // chain state reader.
  581. func (w *Wallet) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) {
  582. w.lock.Lock()
  583. defer w.lock.Unlock()
  584. w.deriveNextPaths = make([]accounts.DerivationPath, len(bases))
  585. for i, base := range bases {
  586. w.deriveNextPaths[i] = make(accounts.DerivationPath, len(base))
  587. copy(w.deriveNextPaths[i][:], base[:])
  588. }
  589. w.deriveNextAddrs = make([]common.Address, len(bases))
  590. w.deriveChain = chain
  591. }
  592. // SignData requests the wallet to sign the hash of the given data.
  593. //
  594. // It looks up the account specified either solely via its address contained within,
  595. // or optionally with the aid of any location metadata from the embedded URL field.
  596. //
  597. // If the wallet requires additional authentication to sign the request (e.g.
  598. // a password to decrypt the account, or a PIN code o verify the transaction),
  599. // an AuthNeededError instance will be returned, containing infos for the user
  600. // about which fields or actions are needed. The user may retry by providing
  601. // the needed details via SignDataWithPassphrase, or by other means (e.g. unlock
  602. // the account in a keystore).
  603. func (w *Wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
  604. return w.signHash(account, crypto.Keccak256(data))
  605. }
  606. func (w *Wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
  607. w.lock.Lock()
  608. defer w.lock.Unlock()
  609. path, err := w.findAccountPath(account)
  610. if err != nil {
  611. return nil, err
  612. }
  613. return w.session.sign(path, hash)
  614. }
  615. // SignTx requests the wallet to sign the given transaction.
  616. //
  617. // It looks up the account specified either solely via its address contained within,
  618. // or optionally with the aid of any location metadata from the embedded URL field.
  619. //
  620. // If the wallet requires additional authentication to sign the request (e.g.
  621. // a password to decrypt the account, or a PIN code o verify the transaction),
  622. // an AuthNeededError instance will be returned, containing infos for the user
  623. // about which fields or actions are needed. The user may retry by providing
  624. // the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
  625. // the account in a keystore).
  626. func (w *Wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  627. signer := types.LatestSignerForChainID(chainID)
  628. hash := signer.Hash(tx)
  629. sig, err := w.signHash(account, hash[:])
  630. if err != nil {
  631. return nil, err
  632. }
  633. return tx.WithSignature(signer, sig)
  634. }
  635. // SignDataWithPassphrase requests the wallet to sign the given hash with the
  636. // given passphrase as extra authentication information.
  637. //
  638. // It looks up the account specified either solely via its address contained within,
  639. // or optionally with the aid of any location metadata from the embedded URL field.
  640. func (w *Wallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
  641. return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(data))
  642. }
  643. func (w *Wallet) signHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) {
  644. if !w.session.verified {
  645. if err := w.Open(passphrase); err != nil {
  646. return nil, err
  647. }
  648. }
  649. return w.signHash(account, hash)
  650. }
  651. // SignText requests the wallet to sign the hash of a given piece of data, prefixed
  652. // by the Ethereum prefix scheme
  653. // It looks up the account specified either solely via its address contained within,
  654. // or optionally with the aid of any location metadata from the embedded URL field.
  655. //
  656. // If the wallet requires additional authentication to sign the request (e.g.
  657. // a password to decrypt the account, or a PIN code o verify the transaction),
  658. // an AuthNeededError instance will be returned, containing infos for the user
  659. // about which fields or actions are needed. The user may retry by providing
  660. // the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
  661. // the account in a keystore).
  662. func (w *Wallet) SignText(account accounts.Account, text []byte) ([]byte, error) {
  663. return w.signHash(account, accounts.TextHash(text))
  664. }
  665. // SignTextWithPassphrase implements accounts.Wallet, attempting to sign the
  666. // given hash with the given account using passphrase as extra authentication
  667. func (w *Wallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
  668. return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(accounts.TextHash(text)))
  669. }
  670. // SignTxWithPassphrase requests the wallet to sign the given transaction, with the
  671. // given passphrase as extra authentication information.
  672. //
  673. // It looks up the account specified either solely via its address contained within,
  674. // or optionally with the aid of any location metadata from the embedded URL field.
  675. func (w *Wallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  676. if !w.session.verified {
  677. if err := w.Open(passphrase); err != nil {
  678. return nil, err
  679. }
  680. }
  681. return w.SignTx(account, tx, chainID)
  682. }
  683. // findAccountPath returns the derivation path for the provided account.
  684. // It first checks for the address in the list of pinned accounts, and if it is
  685. // not found, attempts to parse the derivation path from the account's URL.
  686. func (w *Wallet) findAccountPath(account accounts.Account) (accounts.DerivationPath, error) {
  687. pairing := w.Hub.pairing(w)
  688. if path, ok := pairing.Accounts[account.Address]; ok {
  689. return path, nil
  690. }
  691. // Look for the path in the URL
  692. if account.URL.Scheme != w.Hub.scheme {
  693. return nil, fmt.Errorf("scheme %s does not match wallet scheme %s", account.URL.Scheme, w.Hub.scheme)
  694. }
  695. parts := strings.SplitN(account.URL.Path, "/", 2)
  696. if len(parts) != 2 {
  697. return nil, fmt.Errorf("invalid URL format: %s", account.URL)
  698. }
  699. if parts[0] != fmt.Sprintf("%x", w.PublicKey[1:3]) {
  700. return nil, fmt.Errorf("URL %s is not for this wallet", account.URL)
  701. }
  702. return accounts.ParseDerivationPath(parts[1])
  703. }
  704. // Session represents a secured communication session with the wallet.
  705. type Session struct {
  706. Wallet *Wallet // A handle to the wallet that opened the session
  707. Channel *SecureChannelSession // A secure channel for encrypted messages
  708. verified bool // Whether the pin has been verified in this session.
  709. }
  710. // pair establishes a new pairing over this channel, using the provided secret.
  711. func (s *Session) pair(secret []byte) (smartcardPairing, error) {
  712. err := s.Channel.Pair(secret)
  713. if err != nil {
  714. return smartcardPairing{}, err
  715. }
  716. return smartcardPairing{
  717. PublicKey: s.Wallet.PublicKey,
  718. PairingIndex: s.Channel.PairingIndex,
  719. PairingKey: s.Channel.PairingKey,
  720. Accounts: make(map[common.Address]accounts.DerivationPath),
  721. }, nil
  722. }
  723. // unpair deletes an existing pairing.
  724. func (s *Session) unpair() error {
  725. if !s.verified {
  726. return fmt.Errorf("unpair requires that the PIN be verified")
  727. }
  728. return s.Channel.Unpair()
  729. }
  730. // verifyPin unlocks a wallet with the provided pin.
  731. func (s *Session) verifyPin(pin []byte) error {
  732. if _, err := s.Channel.transmitEncrypted(claSCWallet, insVerifyPin, 0, 0, pin); err != nil {
  733. return err
  734. }
  735. s.verified = true
  736. return nil
  737. }
  738. // unblockPin unblocks a wallet with the provided puk and resets the pin to the
  739. // new one specified.
  740. func (s *Session) unblockPin(pukpin []byte) error {
  741. if _, err := s.Channel.transmitEncrypted(claSCWallet, insUnblockPin, 0, 0, pukpin); err != nil {
  742. return err
  743. }
  744. s.verified = true
  745. return nil
  746. }
  747. // release releases resources associated with the channel.
  748. func (s *Session) release() error {
  749. return s.Wallet.card.Disconnect(pcsc.LeaveCard)
  750. }
  751. // paired returns true if a valid pairing exists.
  752. func (s *Session) paired() bool {
  753. return s.Channel.PairingKey != nil
  754. }
  755. // authenticate uses an existing pairing to establish a secure channel.
  756. func (s *Session) authenticate(pairing smartcardPairing) error {
  757. if !bytes.Equal(s.Wallet.PublicKey, pairing.PublicKey) {
  758. return fmt.Errorf("cannot pair using another wallet's pairing; %x != %x", s.Wallet.PublicKey, pairing.PublicKey)
  759. }
  760. s.Channel.PairingKey = pairing.PairingKey
  761. s.Channel.PairingIndex = pairing.PairingIndex
  762. return s.Channel.Open()
  763. }
  764. // walletStatus describes a smartcard wallet's status information.
  765. type walletStatus struct {
  766. PinRetryCount int // Number of remaining PIN retries
  767. PukRetryCount int // Number of remaining PUK retries
  768. Initialized bool // Whether the card has been initialized with a private key
  769. }
  770. // walletStatus fetches the wallet's status from the card.
  771. func (s *Session) walletStatus() (*walletStatus, error) {
  772. response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1WalletStatus, 0, nil)
  773. if err != nil {
  774. return nil, err
  775. }
  776. status := new(walletStatus)
  777. if _, err := asn1.UnmarshalWithParams(response.Data, status, "tag:3"); err != nil {
  778. return nil, err
  779. }
  780. return status, nil
  781. }
  782. // derivationPath fetches the wallet's current derivation path from the card.
  783. //lint:ignore U1000 needs to be added to the console interface
  784. func (s *Session) derivationPath() (accounts.DerivationPath, error) {
  785. response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1Path, 0, nil)
  786. if err != nil {
  787. return nil, err
  788. }
  789. buf := bytes.NewReader(response.Data)
  790. path := make(accounts.DerivationPath, len(response.Data)/4)
  791. return path, binary.Read(buf, binary.BigEndian, &path)
  792. }
  793. // initializeData contains data needed to initialize the smartcard wallet.
  794. type initializeData struct {
  795. PublicKey []byte `asn1:"tag:0"`
  796. PrivateKey []byte `asn1:"tag:1"`
  797. ChainCode []byte `asn1:"tag:2"`
  798. }
  799. // initialize initializes the card with new key data.
  800. func (s *Session) initialize(seed []byte) error {
  801. // Check that the wallet isn't currently initialized,
  802. // otherwise the key would be overwritten.
  803. status, err := s.Wallet.Status()
  804. if err != nil {
  805. return err
  806. }
  807. if status == "Online" {
  808. return fmt.Errorf("card is already initialized, cowardly refusing to proceed")
  809. }
  810. s.Wallet.lock.Lock()
  811. defer s.Wallet.lock.Unlock()
  812. // HMAC the seed to produce the private key and chain code
  813. mac := hmac.New(sha512.New, []byte("Bitcoin seed"))
  814. mac.Write(seed)
  815. seed = mac.Sum(nil)
  816. key, err := crypto.ToECDSA(seed[:32])
  817. if err != nil {
  818. return err
  819. }
  820. id := initializeData{}
  821. id.PublicKey = crypto.FromECDSAPub(&key.PublicKey)
  822. id.PrivateKey = seed[:32]
  823. id.ChainCode = seed[32:]
  824. data, err := asn1.Marshal(id)
  825. if err != nil {
  826. return err
  827. }
  828. // Nasty hack to force the top-level struct tag to be context-specific
  829. data[0] = 0xA1
  830. _, err = s.Channel.transmitEncrypted(claSCWallet, insLoadKey, 0x02, 0, data)
  831. return err
  832. }
  833. // derive derives a new HD key path on the card.
  834. func (s *Session) derive(path accounts.DerivationPath) (accounts.Account, error) {
  835. startingPoint, path, err := derivationpath.Decode(path.String())
  836. if err != nil {
  837. return accounts.Account{}, err
  838. }
  839. var p1 uint8
  840. switch startingPoint {
  841. case derivationpath.StartingPointMaster:
  842. p1 = P1DeriveKeyFromMaster
  843. case derivationpath.StartingPointParent:
  844. p1 = P1DeriveKeyFromParent
  845. case derivationpath.StartingPointCurrent:
  846. p1 = P1DeriveKeyFromCurrent
  847. default:
  848. return accounts.Account{}, fmt.Errorf("invalid startingPoint %d", startingPoint)
  849. }
  850. data := new(bytes.Buffer)
  851. for _, segment := range path {
  852. if err := binary.Write(data, binary.BigEndian, segment); err != nil {
  853. return accounts.Account{}, err
  854. }
  855. }
  856. _, err = s.Channel.transmitEncrypted(claSCWallet, insDeriveKey, p1, 0, data.Bytes())
  857. if err != nil {
  858. return accounts.Account{}, err
  859. }
  860. response, err := s.Channel.transmitEncrypted(claSCWallet, insSign, 0, 0, DerivationSignatureHash[:])
  861. if err != nil {
  862. return accounts.Account{}, err
  863. }
  864. sigdata := new(signatureData)
  865. if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil {
  866. return accounts.Account{}, err
  867. }
  868. rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes()
  869. sig := make([]byte, 65)
  870. copy(sig[32-len(rbytes):32], rbytes)
  871. copy(sig[64-len(sbytes):64], sbytes)
  872. if err := confirmPublicKey(sig, sigdata.PublicKey); err != nil {
  873. return accounts.Account{}, err
  874. }
  875. pub, err := crypto.UnmarshalPubkey(sigdata.PublicKey)
  876. if err != nil {
  877. return accounts.Account{}, err
  878. }
  879. return s.Wallet.makeAccount(crypto.PubkeyToAddress(*pub), path), nil
  880. }
  881. // keyExport contains information on an exported keypair.
  882. //lint:ignore U1000 needs to be added to the console interface
  883. type keyExport struct {
  884. PublicKey []byte `asn1:"tag:0"`
  885. PrivateKey []byte `asn1:"tag:1,optional"`
  886. }
  887. // publicKey returns the public key for the current derivation path.
  888. //lint:ignore U1000 needs to be added to the console interface
  889. func (s *Session) publicKey() ([]byte, error) {
  890. response, err := s.Channel.transmitEncrypted(claSCWallet, insExportKey, exportP1Any, exportP2Pubkey, nil)
  891. if err != nil {
  892. return nil, err
  893. }
  894. keys := new(keyExport)
  895. if _, err := asn1.UnmarshalWithParams(response.Data, keys, "tag:1"); err != nil {
  896. return nil, err
  897. }
  898. return keys.PublicKey, nil
  899. }
  900. // signatureData contains information on a signature - the signature itself and
  901. // the corresponding public key.
  902. type signatureData struct {
  903. PublicKey []byte `asn1:"tag:0"`
  904. Signature struct {
  905. R *big.Int
  906. S *big.Int
  907. }
  908. }
  909. // sign asks the card to sign a message, and returns a valid signature after
  910. // recovering the v value.
  911. func (s *Session) sign(path accounts.DerivationPath, hash []byte) ([]byte, error) {
  912. startTime := time.Now()
  913. _, err := s.derive(path)
  914. if err != nil {
  915. return nil, err
  916. }
  917. deriveTime := time.Now()
  918. response, err := s.Channel.transmitEncrypted(claSCWallet, insSign, signP1PrecomputedHash, signP2OnlyBlock, hash)
  919. if err != nil {
  920. return nil, err
  921. }
  922. sigdata := new(signatureData)
  923. if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil {
  924. return nil, err
  925. }
  926. // Serialize the signature
  927. rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes()
  928. sig := make([]byte, 65)
  929. copy(sig[32-len(rbytes):32], rbytes)
  930. copy(sig[64-len(sbytes):64], sbytes)
  931. // Recover the V value.
  932. sig, err = makeRecoverableSignature(hash, sig, sigdata.PublicKey)
  933. if err != nil {
  934. return nil, err
  935. }
  936. log.Debug("Signed using smartcard", "deriveTime", deriveTime.Sub(startTime), "signingTime", time.Since(deriveTime))
  937. return sig, nil
  938. }
  939. // confirmPublicKey confirms that the given signature belongs to the specified key.
  940. func confirmPublicKey(sig, pubkey []byte) error {
  941. _, err := makeRecoverableSignature(DerivationSignatureHash[:], sig, pubkey)
  942. return err
  943. }
  944. // makeRecoverableSignature uses a signature and an expected public key to
  945. // recover the v value and produce a recoverable signature.
  946. func makeRecoverableSignature(hash, sig, expectedPubkey []byte) ([]byte, error) {
  947. var libraryError error
  948. for v := 0; v < 2; v++ {
  949. sig[64] = byte(v)
  950. if pubkey, err := crypto.Ecrecover(hash, sig); err == nil {
  951. if bytes.Equal(pubkey, expectedPubkey) {
  952. return sig, nil
  953. }
  954. } else {
  955. libraryError = err
  956. }
  957. }
  958. if libraryError != nil {
  959. return nil, libraryError
  960. }
  961. return nil, ErrPubkeyMismatch
  962. }