Skip to content

Commit

Permalink
temp
Browse files Browse the repository at this point in the history
  • Loading branch information
Nodonisko committed Nov 6, 2024
1 parent 5707a4d commit 898e243
Show file tree
Hide file tree
Showing 34 changed files with 1,061 additions and 91 deletions.
11 changes: 7 additions & 4 deletions packages/connect/src/core/onCallFirmwareUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ const waitForReconnectedDevice = async (
i,
}),
);
await new Promise(resolve => {
deviceList.once('device-disconnect', resolve);
});
// await new Promise(resolve => {
// deviceList.once('device-disconnect', resolve);
// });
}

log.debug(
Expand All @@ -92,7 +92,10 @@ const waitForReconnectedDevice = async (
await createTimeoutPromise(2000);
try {
reconnectedDevice = deviceList.getOnlyDevice();
} catch {}
console.log('reconnectedDevice features', await reconnectedDevice?.getFeatures());
} catch (error) {
console.log('error', error);
}
i++;
log.debug('onCallFirmwareUpdate', 'waiting for device to reconnect', i);
} while (
Expand Down
17 changes: 8 additions & 9 deletions packages/connect/src/utils/assets-browser.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
// origin https://github.com/trezor/connect/blob/develop/src/js/env/browser/networkUtils.js

import fetch from 'cross-fetch';
import { HttpRequestType, HttpRequestReturnType, HttpRequestOptions } from './assetsTypes';

export const httpRequest = async (
export const httpRequest = async <T extends HttpRequestType>(
url: string,
type: 'text' | 'binary' | 'json' = 'text',
options?: RequestInit,
) => {
type: T = 'text' as T,
options?: HttpRequestOptions,
): Promise<HttpRequestReturnType<T>> => {
const init: RequestInit = { ...options, credentials: 'same-origin' };

const response = await fetch(url, init);
if (response.ok) {
if (type === 'json') {
const txt = await response.text();

return JSON.parse(txt);
return JSON.parse(txt) as HttpRequestReturnType<T>;
}
if (type === 'binary') {
return response.arrayBuffer();
return response.arrayBuffer() as Promise<HttpRequestReturnType<T>>;
}

return response.text();
return response.text() as Promise<HttpRequestReturnType<T>>;
}

throw new Error(`httpRequest error: ${url} ${response.statusText}`);
Expand Down
26 changes: 25 additions & 1 deletion packages/connect/src/utils/assets.native.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
import { HttpRequestType, HttpRequestReturnType, HttpRequestOptions } from './assetsTypes';
import { tryLocalAssetRequire } from './assetUtils';

export const httpRequest = (url: string, _type: string): any => tryLocalAssetRequire(url);
export function httpRequest<T extends HttpRequestType>(
url: string,
type: T,
options?: HttpRequestOptions,
): Promise<HttpRequestReturnType<T>> {
const asset = options?.skipLocalForceDownload ? null : tryLocalAssetRequire(url);

if (!asset) {
return fetch(url, {
...options,
}).then(response => {
if (type === 'binary') {
return response.arrayBuffer() as unknown as HttpRequestReturnType<T>;
}
if (type === 'json') {
return response.json() as unknown as HttpRequestReturnType<T>;
}

return response.text() as unknown as HttpRequestReturnType<T>;
});
}

return asset as Promise<HttpRequestReturnType<T>>;
}
41 changes: 10 additions & 31 deletions packages/connect/src/utils/assets.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,25 @@
// https://github.com/trezor/connect/blob/develop/src/js/env/node/networkUtils.js

import fetch from 'cross-fetch';
import { promises as fs } from 'fs';
import { httpRequest as browserHttpRequest } from './assets-browser';
import { HttpRequestOptions, HttpRequestReturnType, HttpRequestType } from './assetsTypes';
import { tryLocalAssetRequire } from './assetUtils';

if (global && typeof global.fetch !== 'function') {
global.fetch = fetch;
}

export function httpRequest(
url: string,
type: 'text',
options?: RequestInit,
skipLocalForceDownload?: boolean,
): Promise<string>;

export function httpRequest(
export function httpRequest<T extends HttpRequestType>(
url: string,
type: 'binary',
options?: RequestInit,
skipLocalForceDownload?: boolean,
): Promise<ArrayBuffer>;

export function httpRequest(
url: string,
type: 'json',
options?: RequestInit,
skipLocalForceDownload?: boolean,
): Promise<Record<string, any>>;

export function httpRequest(
url: any,
type: any,
options?: RequestInit,
skipLocalForceDownload?: boolean,
) {
const asset = skipLocalForceDownload ? null : tryLocalAssetRequire(url);
type: T,
options?: HttpRequestOptions,
): Promise<HttpRequestReturnType<T>> {
const asset = options?.skipLocalForceDownload ? null : tryLocalAssetRequire(url);

if (!asset) {
return /^https?/.test(url) ? browserHttpRequest(url, type, options) : fs.readFile(url);
return /^https?/.test(url)
? browserHttpRequest(url, type, options)
: (fs.readFile(url) as Promise<HttpRequestReturnType<T>>);
}

return asset;
return asset as Promise<HttpRequestReturnType<T>>;
}
13 changes: 13 additions & 0 deletions packages/connect/src/utils/assetsTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export type HttpRequestType = 'text' | 'binary' | 'json';

export type HttpRequestReturnType<T extends HttpRequestType> = T extends 'text'
? string
: T extends 'binary'
? ArrayBuffer | Buffer
: T extends 'json'
? Record<string, any>
: never;

export interface HttpRequestOptions extends RequestInit {
skipLocalForceDownload?: boolean;
}
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ class ReactNativeUsbModule : Module() {
for (device in devicesList) {
if (usbManager.hasPermission(device)) {
Log.d(LOG_TAG, "Has permission, send event onDeviceConnected: $device")

val webUsbDevice = if (hasOpenedConnection(device.deviceName)) {
Log.d(LOG_TAG, "Device already opened: $device")
getWebUSBDevice(device)
Expand Down
2 changes: 1 addition & 1 deletion packages/react-native-usb/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { NativeModulesProxy, EventEmitter, Subscription } from 'expo-modules-cor
import { ReactNativeUsbModule } from './ReactNativeUsbModule';
import { NativeDevice, OnConnectEvent, WebUSBDevice } from './ReactNativeUsb.types';

const DEBUG_LOGS = false;
const DEBUG_LOGS = true;

const debugLog = (...args: any[]) => {
if (DEBUG_LOGS) {
Expand Down
4 changes: 4 additions & 0 deletions suite-common/connect-init/src/connectInitThunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ export const connectInitThunk = createThunk(
if (eventData.type === DEVICE.CONNECT || eventData.type === DEVICE.CONNECT_UNACQUIRED) {
dispatch(deviceConnectThunks({ type: eventData.type, device: eventData.payload }));
} else {
if (eventData.type !== 'device-changed') {
console.log(eventData);
}
dispatch({ type: eventData.type, payload: eventData.payload });
}
});
Expand Down Expand Up @@ -139,6 +142,7 @@ export const connectInitThunk = createThunk(
// debug: true, // Enable debug logs in TrezorConnect
});
} catch (error) {
console.error(error);
let formattedError: string;
if (typeof error === 'string') {
formattedError = error;
Expand Down
8 changes: 7 additions & 1 deletion suite-common/wallet-core/src/device/deviceReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { memoize } from 'proxy-memoize';
import { isAnyOf } from '@reduxjs/toolkit';

import * as deviceUtils from '@suite-common/suite-utils';
import { getDeviceInstances, getStatus } from '@suite-common/suite-utils';
import { getDeviceInstances, getFwUpdateVersion, getStatus } from '@suite-common/suite-utils';
import { Device, DeviceState, Features, StaticSessionId, UI } from '@trezor/connect';
import {
getFirmwareVersion,
Expand Down Expand Up @@ -992,3 +992,9 @@ export const selectIsBitcoinOnlyDevice = (state: DeviceRootState) =>
// Any Trezor that has BTC only firmware
export const selectHasBitcoinOnlyFirmware = (state: DeviceRootState) =>
hasBitcoinOnlyFirmware(selectDevice(state));

export const selectDeviceUpdateFirmwareVersion = (state: DeviceRootState) => {
const device = selectDevice(state);

return device ? getFwUpdateVersion(device) : null;
};
9 changes: 8 additions & 1 deletion suite-native/atoms/src/AlertBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export type AlertBoxProps = {
variant: AlertBoxVariant;
title: ReactNode;
borderRadius?: NativeRadius | number;
rightButton?: ReactNode;
};

const AlertSpinner = ({ color }: { color: Color }) => {
Expand All @@ -92,7 +93,12 @@ const AlertSpinner = ({ color }: { color: Color }) => {
return <ActivityIndicator size={16} color={colors[color]} />;
};

export const AlertBox = ({ title, variant = 'info', borderRadius = 'r16' }: AlertBoxProps) => {
export const AlertBox = ({
title,
variant = 'info',
borderRadius = 'r16',
rightButton,
}: AlertBoxProps) => {
const { applyStyle } = useNativeStyles();
const { contentColor, backgroundColor, borderColor } = variantToColorMap[variant];

Expand All @@ -112,6 +118,7 @@ export const AlertBox = ({ title, variant = 'info', borderRadius = 'r16' }: Aler
<Text color={contentColor} variant="label" style={applyStyle(textStyle)}>
{title}
</Text>
{rightButton}
</Box>
);
};
3 changes: 1 addition & 2 deletions suite-native/atoms/src/Spinner/Spinner.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useRef, useState } from 'react';

import Lottie from 'lottie-react-native';
import LottieView from 'lottie-react-native';

import { prepareNativeStyle, useNativeStyles } from '@trezor/styles';

Expand All @@ -27,7 +26,7 @@ const animationsMap = {
type AnimationName = keyof typeof animationsMap;

export const Spinner = ({ loadingState, onComplete }: SpinnerProps) => {
const animationRef = useRef<LottieView>(null);
const animationRef = useRef<Lottie>(null);
const [currentAnimation, setCurrentAnimation] = useState<AnimationName>('start');
const { applyStyle } = useNativeStyles();

Expand Down
2 changes: 1 addition & 1 deletion suite-native/device-manager/src/components/DeviceList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export const DeviceList = ({ isVisible, onSelectDevice }: DeviceListProps) => {
d =>
d.state && (
<DeviceItem
key={d.state.staticSessionId}
key={d.path}
deviceState={d.state}
onPress={() => onSelectDevice(d)}
/>
Expand Down
14 changes: 14 additions & 0 deletions suite-native/device/src/hooks/useHandleDeviceConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { selectDeviceRequestedPin } from '@suite-native/device-authorization';
import { selectIsOnboardingFinished } from '@suite-native/settings';
import { requestPrioritizedDeviceAccess } from '@suite-native/device-mutex';
import { useIsBiometricsOverlayVisible } from '@suite-native/biometrics';
import { selectIsFirmwareInstallationRunning } from '@suite-native/firmware';

type NavigationProp = StackToStackCompositeNavigationProps<
AuthorizeDeviceStackParamList | RootStackParamList,
Expand All @@ -42,6 +43,7 @@ export const useHandleDeviceConnection = () => {
const isDeviceConnected = useSelector(selectIsDeviceConnected);
const { isBiometricsOverlayVisible } = useIsBiometricsOverlayVisible();
const isDeviceUsingPassphrase = useSelector(selectIsDeviceUsingPassphrase);
const isFirmwareInstallationRunning = useSelector(selectIsFirmwareInstallationRunning);
const navigation = useNavigation<NavigationProp>();
const dispatch = useDispatch();

Expand All @@ -53,6 +55,11 @@ export const useHandleDeviceConnection = () => {
// At the moment when unauthorized physical device is selected,
// redirect to the Connecting screen where is handled the connection logic.
useEffect(() => {
console.log('isFirmwareInstallationRunning', isFirmwareInstallationRunning);
if (isFirmwareInstallationRunning) return;

console.log('isDeviceConnected', isDeviceConnected);

if (
isDeviceConnected &&
isOnboardingFinished &&
Expand Down Expand Up @@ -83,11 +90,16 @@ export const useHandleDeviceConnection = () => {
navigation,
isDeviceUsingPassphrase,
shouldBlockSendReviewRedirect,
isFirmwareInstallationRunning,
]);

// In case that the physical device is disconnected, redirect to the home screen and
// set connecting screen to be displayed again on the next device connection.
useEffect(() => {
console.log('isFirmwareInstallationRunning', isFirmwareInstallationRunning);
if (isFirmwareInstallationRunning) return;

console.log('isNoPhysicalDeviceConnected', isNoPhysicalDeviceConnected);
if (isNoPhysicalDeviceConnected && isOnboardingFinished) {
const previousRoute = navigation.getState()?.routes.at(-1)?.name;

Expand All @@ -97,6 +109,7 @@ export const useHandleDeviceConnection = () => {
if (isPreviousRouteOnboarding || shouldBlockSendReviewRedirect) {
return;
}
console.log('navigating to home');
navigation.navigate(RootStackRoutes.AppTabs, {
screen: AppTabsRoutes.HomeStack,
params: {
Expand All @@ -109,6 +122,7 @@ export const useHandleDeviceConnection = () => {
isOnboardingFinished,
navigation,
shouldBlockSendReviewRedirect,
isFirmwareInstallationRunning,
]);

// When trezor gets locked, it is necessary to display a PIN matrix for T1 so that it can be unlocked
Expand Down
14 changes: 14 additions & 0 deletions suite-native/firmware/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "@suite-native/firmware",
"version": "1.0.0",
"private": true,
"license": "See LICENSE.md in repo root",
"sideEffects": false,
"main": "src/index",
"scripts": {
"depcheck": "yarn g:depcheck",
"lint:js": "yarn g:eslint '**/*.{ts,tsx,js}'",
"test:unit": "jest -c ../../jest.config.base.js",
"type-check": "yarn g:tsc --build"
}
}
29 changes: 29 additions & 0 deletions suite-native/firmware/src/firmwareSlice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface FirmwareState {
isFirmwareInstallationRunning: boolean;
}

const initialState: FirmwareState = {
isFirmwareInstallationRunning: false,
};

type FirmwareRootState = {
firmware: FirmwareState;
};

export const firmwareSlice = createSlice({
name: 'firmware',
initialState,
reducers: {
setIsFirmwareInstallationRunning: (state, action: PayloadAction<boolean>) => {
state.isFirmwareInstallationRunning = action.payload;
},
},
});

export const firmwareActions = firmwareSlice.actions;
export const firmwareReducer = firmwareSlice.reducer;

export const selectIsFirmwareInstallationRunning = (state: FirmwareRootState) =>
state.firmware.isFirmwareInstallationRunning;
1 change: 1 addition & 0 deletions suite-native/firmware/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './firmwareSlice';
5 changes: 5 additions & 0 deletions suite-native/firmware/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": { "outDir": "libDev" },
"references": []
}
Loading

0 comments on commit 898e243

Please sign in to comment.