@trezor/transport
Version:
Low level library facilitating protocol buffers based communication with Trezor devices
56 lines (55 loc) • 1.66 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.receive = receive;
exports.receiveAndParse = receiveAndParse;
const protobuf_1 = require("@trezor/protobuf");
const result_1 = require("./result");
async function receive(receiver, protocol) {
const readResult = await receiver();
if (!readResult.success) {
return readResult;
}
const data = readResult.payload;
const {
length,
messageType,
payload,
header
} = protocol.decode(data);
const result = Buffer.alloc(length);
const [, chunkHeader] = protocol.getHeaders(Buffer.from(data));
payload.copy(result);
let offset = payload.length;
while (offset < length) {
const readResult = await receiver();
if (!readResult.success) {
return readResult;
}
const data = readResult.payload;
const dataChunkHeader = data.subarray(0, chunkHeader.length);
if (dataChunkHeader.compare(chunkHeader) !== 0) {
throw new Error(`Unexpected chunkHeader ${dataChunkHeader.toString('hex')}`);
}
Buffer.from(data).copy(result, offset, chunkHeader.byteLength);
offset += data.byteLength - chunkHeader.byteLength;
}
return (0, result_1.success)({
messageType,
payload: result,
header,
length
});
}
async function receiveAndParse(messages, receiver, protocol) {
const readResult = await receive(receiver, protocol);
if (!readResult.success) return readResult;
const {
messageType,
payload
} = readResult.payload;
const message = (0, protobuf_1.decodeMessage)(messages, messageType, payload);
return (0, result_1.success)(message);
}
//# sourceMappingURL=receive.js.map