Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: init ldmk-transport pkg #8071

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/many-moons-study.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ledgerhq/ldmk-transport": patch
---

Init ldmk transport pkg
Empty file.
13 changes: 13 additions & 0 deletions libs/ldmk-transport/jest.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"transform": {
"^.+\\.(ts|tsx)?$": [
"ts-jest",
{
"globals": {
"isolatedModules": true
}
}
]
},
"testPathIgnorePatterns": ["lib/", "lib-es/"]
}
7 changes: 7 additions & 0 deletions libs/ldmk-transport/notes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[x] add alias to pkg to json (you can test by running commands)
[x] look into device core for other files
[ ] meat
[ ] import ldmk
[ ] like poc5

- to test at the end run pnpm build:libs and check if pkg gets built ()
55 changes: 55 additions & 0 deletions libs/ldmk-transport/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"name": "@ledgerhq/ldmk-transport",
"version": "0.1.0",
"description": "Ledger Device Managment Kit transport module",
"license": "Apache-2.0",
"keywords": [
"Ledger"
],
"repository": {
"type": "git",
"url": "https://github.com/LedgerHQ/ledger-live.git"
},
"bugs": {
"url": "https://github.com/LedgerHQ/ledger-live/issues"
},
"homepage": "https://github.com/LedgerHQ/ledger-live/tree/develop/libs/env",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"module": "lib-es/index.js",
"scripts": {
"clean": "rimraf lib lib-es",
"build": "tsc && tsc -m ES6 --outDir lib-es",
"prewatch": "pnpm build",
"watch": "tsc --watch",
"lint": "eslint ./src --no-error-on-unmatched-pattern --ext .ts,.tsx --cache",
"lint:fix": "pnpm lint --fix",
"typecheck": "tsc --noEmit",
"unimported": "unimported",
"test": "jest"
},
"workspaces": [
"apps/*",
"libs/*"
],
"typesVersions": {
"*": {
"*.json": [
"*.json"
],
"*": [
"lib/*"
],
"lib/*": [
"lib/*"
],
"lib-es/*": [
"lib-es/*"
]
}
},
"dependencies": {
"@ledgerhq/hw-transport": "workspace:^",
"rxjs": "^7.8.1"
}
}
146 changes: 146 additions & 0 deletions libs/ldmk-transport/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import React, { createContext, useContext, useEffect, useState } from "react";
import Transport from "@ledgerhq/hw-transport";
import {
DeviceSdkBuilder,
ConsoleLogger,
type DeviceSdk,
type DeviceSessionState,
DeviceStatus,
LogLevel,
} from "@ledgerhq/device-management-kit";
import { BehaviorSubject, firstValueFrom } from "rxjs";

const deviceSdk = new DeviceSdkBuilder().addLogger(new ConsoleLogger(LogLevel.Debug)).build();

export const DeviceSdkContext = createContext<DeviceSdk>(deviceSdk);

type Props = {
children: React.ReactNode;
};

export const DeviceSdkProvider: React.FC<Props> = ({ children }) => {
return <DeviceSdkContext.Provider value={deviceSdk}>{children}</DeviceSdkContext.Provider>;
};

export const useDeviceSdk = (): DeviceSdk => {
return useContext(DeviceSdkContext);
};

export const useDeviceSessionState = (): DeviceSessionState | undefined => {
const sdk = useDeviceSdk();
const [sessionState, setSessionState] = useState<DeviceSessionState | undefined>(undefined);

useEffect(() => {
const subscription = activeDeviceSessionSubject.subscribe({
next: session => {
if (session) {
const { sessionId } = session;
const stateSubscription = sdk.getDeviceSessionState({ sessionId }).subscribe({
next: (state: { deviceStatus: any }) => {
state.deviceStatus !== DeviceStatus.NOT_CONNECTED
? setSessionState(state)
: setSessionState(undefined);
},
error: (error: any) => console.error("[useDeviceSessionState] error", error),
});
return () => stateSubscription.unsubscribe();
} else {
setSessionState(undefined);
}
},
error: error => console.error("[useDeviceSessionState] subscription error", error),
});

return () => subscription.unsubscribe();
}, [sdk]);

return sessionState;
};

const activeDeviceSessionSubject: BehaviorSubject<{
sessionId: string;
transport: DeviceManagementKitTransport;
} | null> = new BehaviorSubject<{
sessionId: string;
transport: DeviceManagementKitTransport;
} | null>(null);

export class DeviceManagementKitTransport extends Transport {
readonly sessionId: string;
readonly sdk: DeviceSdk;

constructor(sdk: DeviceSdk, sessionId: string) {
super();
this.sessionId = sessionId;
this.sdk = sdk;
this.listenToDisconnect();
}

listenToDisconnect = () => {
const subscription = this.sdk.getDeviceSessionState({ sessionId: this.sessionId }).subscribe({
next: (state: { deviceStatus: any }) => {
if (state.deviceStatus === DeviceStatus.NOT_CONNECTED) {
console.log(
"[SDKTransport][listenToDisconnect] device not connected, session ended, closing transport",
);
activeDeviceSessionSubject.next(null);
this.emit("disconnect");
}
},
error: (error: any) => {
console.error("[SDKTransport][listenToDisconnect] error", error);
this.emit("disconnect");
subscription.unsubscribe();
},
complete: () => {
console.log("[SDKTransport][listenToDisconnect] complete");
this.emit("disconnect");
subscription.unsubscribe();
},
});
};

static async open(): Promise<DeviceManagementKitTransport> {
console.log("[SDKTransport][open]");
const activeSessionId = activeDeviceSessionSubject.value?.sessionId;
if (activeSessionId) {
console.log("[SDKTransport][open] checking existing session", activeSessionId);
let deviceSessionState: DeviceSessionState | null = null;
try {
deviceSessionState = await firstValueFrom(
deviceSdk.getDeviceSessionState({ sessionId: activeSessionId }),
);
} catch (e) {
console.error("[SDKTransport][open] error getting device session state", e);
}
if (deviceSessionState?.deviceStatus !== DeviceStatus.NOT_CONNECTED) {
console.log(
"[SDKTransport][open] reusing existing session and instantiating a new SdkTransport",
);
return activeDeviceSessionSubject.value.transport;
}
}

console.log("[SDKTransport][open] no active session found, starting discovery");
const discoveredDevice: { id: string } = await firstValueFrom(deviceSdk.startDiscovering());
const connectedSessionId = await deviceSdk.connect({ deviceId: discoveredDevice.id });
console.log("[SDKTransport][open] connected");
const transport = new DeviceManagementKitTransport(deviceSdk, connectedSessionId);
activeDeviceSessionSubject.next({ sessionId: connectedSessionId, transport });
return transport;
}

close: () => Promise<void> = () => Promise.resolve();

async exchange(apdu: Buffer): Promise<Buffer> {
console.log("[SDKTransport][exchange] =>", apdu);
const apduUint8Array = new Uint8Array(apdu);
const apduResponse = await this.sdk.sendApdu({
sessionId: this.sessionId,
apdu: apduUint8Array,
});
const response = Buffer.from([...apduResponse.data, ...apduResponse.statusCode]);
console.log("[SDKTransport][exchange] <=", response);
return response;
}
}
17 changes: 17 additions & 0 deletions libs/ldmk-transport/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"extends": "../../tsconfig.base",
"compilerOptions": {
"jsx": "react",
"declaration": true,
"declarationMap": true,
"noImplicitAny": true,
"noImplicitThis": true,
"module": "commonjs",
"moduleResolution": "node",
"downlevelIteration": true,
"lib": ["es2020", "dom"],
"outDir": "lib",
"baseUrl": "."
},
"include": ["src/**/*", "src/index.tsx"]
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
"countervalues-react": "pnpm --filter live-countervalues-react",
"nft": "pnpm --filter live-nft",
"nft-react": "pnpm --filter live-nft-react",
"ldmk-transport": "pnpm --filter ldmk-transport",
"bot:github": "pnpm --filter live-github-bot",
"ljs:cryptoassets": "pnpm --filter cryptoassets",
"ljs:devices": "pnpm --filter devices",
Expand Down
12 changes: 12 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading