js-rln/src/byte_utils.ts
Sasha 891ee3474a
feat: keystore implementation (#70)
* add deps

* complete keystore, move code

* remove esling

* rename command

* rename export

* fix bug

* rollback example

* rollback example[2]

* improve compatibility with nwaku

* add packages

* update example

* add keystore.spec.ts

* up node, add whitelist words

* add types

* try break test

* add test

* add more tests

* add helper functions, update example, add tests

* fix types

* fix test

* add logs

* fix build of the object

* use different approach to catch errors

* run one test

* anotehr one

* fix validation error

* apply last fixes

* update example

* up

* ignroe generated files

* up

* up

* fix test

* test

* fix

* up

* add prettier ignore

* up

* fix lint

* up

* last
2023-10-14 02:21:35 +02:00

50 lines
1.1 KiB
TypeScript

// Adapted from https://github.com/feross/buffer
function checkInt(
buf: Uint8Array,
value: number,
offset: number,
ext: number,
max: number,
min: number
): void {
if (value > max || value < min)
throw new RangeError('"value" argument is out of bounds');
if (offset + ext > buf.length) throw new RangeError("Index out of range");
}
export function writeUIntLE(
buf: Uint8Array,
value: number,
offset: number,
byteLength: number,
noAssert?: boolean
): Uint8Array {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
const maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(buf, value, offset, byteLength, maxBytes, 0);
}
let mul = 1;
let i = 0;
buf[offset] = value & 0xff;
while (++i < byteLength && (mul *= 0x100)) {
buf[offset + i] = (value / mul) & 0xff;
}
return buf;
}
/**
* Transforms Uint8Array into BigInt
* @param array: Uint8Array
* @returns BigInt
*/
export function buildBigIntFromUint8Array(array: Uint8Array): bigint {
const dataView = new DataView(array.buffer);
return dataView.getBigUint64(0, true);
}