Use browser friendly concatUint8Arrays instead of Buffer.concat

This commit is contained in:
dapplion 2020-12-03 00:06:36 +00:00
parent 13ea412c3f
commit 7f76672a40
4 changed files with 37 additions and 12 deletions

View File

@ -20,3 +20,17 @@ export function validateBytes(
export function isZeroUint8Array(bytes: Uint8Array): boolean {
return bytes.every((byte) => byte === 0);
}
export function concatUint8Arrays(bytesArr: Uint8Array[]): Uint8Array {
const totalLen = bytesArr.reduce((total, bytes) => total + bytes.length, 0);
const merged = new Uint8Array(totalLen);
let mergedLen = 0;
for (const bytes of bytesArr) {
merged.set(bytes, mergedLen);
mergedLen += bytes.length;
}
return merged;
}

View File

@ -2,7 +2,7 @@ import {SIGNATURE_LENGTH} from "../constants";
import {SignatureType, multiVerify} from "bls-eth-wasm";
import {getContext} from "./context";
import {PublicKey} from "./publicKey";
import {bytesToHex, hexToBytes, isZeroUint8Array} from "../helpers";
import {bytesToHex, concatUint8Arrays, hexToBytes, isZeroUint8Array} from "../helpers";
import {Signature as ISignature} from "../interface";
import {EmptyAggregateError, InvalidLengthError, InvalidOrderError} from "../errors";
@ -65,10 +65,9 @@ export class Signature implements ISignature {
}
verifyMultiple(publicKeys: PublicKey[], messages: Uint8Array[]): boolean {
const msgs = Buffer.concat(messages);
return this.value.aggregateVerifyNoCheck(
publicKeys.map((key) => key.value),
msgs
concatUint8Arrays(messages)
);
}

View File

@ -1,5 +1,6 @@
import {expect} from "chai";
import {isZeroUint8Array} from "../../../src/helpers/utils";
import {concatUint8Arrays, isZeroUint8Array} from "../../../src/helpers/utils";
import {hexToBytesNode} from "../../util";
describe("helpers / bytes", () => {
describe("isZeroUint8Array", () => {
@ -21,8 +22,22 @@ describe("helpers / bytes", () => {
});
}
});
});
function hexToBytesNode(hex: string): Buffer {
return Buffer.from(hex.replace("0x", ""), "hex");
}
describe("concatUint8Arrays", () => {
it("Should merge multiple Uint8Array", () => {
const bytesArr = [
new Uint8Array([1, 2, 3]),
new Uint8Array([4, 5]),
new Uint8Array([6]),
new Uint8Array([7, 8]),
new Uint8Array([9, 10, 11]),
];
const expectedBytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
const bytes = concatUint8Arrays(bytesArr);
expect(bytes.toString()).to.equal(expectedBytes.toString());
});
});
});

View File

@ -1,5 +1,6 @@
import {expect} from "chai";
import {hexToBytes, bytesToHex} from "../../../src/helpers/hex";
import {hexToBytesNode} from "../../util";
describe("helpers / hex", () => {
const testCases: {id: string; hex: string}[] = [
@ -23,7 +24,3 @@ describe("helpers / hex", () => {
});
}
});
function hexToBytesNode(hex: string): Buffer {
return Buffer.from(hex.replace("0x", ""), "hex");
}