wallet.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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. 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. deriveNextPath accounts.DerivationPath // Next derivation path for account auto-discovery
  106. deriveNextAddr common.Address // Next derived account address for auto-discovery
  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 PUK", 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:
  275. return fmt.Sprintf("Blocked, waiting for PUK and new PIN"), nil
  276. case !w.session.verified:
  277. return fmt.Sprintf("Locked, waiting for PIN (%d attempts left)", status.PinRetryCount), nil
  278. case !status.Initialized:
  279. return fmt.Sprintf("Empty, waiting for initialization"), nil
  280. default:
  281. return fmt.Sprintf("Online"), nil
  282. }
  283. }
  284. // Open initializes access to a wallet instance. It is not meant to unlock or
  285. // decrypt account keys, rather simply to establish a connection to hardware
  286. // wallets and/or to access derivation seeds.
  287. //
  288. // The passphrase parameter may or may not be used by the implementation of a
  289. // particular wallet instance. The reason there is no passwordless open method
  290. // is to strive towards a uniform wallet handling, oblivious to the different
  291. // backend providers.
  292. //
  293. // Please note, if you open a wallet, you must close it to release any allocated
  294. // resources (especially important when working with hardware wallets).
  295. func (w *Wallet) Open(passphrase string) error {
  296. w.lock.Lock()
  297. defer w.lock.Unlock()
  298. // If the session is already open, bail out
  299. if w.session.verified {
  300. return ErrAlreadyOpen
  301. }
  302. // If the smart card is not yet paired, attempt to do so either from a previous
  303. // pairing key or form the supplied PUK code.
  304. if !w.session.paired() {
  305. // If a previous pairing exists, only ever try to use that
  306. if pairing := w.Hub.pairing(w); pairing != nil {
  307. if err := w.session.authenticate(*pairing); err != nil {
  308. return fmt.Errorf("failed to authenticate card %x: %s", w.PublicKey[:4], err)
  309. }
  310. // Pairing still ok, fall through to PIN checks
  311. } else {
  312. // If no passphrase was supplied, request the PUK from the user
  313. if passphrase == "" {
  314. return ErrPairingPasswordNeeded
  315. }
  316. // Attempt to pair the smart card with the user supplied PUK
  317. if err := w.pair([]byte(passphrase)); err != nil {
  318. return err
  319. }
  320. // Pairing succeeded, fall through to PIN checks. This will of course fail,
  321. // but we can't return ErrPINNeeded directly here becase we don't know whether
  322. // a PIN check or a PIN reset is needed.
  323. passphrase = ""
  324. }
  325. }
  326. // The smart card was successfully paired, retrieve its status to check whether
  327. // PIN verification or unblocking is needed.
  328. status, err := w.session.walletStatus()
  329. if err != nil {
  330. return err
  331. }
  332. // Request the appropriate next authentication data, or use the one supplied
  333. switch {
  334. case passphrase == "" && status.PinRetryCount > 0:
  335. return ErrPINNeeded
  336. case passphrase == "":
  337. return ErrPINUnblockNeeded
  338. case status.PinRetryCount > 0:
  339. if err := w.session.verifyPin([]byte(passphrase)); err != nil {
  340. return err
  341. }
  342. default:
  343. if err := w.session.unblockPin([]byte(passphrase)); err != nil {
  344. return err
  345. }
  346. }
  347. // Smart card paired and unlocked, initialize and register
  348. w.deriveReq = make(chan chan struct{})
  349. w.deriveQuit = make(chan chan error)
  350. go w.selfDerive()
  351. // Notify anyone listening for wallet events that a new device is accessible
  352. go w.Hub.updateFeed.Send(accounts.WalletEvent{Wallet: w, Kind: accounts.WalletOpened})
  353. return nil
  354. }
  355. // Close stops and closes the wallet, freeing any resources.
  356. func (w *Wallet) Close() error {
  357. // Ensure the wallet was opened
  358. w.lock.Lock()
  359. dQuit := w.deriveQuit
  360. w.lock.Unlock()
  361. // Terminate the self-derivations
  362. var derr error
  363. if dQuit != nil {
  364. errc := make(chan error)
  365. dQuit <- errc
  366. derr = <-errc // Save for later, we *must* close the USB
  367. }
  368. // Terminate the device connection
  369. w.lock.Lock()
  370. defer w.lock.Unlock()
  371. w.deriveQuit = nil
  372. w.deriveReq = nil
  373. if err := w.release(); err != nil {
  374. return err
  375. }
  376. return derr
  377. }
  378. // selfDerive is an account derivation loop that upon request attempts to find
  379. // new non-zero accounts.
  380. func (w *Wallet) selfDerive() {
  381. w.log.Debug("Smart card wallet self-derivation started")
  382. defer w.log.Debug("Smart card wallet self-derivation stopped")
  383. // Execute self-derivations until termination or error
  384. var (
  385. reqc chan struct{}
  386. errc chan error
  387. err error
  388. )
  389. for errc == nil && err == nil {
  390. // Wait until either derivation or termination is requested
  391. select {
  392. case errc = <-w.deriveQuit:
  393. // Termination requested
  394. continue
  395. case reqc = <-w.deriveReq:
  396. // Account discovery requested
  397. }
  398. // Derivation needs a chain and device access, skip if either unavailable
  399. w.lock.Lock()
  400. if w.session == nil || w.deriveChain == nil {
  401. w.lock.Unlock()
  402. reqc <- struct{}{}
  403. continue
  404. }
  405. pairing := w.Hub.pairing(w)
  406. // Device lock obtained, derive the next batch of accounts
  407. var (
  408. paths []accounts.DerivationPath
  409. nextAcc accounts.Account
  410. nextAddr = w.deriveNextAddr
  411. nextPath = w.deriveNextPath
  412. context = context.Background()
  413. )
  414. for empty := false; !empty; {
  415. // Retrieve the next derived Ethereum account
  416. if nextAddr == (common.Address{}) {
  417. if nextAcc, err = w.session.derive(nextPath); err != nil {
  418. w.log.Warn("Smartcard wallet account derivation failed", "err", err)
  419. break
  420. }
  421. nextAddr = 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, nextAddr, 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, nextAddr, 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 it nonetheless
  439. if balance.Sign() == 0 && nonce == 0 {
  440. empty = true
  441. }
  442. // We've just self-derived a new account, start tracking it locally
  443. path := make(accounts.DerivationPath, len(nextPath))
  444. copy(path[:], nextPath[:])
  445. paths = append(paths, path)
  446. // Display a log message to the user for new (or previously empty accounts)
  447. if _, known := pairing.Accounts[nextAddr]; !known || !empty || nextAddr != w.deriveNextAddr {
  448. w.log.Info("Smartcard wallet discovered new account", "address", nextAddr, "path", path, "balance", balance, "nonce", nonce)
  449. }
  450. pairing.Accounts[nextAddr] = path
  451. // Fetch the next potential account
  452. if !empty {
  453. nextAddr = common.Address{}
  454. nextPath[len(nextPath)-1]++
  455. }
  456. }
  457. // If there are new accounts, write them out
  458. if len(paths) > 0 {
  459. err = w.Hub.setPairing(w, pairing)
  460. }
  461. // Shift the self-derivation forward
  462. w.deriveNextAddr = nextAddr
  463. w.deriveNextPath = nextPath
  464. // Self derivation complete, release device lock
  465. w.lock.Unlock()
  466. // Notify the user of termination and loop after a bit of time (to avoid trashing)
  467. reqc <- struct{}{}
  468. if err == nil {
  469. select {
  470. case errc = <-w.deriveQuit:
  471. // Termination requested, abort
  472. case <-time.After(selfDeriveThrottling):
  473. // Waited enough, willing to self-derive again
  474. }
  475. }
  476. }
  477. // In case of error, wait for termination
  478. if err != nil {
  479. w.log.Debug("Smartcard wallet self-derivation failed", "err", err)
  480. errc = <-w.deriveQuit
  481. }
  482. errc <- err
  483. }
  484. // Accounts retrieves the list of signing accounts the wallet is currently aware
  485. // of. For hierarchical deterministic wallets, the list will not be exhaustive,
  486. // rather only contain the accounts explicitly pinned during account derivation.
  487. func (w *Wallet) Accounts() []accounts.Account {
  488. // Attempt self-derivation if it's running
  489. reqc := make(chan struct{}, 1)
  490. select {
  491. case w.deriveReq <- reqc:
  492. // Self-derivation request accepted, wait for it
  493. <-reqc
  494. default:
  495. // Self-derivation offline, throttled or busy, skip
  496. }
  497. w.lock.Lock()
  498. defer w.lock.Unlock()
  499. if pairing := w.Hub.pairing(w); pairing != nil {
  500. ret := make([]accounts.Account, 0, len(pairing.Accounts))
  501. for address, path := range pairing.Accounts {
  502. ret = append(ret, w.makeAccount(address, path))
  503. }
  504. sort.Sort(accounts.AccountsByURL(ret))
  505. return ret
  506. }
  507. return nil
  508. }
  509. func (w *Wallet) makeAccount(address common.Address, path accounts.DerivationPath) accounts.Account {
  510. return accounts.Account{
  511. Address: address,
  512. URL: accounts.URL{
  513. Scheme: w.Hub.scheme,
  514. Path: fmt.Sprintf("%x/%s", w.PublicKey[1:3], path.String()),
  515. },
  516. }
  517. }
  518. // Contains returns whether an account is part of this particular wallet or not.
  519. func (w *Wallet) Contains(account accounts.Account) bool {
  520. if pairing := w.Hub.pairing(w); pairing != nil {
  521. _, ok := pairing.Accounts[account.Address]
  522. return ok
  523. }
  524. return false
  525. }
  526. // Initialize installs a keypair generated from the provided key into the wallet.
  527. func (w *Wallet) Initialize(seed []byte) error {
  528. go w.selfDerive()
  529. // DO NOT lock at this stage, as the initialize
  530. // function relies on Status()
  531. return w.session.initialize(seed)
  532. }
  533. // Derive attempts to explicitly derive a hierarchical deterministic account at
  534. // the specified derivation path. If requested, the derived account will be added
  535. // to the wallet's tracked account list.
  536. func (w *Wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
  537. w.lock.Lock()
  538. defer w.lock.Unlock()
  539. account, err := w.session.derive(path)
  540. if err != nil {
  541. return accounts.Account{}, err
  542. }
  543. if pin {
  544. pairing := w.Hub.pairing(w)
  545. pairing.Accounts[account.Address] = path
  546. if err := w.Hub.setPairing(w, pairing); err != nil {
  547. return accounts.Account{}, err
  548. }
  549. }
  550. return account, nil
  551. }
  552. // SelfDerive sets a base account derivation path from which the wallet attempts
  553. // to discover non zero accounts and automatically add them to list of tracked
  554. // accounts.
  555. //
  556. // Note, self derivaton will increment the last component of the specified path
  557. // opposed to decending into a child path to allow discovering accounts starting
  558. // from non zero components.
  559. //
  560. // You can disable automatic account discovery by calling SelfDerive with a nil
  561. // chain state reader.
  562. func (w *Wallet) SelfDerive(base accounts.DerivationPath, chain ethereum.ChainStateReader) {
  563. w.lock.Lock()
  564. defer w.lock.Unlock()
  565. w.deriveNextPath = make(accounts.DerivationPath, len(base))
  566. copy(w.deriveNextPath[:], base[:])
  567. w.deriveNextAddr = common.Address{}
  568. w.deriveChain = chain
  569. }
  570. // SignData requests the wallet to sign the hash of the given data.
  571. //
  572. // It looks up the account specified either solely via its address contained within,
  573. // or optionally with the aid of any location metadata from the embedded URL field.
  574. //
  575. // If the wallet requires additional authentication to sign the request (e.g.
  576. // a password to decrypt the account, or a PIN code o verify the transaction),
  577. // an AuthNeededError instance will be returned, containing infos for the user
  578. // about which fields or actions are needed. The user may retry by providing
  579. // the needed details via SignDataWithPassphrase, or by other means (e.g. unlock
  580. // the account in a keystore).
  581. func (w *Wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
  582. return w.signHash(account, crypto.Keccak256(data))
  583. }
  584. func (w *Wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
  585. w.lock.Lock()
  586. defer w.lock.Unlock()
  587. path, err := w.findAccountPath(account)
  588. if err != nil {
  589. return nil, err
  590. }
  591. return w.session.sign(path, hash)
  592. }
  593. // SignTx requests the wallet to sign the given transaction.
  594. //
  595. // It looks up the account specified either solely via its address contained within,
  596. // or optionally with the aid of any location metadata from the embedded URL field.
  597. //
  598. // If the wallet requires additional authentication to sign the request (e.g.
  599. // a password to decrypt the account, or a PIN code o verify the transaction),
  600. // an AuthNeededError instance will be returned, containing infos for the user
  601. // about which fields or actions are needed. The user may retry by providing
  602. // the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
  603. // the account in a keystore).
  604. func (w *Wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  605. signer := types.NewEIP155Signer(chainID)
  606. hash := signer.Hash(tx)
  607. sig, err := w.signHash(account, hash[:])
  608. if err != nil {
  609. return nil, err
  610. }
  611. return tx.WithSignature(signer, sig)
  612. }
  613. // SignDataWithPassphrase requests the wallet to sign the given hash with the
  614. // given passphrase as extra authentication information.
  615. //
  616. // It looks up the account specified either solely via its address contained within,
  617. // or optionally with the aid of any location metadata from the embedded URL field.
  618. func (w *Wallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
  619. return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(data))
  620. }
  621. func (w *Wallet) signHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) {
  622. if !w.session.verified {
  623. if err := w.Open(passphrase); err != nil {
  624. return nil, err
  625. }
  626. }
  627. return w.signHash(account, hash)
  628. }
  629. // SignText requests the wallet to sign the hash of a given piece of data, prefixed
  630. // by the Ethereum prefix scheme
  631. // It looks up the account specified either solely via its address contained within,
  632. // or optionally with the aid of any location metadata from the embedded URL field.
  633. //
  634. // If the wallet requires additional authentication to sign the request (e.g.
  635. // a password to decrypt the account, or a PIN code o verify the transaction),
  636. // an AuthNeededError instance will be returned, containing infos for the user
  637. // about which fields or actions are needed. The user may retry by providing
  638. // the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
  639. // the account in a keystore).
  640. func (w *Wallet) SignText(account accounts.Account, text []byte) ([]byte, error) {
  641. return w.signHash(account, accounts.TextHash(text))
  642. }
  643. // SignTextWithPassphrase implements accounts.Wallet, attempting to sign the
  644. // given hash with the given account using passphrase as extra authentication
  645. func (w *Wallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
  646. return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(accounts.TextHash(text)))
  647. }
  648. // SignTxWithPassphrase requests the wallet to sign the given transaction, with the
  649. // given passphrase as extra authentication information.
  650. //
  651. // It looks up the account specified either solely via its address contained within,
  652. // or optionally with the aid of any location metadata from the embedded URL field.
  653. func (w *Wallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  654. if !w.session.verified {
  655. if err := w.Open(passphrase); err != nil {
  656. return nil, err
  657. }
  658. }
  659. return w.SignTx(account, tx, chainID)
  660. }
  661. // findAccountPath returns the derivation path for the provided account.
  662. // It first checks for the address in the list of pinned accounts, and if it is
  663. // not found, attempts to parse the derivation path from the account's URL.
  664. func (w *Wallet) findAccountPath(account accounts.Account) (accounts.DerivationPath, error) {
  665. pairing := w.Hub.pairing(w)
  666. if path, ok := pairing.Accounts[account.Address]; ok {
  667. return path, nil
  668. }
  669. // Look for the path in the URL
  670. if account.URL.Scheme != w.Hub.scheme {
  671. return nil, fmt.Errorf("Scheme %s does not match wallet scheme %s", account.URL.Scheme, w.Hub.scheme)
  672. }
  673. parts := strings.SplitN(account.URL.Path, "/", 2)
  674. if len(parts) != 2 {
  675. return nil, fmt.Errorf("Invalid URL format: %s", account.URL)
  676. }
  677. if parts[0] != fmt.Sprintf("%x", w.PublicKey[1:3]) {
  678. return nil, fmt.Errorf("URL %s is not for this wallet", account.URL)
  679. }
  680. return accounts.ParseDerivationPath(parts[1])
  681. }
  682. // Session represents a secured communication session with the wallet.
  683. type Session struct {
  684. Wallet *Wallet // A handle to the wallet that opened the session
  685. Channel *SecureChannelSession // A secure channel for encrypted messages
  686. verified bool // Whether the pin has been verified in this session.
  687. }
  688. // pair establishes a new pairing over this channel, using the provided secret.
  689. func (s *Session) pair(secret []byte) (smartcardPairing, error) {
  690. err := s.Channel.Pair(secret)
  691. if err != nil {
  692. return smartcardPairing{}, err
  693. }
  694. return smartcardPairing{
  695. PublicKey: s.Wallet.PublicKey,
  696. PairingIndex: s.Channel.PairingIndex,
  697. PairingKey: s.Channel.PairingKey,
  698. Accounts: make(map[common.Address]accounts.DerivationPath),
  699. }, nil
  700. }
  701. // unpair deletes an existing pairing.
  702. func (s *Session) unpair() error {
  703. if !s.verified {
  704. return fmt.Errorf("Unpair requires that the PIN be verified")
  705. }
  706. return s.Channel.Unpair()
  707. }
  708. // verifyPin unlocks a wallet with the provided pin.
  709. func (s *Session) verifyPin(pin []byte) error {
  710. if _, err := s.Channel.transmitEncrypted(claSCWallet, insVerifyPin, 0, 0, pin); err != nil {
  711. return err
  712. }
  713. s.verified = true
  714. return nil
  715. }
  716. // unblockPin unblocks a wallet with the provided puk and resets the pin to the
  717. // new one specified.
  718. func (s *Session) unblockPin(pukpin []byte) error {
  719. if _, err := s.Channel.transmitEncrypted(claSCWallet, insUnblockPin, 0, 0, pukpin); err != nil {
  720. return err
  721. }
  722. s.verified = true
  723. return nil
  724. }
  725. // release releases resources associated with the channel.
  726. func (s *Session) release() error {
  727. return s.Wallet.card.Disconnect(pcsc.LeaveCard)
  728. }
  729. // paired returns true if a valid pairing exists.
  730. func (s *Session) paired() bool {
  731. return s.Channel.PairingKey != nil
  732. }
  733. // authenticate uses an existing pairing to establish a secure channel.
  734. func (s *Session) authenticate(pairing smartcardPairing) error {
  735. if !bytes.Equal(s.Wallet.PublicKey, pairing.PublicKey) {
  736. return fmt.Errorf("Cannot pair using another wallet's pairing; %x != %x", s.Wallet.PublicKey, pairing.PublicKey)
  737. }
  738. s.Channel.PairingKey = pairing.PairingKey
  739. s.Channel.PairingIndex = pairing.PairingIndex
  740. return s.Channel.Open()
  741. }
  742. // walletStatus describes a smartcard wallet's status information.
  743. type walletStatus struct {
  744. PinRetryCount int // Number of remaining PIN retries
  745. PukRetryCount int // Number of remaining PUK retries
  746. Initialized bool // Whether the card has been initialized with a private key
  747. }
  748. // walletStatus fetches the wallet's status from the card.
  749. func (s *Session) walletStatus() (*walletStatus, error) {
  750. response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1WalletStatus, 0, nil)
  751. if err != nil {
  752. return nil, err
  753. }
  754. status := new(walletStatus)
  755. if _, err := asn1.UnmarshalWithParams(response.Data, status, "tag:3"); err != nil {
  756. return nil, err
  757. }
  758. return status, nil
  759. }
  760. // derivationPath fetches the wallet's current derivation path from the card.
  761. func (s *Session) derivationPath() (accounts.DerivationPath, error) {
  762. response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1Path, 0, nil)
  763. if err != nil {
  764. return nil, err
  765. }
  766. buf := bytes.NewReader(response.Data)
  767. path := make(accounts.DerivationPath, len(response.Data)/4)
  768. return path, binary.Read(buf, binary.BigEndian, &path)
  769. }
  770. // initializeData contains data needed to initialize the smartcard wallet.
  771. type initializeData struct {
  772. PublicKey []byte `asn1:"tag:0"`
  773. PrivateKey []byte `asn1:"tag:1"`
  774. ChainCode []byte `asn1:"tag:2"`
  775. }
  776. // initialize initializes the card with new key data.
  777. func (s *Session) initialize(seed []byte) error {
  778. // Check that the wallet isn't currently initialized,
  779. // otherwise the key would be overwritten.
  780. status, err := s.Wallet.Status()
  781. if err != nil {
  782. return err
  783. }
  784. if status == "Online" {
  785. return fmt.Errorf("card is already initialized, cowardly refusing to proceed")
  786. }
  787. s.Wallet.lock.Lock()
  788. defer s.Wallet.lock.Unlock()
  789. // HMAC the seed to produce the private key and chain code
  790. mac := hmac.New(sha512.New, []byte("Bitcoin seed"))
  791. mac.Write(seed)
  792. seed = mac.Sum(nil)
  793. key, err := crypto.ToECDSA(seed[:32])
  794. if err != nil {
  795. return err
  796. }
  797. id := initializeData{}
  798. id.PublicKey = crypto.FromECDSAPub(&key.PublicKey)
  799. id.PrivateKey = seed[:32]
  800. id.ChainCode = seed[32:]
  801. data, err := asn1.Marshal(id)
  802. if err != nil {
  803. return err
  804. }
  805. // Nasty hack to force the top-level struct tag to be context-specific
  806. data[0] = 0xA1
  807. _, err = s.Channel.transmitEncrypted(claSCWallet, insLoadKey, 0x02, 0, data)
  808. return err
  809. }
  810. // derive derives a new HD key path on the card.
  811. func (s *Session) derive(path accounts.DerivationPath) (accounts.Account, error) {
  812. startingPoint, path, err := derivationpath.Decode(path.String())
  813. if err != nil {
  814. return accounts.Account{}, err
  815. }
  816. var p1 uint8
  817. switch startingPoint {
  818. case derivationpath.StartingPointMaster:
  819. p1 = P1DeriveKeyFromMaster
  820. case derivationpath.StartingPointParent:
  821. p1 = P1DeriveKeyFromParent
  822. case derivationpath.StartingPointCurrent:
  823. p1 = P1DeriveKeyFromCurrent
  824. default:
  825. return accounts.Account{}, fmt.Errorf("invalid startingPoint %d", startingPoint)
  826. }
  827. data := new(bytes.Buffer)
  828. for _, segment := range path {
  829. if err := binary.Write(data, binary.BigEndian, segment); err != nil {
  830. return accounts.Account{}, err
  831. }
  832. }
  833. _, err = s.Channel.transmitEncrypted(claSCWallet, insDeriveKey, p1, 0, data.Bytes())
  834. if err != nil {
  835. return accounts.Account{}, err
  836. }
  837. response, err := s.Channel.transmitEncrypted(claSCWallet, insSign, 0, 0, DerivationSignatureHash[:])
  838. if err != nil {
  839. return accounts.Account{}, err
  840. }
  841. sigdata := new(signatureData)
  842. if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil {
  843. return accounts.Account{}, err
  844. }
  845. rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes()
  846. sig := make([]byte, 65)
  847. copy(sig[32-len(rbytes):32], rbytes)
  848. copy(sig[64-len(sbytes):64], sbytes)
  849. pubkey, err := determinePublicKey(sig, sigdata.PublicKey)
  850. if err != nil {
  851. return accounts.Account{}, err
  852. }
  853. pub, err := crypto.UnmarshalPubkey(pubkey)
  854. if err != nil {
  855. return accounts.Account{}, err
  856. }
  857. return s.Wallet.makeAccount(crypto.PubkeyToAddress(*pub), path), nil
  858. }
  859. // keyExport contains information on an exported keypair.
  860. type keyExport struct {
  861. PublicKey []byte `asn1:"tag:0"`
  862. PrivateKey []byte `asn1:"tag:1,optional"`
  863. }
  864. // publicKey returns the public key for the current derivation path.
  865. func (s *Session) publicKey() ([]byte, error) {
  866. response, err := s.Channel.transmitEncrypted(claSCWallet, insExportKey, exportP1Any, exportP2Pubkey, nil)
  867. if err != nil {
  868. return nil, err
  869. }
  870. keys := new(keyExport)
  871. if _, err := asn1.UnmarshalWithParams(response.Data, keys, "tag:1"); err != nil {
  872. return nil, err
  873. }
  874. return keys.PublicKey, nil
  875. }
  876. // signatureData contains information on a signature - the signature itself and
  877. // the corresponding public key.
  878. type signatureData struct {
  879. PublicKey []byte `asn1:"tag:0"`
  880. Signature struct {
  881. R *big.Int
  882. S *big.Int
  883. }
  884. }
  885. // sign asks the card to sign a message, and returns a valid signature after
  886. // recovering the v value.
  887. func (s *Session) sign(path accounts.DerivationPath, hash []byte) ([]byte, error) {
  888. startTime := time.Now()
  889. _, err := s.derive(path)
  890. if err != nil {
  891. return nil, err
  892. }
  893. deriveTime := time.Now()
  894. response, err := s.Channel.transmitEncrypted(claSCWallet, insSign, signP1PrecomputedHash, signP2OnlyBlock, hash)
  895. if err != nil {
  896. return nil, err
  897. }
  898. sigdata := new(signatureData)
  899. if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil {
  900. return nil, err
  901. }
  902. // Serialize the signature
  903. rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes()
  904. sig := make([]byte, 65)
  905. copy(sig[32-len(rbytes):32], rbytes)
  906. copy(sig[64-len(sbytes):64], sbytes)
  907. // Recover the V value.
  908. sig, err = makeRecoverableSignature(hash, sig, sigdata.PublicKey)
  909. if err != nil {
  910. return nil, err
  911. }
  912. log.Debug("Signed using smartcard", "deriveTime", deriveTime.Sub(startTime), "signingTime", time.Since(deriveTime))
  913. return sig, nil
  914. }
  915. // determinePublicKey uses a signature and the X component of a public key to
  916. // recover the entire public key.
  917. func determinePublicKey(sig, pubkeyX []byte) ([]byte, error) {
  918. for v := 0; v < 2; v++ {
  919. sig[64] = byte(v)
  920. pubkey, err := crypto.Ecrecover(DerivationSignatureHash[:], sig)
  921. if err == nil {
  922. if bytes.Equal(pubkey, pubkeyX) {
  923. return pubkey, nil
  924. }
  925. } else if v == 1 || err != secp256k1.ErrRecoverFailed {
  926. return nil, err
  927. }
  928. }
  929. return nil, ErrPubkeyMismatch
  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. for v := 0; v < 2; v++ {
  935. sig[64] = byte(v)
  936. pubkey, err := crypto.Ecrecover(hash, sig)
  937. if err == nil {
  938. if bytes.Equal(pubkey, expectedPubkey) {
  939. return sig, nil
  940. }
  941. } else if v == 1 || err != secp256k1.ErrRecoverFailed {
  942. return nil, err
  943. }
  944. }
  945. return nil, ErrPubkeyMismatch
  946. }