Skip to content

Commit 418d5e7

Browse files
committed
fix+ref: allow 12-byte command names (no trailing NULL), and .subarray() instead of .slice()
1 parent f40749a commit 418d5e7

File tree

1 file changed

+22
-30
lines changed

1 file changed

+22
-30
lines changed

public/dashp2p.js

Lines changed: 22 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -662,42 +662,38 @@ var DashP2P = ('object' === typeof module && exports) || {};
662662
* @param {Uint8Array} bytes
663663
*/
664664
Parsers.header = function (bytes) {
665-
// let buffer = Buffer.from(bytes);
666-
// console.log(
667-
// new Date(),
668-
// '[debug] parseHeader(bytes)',
669-
// buffer.length,
670-
// buffer.toString('hex'),
671-
// );
672-
// console.log(buffer.toString('utf8'));
673-
// bytes = new Uint8Array(buffer);
674-
675665
if (bytes.length < Sizes.HEADER_SIZE) {
676-
// console.log(
677-
// `[DEBUG] malformed header`,
678-
// buffer.toString('utf8'),
679-
// buffer.toString('hex'),
680-
// );
681666
let msg = `developer error: header should be ${Sizes.HEADER_SIZE}+ bytes (optional payload), not ${bytes.length}`;
682667
throw new Error(msg);
683668
}
684669
let dv = new DataView(bytes.buffer);
685670

686-
let commandStart = 4;
687-
let payloadSizeStart = 16;
688-
let checksumStart = 20;
671+
let index = 0;
689672

690-
let magicBytes = bytes.slice(0, commandStart);
673+
let magicBytes = bytes.subarray(index, index + SIZES.MAGIC_BYTES);
674+
index += SIZES.MAGIC_BYTES; // +4 = 4
691675

692-
let commandEnd = bytes.indexOf(0x00, commandStart);
693-
if (commandEnd >= payloadSizeStart) {
694-
throw new Error('command name longer than 12 bytes');
676+
let commandBuf = bytes.subarray(index, index + SIZES.COMMAND_NAME);
677+
let command = '';
678+
{
679+
let commandEnd = bytes.indexOf(0x00, commandBuf);
680+
if (commandEnd !== -1) {
681+
commandBuf = commandBuf.subarray(0, commandEnd);
682+
}
683+
try {
684+
command = textDecoder.decode(commandBuf);
685+
} catch (e) {
686+
// invalid command name
687+
throw e;
688+
}
695689
}
696-
let commandBuf = bytes.slice(commandStart, commandEnd);
697-
let command = textDecoder.decode(commandBuf);
690+
index += SIZES.COMMAND_NAME; // +12 = 16
698691

699-
let payloadSize = dv.getUint32(payloadSizeStart, DV_LITTLE_ENDIAN);
700-
let checksum = bytes.slice(checksumStart, checksumStart + 4);
692+
let payloadSize = dv.getUint32(index, DV_LITTLE_ENDIAN);
693+
index += 1; // +1 = 17
694+
695+
let checksum = bytes.subarray(index, index + SIZES.CHUCKSUM);
696+
//index += SIZES.CHECKSUM // +4 = 21 (ends at 20)
701697

702698
let headerMessage = {
703699
magicBytes,
@@ -706,10 +702,6 @@ var DashP2P = ('object' === typeof module && exports) || {};
706702
checksum,
707703
};
708704

709-
// if (command !== 'inv') {
710-
// console.log(new Date(), headerMessage);
711-
// }
712-
// console.log();
713705
return headerMessage;
714706
};
715707
Parsers.SIZES = SIZES;

0 commit comments

Comments
 (0)