All files / app/main register-ledger-listeners.ts

0% Statements 0/87
0% Branches 0/17
0% Functions 0/25
0% Lines 0/77

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175                                                                                                                                                                                                                                                                                                                                                             
/* eslint-disable @typescript-eslint/no-unsafe-argument */
import {
  ledgerRequestSignTx,
  ledgerRequestStxAddress,
  ledgerShowStxAddress,
} from './ledger-actions';
import type Transport from '@ledgerhq/hw-transport';
import TransportNodeHid from '@ledgerhq/hw-transport-node-hid';
import { safeAwait } from '@stacks/ui';
import StacksApp, { LedgerError, ResponseVersion } from '@zondax/ledger-blockstack';
import { ipcMain } from 'electron';
import { BehaviorSubject, Subject, timer, combineLatest, from, of } from 'rxjs';
import { delay, filter, map, switchMap, take, takeUntil } from 'rxjs/operators';
 
type LedgerEvents =
  | 'create-listener'
  | 'remove-listener'
  | 'waiting-transport'
  | 'disconnected'
  | 'has-transport';
 
type LedgerStateEvents =
  | Record<'name', LedgerEvents>
  | (Record<'name', keyof typeof LedgerError> & ResponseVersion & { action: 'get-version' });
 
interface LedgerMessageType {
  type: 'ledger-event';
}
 
export type LedgerMessageEvents = LedgerStateEvents & LedgerMessageType;
 
const POLL_LEDGER_INTERVAL = 1_250;
const SAFE_ASSUME_REAL_DEVICE_DISCONNECT_TIME = 2_000;
 
const ledgerState$ = new Subject<LedgerStateEvents>();
const ledgerDeviceBusy$ = new BehaviorSubject(false);
const listeningForDevice$ = new BehaviorSubject(false);
const checkDisconnect$ = new Subject<void>();
 
const transport$ = new BehaviorSubject<Transport | null>(null);
 
export function registerLedgerListeners(webContent: Electron.WebContents) {
  // `webContent` might be destroyed when closing window
  // listenUntil$ tears down the old subscriptoin
  const listenUntil$ = new Subject<void>();
  webContent.on('destroyed', () => {
    listeningForDevice$.next(false);
    listenUntil$.next();
    listenUntil$.complete();
  });
  ledgerState$
    .pipe(
      takeUntil(listenUntil$),
      map(ledgerEvent => ({ type: 'ledger-event', ...ledgerEvent }))
    )
    .subscribe(event => webContent.send('message-event', event));
}
 
let subscription: null | ReturnType<typeof TransportNodeHid.listen> = null;
function createDeviceListener() {
  Iif (subscription) subscription.unsubscribe();
  subscription = TransportNodeHid.listen({
    next: async event => {
      Iif (event.type === 'add') {
        ledgerState$.next({ name: 'waiting-transport' });
        Iif (subscription) subscription.unsubscribe();
        const [error, ledgerTransport] = await safeAwait(TransportNodeHid.open(event.descriptor));
        ledgerState$.next({ name: 'has-transport' });
        Iif (ledgerTransport) transport$.next(ledgerTransport);
        Iif (error) console.log({ error });
      }
    },
    error: e => console.log('err', e),
    complete: () => console.log('complete'),
  });
}
 
listeningForDevice$.subscribe(listening => {
  Iif (listening) {
    createDeviceListener();
    return;
  }
  subscription?.unsubscribe();
  const transport = transport$.getValue();
  Iif (transport) void transport.close();
});
 
const shouldPoll$ = combineLatest([listeningForDevice$, ledgerDeviceBusy$]).pipe(
  map(([listeningForDevice, deviceBusy]) => Boolean(listeningForDevice && !deviceBusy))
);
 
//
// Ledger devices do not immediately fire updates, such as if
// the device disconnects or jumps to another state. In order
// to get the latest state, we poll the device, but only in
// certain circumstances. This stream emits with an interval
// and is then filtered based on the value of these conditions.
const devicePoll$ = timer(0, POLL_LEDGER_INTERVAL).pipe(
  switchMap(() => shouldPoll$.pipe(take(1))),
  filter(shouldPoll => shouldPoll),
  switchMap(() => {
    const transport = transport$.getValue();
    Iif (!transport) {
      createDeviceListener();
      return of(true);
    }
    return from(
      new StacksApp(transport as any)
        .getVersion()
        .then(resp => {
          Iif (resp.returnCode === 0xffff) {
            transport$.next(null);
            checkDisconnect$.next();
            createDeviceListener();
            return;
          }
          ledgerState$.next({
            ...resp,
            action: 'get-version',
            name: LedgerError[resp.returnCode] as keyof typeof LedgerError,
          });
        })
        .catch(console.log)
    );
  })
);
 
devicePoll$.subscribe();
 
//
// When jumping between screens on a Ledger device,
// it technically disconnects/reconnects very quickly.
// To detect real device unplugs we watch to see if
// if a transport exists after a set period
checkDisconnect$
  .pipe(
    delay(SAFE_ASSUME_REAL_DEVICE_DISCONNECT_TIME),
    switchMap(() => transport$.pipe(take(1)))
  )
  .subscribe(transport => transport === null && ledgerState$.next({ name: 'disconnected' }));
 
async function wrapAsBusy<T>(ledgerOperation: Promise<T>) {
  ledgerDeviceBusy$.next(true);
  const resp = await ledgerOperation;
  ledgerDeviceBusy$.next(false);
  return resp;
}
 
//
// Request ledger stx address
const wrappedLedgerRequestStxAddress = () =>
  wrapAsBusy(ledgerRequestStxAddress(transport$.getValue()));
 
export type LedgerRequestStxAddress = ReturnType<typeof ledgerRequestStxAddress>;
ipcMain.handle('ledger-request-stx-address', async () => wrappedLedgerRequestStxAddress());
 
//
// Show ledger stx address
const wrappedShowLedgerStxAddress = () => wrapAsBusy(ledgerShowStxAddress(transport$.getValue()));
ipcMain.handle('ledger-show-stx-address', async () => wrappedShowLedgerStxAddress());
 
//
// Sign ledger transaction
export type LedgerRequestSignTx = ReturnType<ReturnType<typeof ledgerRequestSignTx>>;
 
const wrappedLedgerRequestSignTx = (unsignedTx: string) =>
  wrapAsBusy(ledgerRequestSignTx(transport$.getValue())(unsignedTx));
 
ipcMain.handle('ledger-request-sign-tx', async (_, unsignedTx: string) =>
  wrappedLedgerRequestSignTx(unsignedTx)
);
 
ipcMain.on('create-ledger-listener', () => listeningForDevice$.next(true));
ipcMain.on('remove-ledger-listener', () => listeningForDevice$.next(false));