2022-02-04 14:12:00 +11:00
|
|
|
import { keccak256, Message } from "js-sha3";
|
2022-01-13 11:33:26 +11:00
|
|
|
|
2022-02-11 17:27:15 +11:00
|
|
|
/**
|
|
|
|
|
* Convert input to a Buffer.
|
|
|
|
|
*/
|
2021-07-12 17:09:44 +10:00
|
|
|
export function hexToBuf(hex: string | Buffer | Uint8Array): Buffer {
|
2022-02-04 14:12:00 +11:00
|
|
|
if (typeof hex === "string") {
|
|
|
|
|
return Buffer.from(hex.replace(/^0x/i, ""), "hex");
|
2021-07-12 17:09:44 +10:00
|
|
|
} else {
|
|
|
|
|
return Buffer.from(hex);
|
|
|
|
|
}
|
2021-07-09 15:12:52 +10:00
|
|
|
}
|
|
|
|
|
|
2022-02-11 17:27:15 +11:00
|
|
|
/**
|
|
|
|
|
* Convert input to hex string (no `0x` prefix).
|
|
|
|
|
*/
|
2021-07-09 15:57:47 +10:00
|
|
|
export function bufToHex(buf: Uint8Array | Buffer | ArrayBuffer): string {
|
2021-07-09 15:12:52 +10:00
|
|
|
const _buf = Buffer.from(buf);
|
2022-02-04 14:12:00 +11:00
|
|
|
return _buf.toString("hex");
|
2021-07-09 15:12:52 +10:00
|
|
|
}
|
|
|
|
|
|
2022-02-11 17:27:15 +11:00
|
|
|
/**
|
|
|
|
|
* Compare both inputs, return true if they represent the same byte array.
|
|
|
|
|
*/
|
2021-07-09 15:12:52 +10:00
|
|
|
export function equalByteArrays(
|
|
|
|
|
a: Uint8Array | Buffer | string,
|
|
|
|
|
b: Uint8Array | Buffer | string
|
|
|
|
|
): boolean {
|
|
|
|
|
let aBuf: Buffer;
|
|
|
|
|
let bBuf: Buffer;
|
2022-02-04 14:12:00 +11:00
|
|
|
if (typeof a === "string") {
|
2021-07-09 15:12:52 +10:00
|
|
|
aBuf = hexToBuf(a);
|
|
|
|
|
} else {
|
|
|
|
|
aBuf = Buffer.from(a);
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-04 14:12:00 +11:00
|
|
|
if (typeof b === "string") {
|
2021-07-09 15:12:52 +10:00
|
|
|
bBuf = hexToBuf(b);
|
|
|
|
|
} else {
|
|
|
|
|
bBuf = Buffer.from(b);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return aBuf.compare(bBuf) === 0;
|
2021-07-05 15:48:57 +10:00
|
|
|
}
|
2022-01-13 11:33:26 +11:00
|
|
|
|
2022-02-11 17:27:15 +11:00
|
|
|
/**
|
|
|
|
|
* Return Keccak-256 of the input.
|
|
|
|
|
*/
|
2022-01-13 11:33:26 +11:00
|
|
|
export function keccak256Buf(message: Message): Buffer {
|
|
|
|
|
return Buffer.from(keccak256.arrayBuffer(message));
|
|
|
|
|
}
|