From 65939dbe9d2555444a09374849bef33c0a641d81 Mon Sep 17 00:00:00 2001 From: Jaco Date: Thu, 12 May 2022 11:14:34 +0200 Subject: [PATCH] Signed conversion on empty u8a (#1484) --- packages/util/src/u8a/toBn.spec.ts | 43 +++++++++++++++++++++++++----- packages/util/src/u8a/toBn.ts | 4 +-- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/packages/util/src/u8a/toBn.spec.ts b/packages/util/src/u8a/toBn.spec.ts index 5d8e06e53..1c7951d91 100644 --- a/packages/util/src/u8a/toBn.spec.ts +++ b/packages/util/src/u8a/toBn.spec.ts @@ -30,13 +30,42 @@ describe('u8aToBn', (): void => { ).toBe('3412'); }); - it('converts empty', (): void => { - expect( - u8aToBn( - new Uint8Array(), - { isLe: true } - ).toString(16) - ).toBe('0'); + describe('empty creation', (): void => { + it('handles unsigned (le)', (): void => { + expect( + u8aToBn( + new Uint8Array(), + { isLe: true } + ).toString(16) + ).toBe('0'); + }); + + it('handles signed (le)', (): void => { + expect( + u8aToBn( + new Uint8Array(), + { isLe: true, isNegative: true } + ).toString(16) + ).toBe('0'); + }); + + it('handles unsigned (be)', (): void => { + expect( + u8aToBn( + new Uint8Array(), + { isLe: false } + ).toString(16) + ).toBe('0'); + }); + + it('handles signed (be)', (): void => { + expect( + u8aToBn( + new Uint8Array(), + { isLe: false, isNegative: true } + ).toString(16) + ).toBe('0'); + }); }); it('handles negative numbers (little-endian)', (): void => { diff --git a/packages/util/src/u8a/toBn.ts b/packages/util/src/u8a/toBn.ts index 095b431cc..05c5896ec 100644 --- a/packages/util/src/u8a/toBn.ts +++ b/packages/util/src/u8a/toBn.ts @@ -26,7 +26,7 @@ import { objectSpread } from '../object/spread'; * ``` */ export function u8aToBn (value: Uint8Array, options: ToBnOptions | boolean = {}): BN { - // NOTE: This is the same process as followed in the hex conversion + // NOTE: This is the same process as followed in the hextoBn conversion // For Uint8Array, default to LE const { isLe, isNegative } = objectSpread( { isLe: true, isNegative: false }, @@ -36,7 +36,7 @@ export function u8aToBn (value: Uint8Array, options: ToBnOptions | boolean = {}) ); const bn = new BN(value, isLe ? 'le' : 'be'); - return isNegative + return isNegative && value.length ? bn.fromTwos(value.length * 8) : bn; }