import Transport from "@ledgerhq/hw-transport" ; import { ErrorCode , evalTransportError , TransportStatusError , } from "./ErrorCode" ; import { DerToHexSignature } from "./utils" ; const DEFAULT_STATUSLIST = [ ErrorCode . VALID_STATUS ] ; param msg async function appendDataForSignature ( ledger , msg ) { return await ledger . send ( 0x80 , 0x02 , 0x00 , 0x00 , Buffer . from ( msg , "hex" ) , DEFAULT_STATUSLIST ) ; } param ledger param msg async function finalizeDataForSignature ( ledger , msg ) { return await ledger . send ( 0x80 , 0x02 , 0x80 , 0x00 , Buffer . from ( msg , "hex" ) , DEFAULT_STATUSLIST ) ; } param ledgerLibrary export async function getDevicePaths ( ledgerLibrary ) { const supported = await ledgerLibrary . isSupported ( ) ; if ( ! supported ) { throw new Error ( `Your computer does not support the ledger!` ) ; } return await ledgerLibrary . list ( ) ; } param ledger param bip44String returns export async function getPublicKey ( ledger , bip44String ) { try { const response = await ledger . send ( 0x80 , 0x04 , 0x00 , 0x00 , Buffer . from ( bip44String , "hex" ) , DEFAULT_STATUSLIST ) ; return response . toString ( "hex" ) . substring ( 0 , 130 ) ; } catch ( e ) { if ( e . statusCode ) { throw evalTransportError ( e as TransportStatusError ) ; } throw e ; } } param ledger param hex param bip44String returns export async function getSignature ( ledger , hex , bip44String ) { const payload = hex + bip44String ; const chunks = payload . match ( /.{1,510}/g ) || [ ] ; try { for ( let i = 0 ; i < chunks . length - 1 ; i ++ ) { await appendDataForSignature ( ledger , chunks [ i ] ) ; } const response = await finalizeDataForSignature ( ledger , chunks [ chunks . length - 1 ] ) ; if ( response . readUIntBE ( 0 , 2 ) === ErrorCode . VALID_STATUS ) { throw new Error ( `No more data but Ledger did not return signature!` ) ; } return DerToHexSignature ( response . toString ( "hex" ) ) ; } catch ( e ) { if ( e . statusCode ) { throw evalTransportError ( e as TransportStatusError ) ; } throw e ; } }