wallet.go 34 KB

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