@trezor/transport
Version:
Low level library facilitating protocol buffers based communication with Trezor devices
67 lines (66 loc) • 1.91 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sendChunks = exports.buildMessage = exports.createChunks = void 0;
const protobuf_1 = require("@trezor/protobuf");
const protocol_1 = require("@trezor/protocol");
const createChunks = (data, chunkHeader, chunkSize) => {
if (!chunkSize || data.byteLength <= chunkSize) {
const buffer = Buffer.alloc(Math.max(chunkSize, data.byteLength));
data.copy(buffer);
return [buffer];
}
const chunks = [data.subarray(0, chunkSize)];
let position = chunkSize;
while (position < data.byteLength) {
const sliceEnd = Math.min(position + chunkSize - chunkHeader.byteLength, data.byteLength);
const slice = data.subarray(position, sliceEnd);
const chunk = Buffer.concat([chunkHeader, slice]);
chunks.push(Buffer.alloc(chunkSize).fill(chunk, 0, chunk.byteLength));
position = sliceEnd;
}
return chunks;
};
exports.createChunks = createChunks;
const buildMessage = ({
messages,
name,
data,
protocol,
thpState
}) => {
const protobufEncoder = (messageName, data) => {
const {
messageType,
message
} = (0, protobuf_1.encodeMessage)(messages, messageName, data);
return protocol.encode(message, {
messageType
});
};
if (protocol.name === 'v2') {
return protocol_1.thp.encode({
messageName: name,
data,
thpState,
protobufEncoder: (messageName, data) => (0, protobuf_1.encodeMessage)(messages, messageName, data)
});
}
return protobufEncoder(name, data);
};
exports.buildMessage = buildMessage;
const sendChunks = async (chunks, apiWrite) => {
for (let i = 0; i < chunks.length; i++) {
const result = await apiWrite(chunks[i]);
if (!result.success) {
return result;
}
}
return {
success: true,
payload: undefined
};
};
exports.sendChunks = sendChunks;
//# sourceMappingURL=send.js.map