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