Fix large-value Compact encoding (#281)

This commit is contained in:
Jaco Greeff
2018-12-21 10:04:11 +01:00
committed by Amaury Martiny
parent 32daf3636a
commit 5585a16814
6 changed files with 19 additions and 38 deletions
+2 -2
View File
@@ -33,7 +33,7 @@ describe('compactFromU8a', () => {
it('decodes from same u32 as u64 encoded value (full, default)', () => {
expect(
compactFromU8a(new Uint8Array([3, 249, 255, 255, 255]), 64)
).toEqual([9, new BN(0xfffffff9)]);
compactFromU8a(new Uint8Array([3 + ((4 - 4) << 2), 249, 255, 255, 255]), 64)
).toEqual([5, new BN(0xfffffff9)]);
});
});
+5 -1
View File
@@ -35,7 +35,11 @@ export default function compactFromU8a (_input: Uint8Array | string, bitLength:
return [4, u8aToBn(input.slice(0, 4), true).shrn(2)];
}
const offset = 1 + (bitLength / 8);
const length = new BN(input[0])
.shrn(2) // clear flag
.addn(4) // add 4 for base length
.toNumber();
const offset = 1 + length;
return [offset, u8aToBn(input.subarray(1, offset), true)];
}
+1 -1
View File
@@ -51,7 +51,7 @@ describe('encode', () => {
expect(
compactToU8a(0xfffffff9)
).toEqual(
new Uint8Array([3, 249, 255, 255, 255])
new Uint8Array([3 + ((4 - 4) << 2), 249, 255, 255, 255])
);
});
});
+6 -1
View File
@@ -39,7 +39,12 @@ export default function compactToU8a (_value: BN | number, bitLength: BitLength
return u8aConcat(
new Uint8Array([
0b11
// FIXME For optimal encoding, detemine actual used bit (do not just use max)
new BN(bitLength / 8)
.subn(4) // at least 4
.shln(2) // clear low
.addn(0b11) // add flag
.toNumber()
]),
bnToU8a(value, bitLength, true)
);