wallet.go 31 KB

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