Fix large-value Compact encoding (#281)
This commit is contained in:
committed by
Amaury Martiny
parent
32daf3636a
commit
5585a16814
@@ -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)]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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)];
|
||||
}
|
||||
|
||||
@@ -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])
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user