From 7b9ca4ad6ec06582175f5e27d22df330f5abd333 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Tue, 25 Dec 2018 13:29:33 +0100 Subject: [PATCH] Minimum number of bytes for compact encoding (#285) * Minimum number of bytes for compact encoding * Cleanup comment --- packages/util/src/compact/toU8a.spec.ts | 2 +- packages/util/src/compact/toU8a.ts | 20 +++++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/packages/util/src/compact/toU8a.spec.ts b/packages/util/src/compact/toU8a.spec.ts index ed194bdfa..d5528bdbf 100644 --- a/packages/util/src/compact/toU8a.spec.ts +++ b/packages/util/src/compact/toU8a.spec.ts @@ -58,7 +58,7 @@ describe('encode', () => { it('encodes a large value', () => { expect( compactToU8a( - new BN('5af3107a4000', 16) + new BN('00005af3107a4000', 16) ) ).toEqual( new Uint8Array([3 + ((6 - 4) << 2), 0x00, 0x40, 0x7a, 0x10, 0xf3, 0x5a]) diff --git a/packages/util/src/compact/toU8a.ts b/packages/util/src/compact/toU8a.ts index 89c106b36..cbc1ce8d3 100644 --- a/packages/util/src/compact/toU8a.ts +++ b/packages/util/src/compact/toU8a.ts @@ -35,19 +35,21 @@ export default function compactToU8a (_value: BN | number): Uint8Array { return bnToU8a(value.shln(2).addn(0b10), 32, true); } - // Number of bytes needed to represent `value` - const bytesNeeded = Math.ceil(value.bitLength() / 8); + const u8a = bnToU8a(value); + let length = u8a.length; - assert(bytesNeeded >= 4, 'Previous tests match anyting less than 2^30; qed'); + // adjust to the minimum number of bytes + while (u8a[length - 1] === 0) { + length--; + } + + assert(length >= 4, 'Previous tests match anyting less than 2^30; qed'); return u8aConcat( new Uint8Array([ - new BN(bytesNeeded) - .subn(4) // how many bytes more than 4 do we need? - .shln(2) // clear low - .addn(0b11) // add flag - .toNumber() + // substract 4 as minimum (also catered for in decoding) + ((length - 4) << 2) + 0b11 ]), - bnToU8a(value) + u8a.subarray(0, length) ); }