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

refactor(core-p2p): refactor codecs so buffer isn't re-allocated 400 times. #4493

Merged
Merged
Changes from 1 commit
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
Next Next commit
Refactor getBlocks so buffer isn't re-allocated 400 times.
  • Loading branch information
rainydio committed Sep 16, 2021
commit 06909ad7bbfdd38cd3cbe7519cf86a2c818ddb66
35 changes: 20 additions & 15 deletions packages/core-p2p/src/socket-server/codecs/blocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,35 @@ export const getBlocks = {
},
response: {
serialize: (obj): Buffer => {
const blocksEncoded: Buffer[] = [];
const blockBuffers: Buffer[] = [];

for (const block of obj) {
let txBuffers: Buffer[] = [];

if (block.transactions) {
for (const transaction of block.transactions) {
const txBuffer = Buffer.from(transaction, "hex");
const txLengthBuffer = Buffer.alloc(4);
txLengthBuffer.writeUInt32BE(txBuffer.byteLength);
txBuffers.push(txLengthBuffer, txBuffer);
}
}

const blockEncoded = blocks.GetBlocksResponse.BlockHeader.encode({
...block,
totalAmount: block.totalAmount.toString(),
totalFee: block.totalFee.toString(),
reward: block.reward.toString(),
transactions: block.transactions
? block.transactions.reduce((acc, curr) => {
const txBuffer = Buffer.from(curr, "hex");
const txByteLength = Buffer.alloc(4);
txByteLength.writeUInt32BE(txBuffer.byteLength);
return Buffer.concat([acc, txByteLength, txBuffer]);
}, Buffer.alloc(0))
: Buffer.alloc(0),
transactions: Buffer.concat(txBuffers),
}).finish();
blocksEncoded.push(Buffer.from(blockEncoded));

const blockBuffer = Buffer.from(blockEncoded);
const blockLengthBuffer = Buffer.alloc(4);
blockLengthBuffer.writeUInt32BE(blockBuffer.length);
blockBuffers.push(blockLengthBuffer, blockBuffer);
}

return blocksEncoded.reduce((acc, curr) => {
const txByteLength = Buffer.alloc(4);
txByteLength.writeUInt32BE(curr.byteLength);
return Buffer.concat([acc, txByteLength, curr]);
}, Buffer.alloc(0));
return Buffer.concat(blockBuffers);
},
deserialize: (payload: Buffer) => {
const blocksBuffer = Buffer.from(payload);
Expand Down