@tonappchain/adnl
Version:
ADNL TypeScript implementation
55 lines • 1.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PACKET_MIN_SIZE = exports.ADNLPacket = void 0;
const hash_1 = require("./hash");
const utils_1 = require("@noble/hashes/utils");
const PACKET_MIN_SIZE = 4 + 32 + 32;
exports.PACKET_MIN_SIZE = PACKET_MIN_SIZE;
class ADNLPacket {
constructor(payload, nonce = Buffer.from((0, utils_1.randomBytes)(32))) {
this._payload = payload;
this._nonce = nonce;
}
get payload() {
return this._payload;
}
get nonce() {
return this._nonce;
}
get hash() {
const value = new Uint8Array([...this.nonce, ...this.payload]);
return Buffer.from((0, hash_1.sha256)(value));
}
get size() {
const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);
view.setUint32(0, this._payload.length + 32 + 32, true);
return Buffer.from(view.buffer);
}
get data() {
return Buffer.concat([this.size, this.nonce, this.payload, this.hash]);
}
get length() {
return 4 + 32 + this._payload.length + 32;
}
static parse(data) {
const packet = { cursor: 0, data };
if (packet.data.byteLength < 4) {
return null;
}
const size = packet.data.slice(0, packet.cursor += 4).readUint32LE(0);
if (packet.data.byteLength - 4 < size) {
return null;
}
const nonce = packet.data.slice(packet.cursor, packet.cursor += 32);
const payload = packet.data.slice(packet.cursor, packet.cursor += (size - (32 + 32)));
const hash = packet.data.slice(packet.cursor, packet.cursor += 32);
const target = Buffer.from((0, hash_1.sha256)(new Uint8Array([...nonce, ...payload])));
if (!hash.equals(target)) {
throw new Error('ADNLPacket: Bad packet hash.');
}
return new ADNLPacket(payload, nonce);
}
}
exports.ADNLPacket = ADNLPacket;
//# sourceMappingURL=packet.js.map