From 86001d51f94e23c3a9923accd27ba59bf18dd577 Mon Sep 17 00:00:00 2001 From: Pi Delport Date: Thu, 28 Apr 2022 22:18:39 +0200 Subject: [PATCH] fix(ripple-keypairs): make bytesToHex work with typed arrays (Uint8Array) (#1975) This works the same as before for Array inputs, but it should now also work correctly with a wider range of Iterable or ArrayLike input types. In particular, this makes it work with typed arrays such as Uint8Array, which previously produced invalid output due to the hex numerals being coerced back to the element type before the call to `join('')`. --- packages/ripple-keypairs/HISTORY.md | 4 ++++ packages/ripple-keypairs/src/utils.ts | 12 +++++------- packages/ripple-keypairs/test/utils-test.js | 8 ++++++++ 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/packages/ripple-keypairs/HISTORY.md b/packages/ripple-keypairs/HISTORY.md index e4f6f269..8bb620f9 100644 --- a/packages/ripple-keypairs/HISTORY.md +++ b/packages/ripple-keypairs/HISTORY.md @@ -1,5 +1,9 @@ # ripple-keypairs Release History +## Unreleased +- Extend `bytesToHex` to work correctly with any input type accepted by `Array.from`. + In particular, it now produces correct output for typed arrays such as `UInt8Array`. + ## 1.1.1 (2021-12-1) - Fix issue where npm < 7 was not allowed to install the library diff --git a/packages/ripple-keypairs/src/utils.ts b/packages/ripple-keypairs/src/utils.ts index 100b3b65..f5542ae4 100644 --- a/packages/ripple-keypairs/src/utils.ts +++ b/packages/ripple-keypairs/src/utils.ts @@ -2,13 +2,11 @@ import * as assert from 'assert' import * as hashjs from 'hash.js' import * as BN from 'bn.js' -function bytesToHex(a): string { - return a - .map((byteValue) => { - const hex = byteValue.toString(16).toUpperCase() - return hex.length > 1 ? hex : `0${hex}` - }) - .join('') +function bytesToHex(a: Iterable | ArrayLike): string { + return Array.from(a, (byteValue) => { + const hex = byteValue.toString(16).toUpperCase() + return hex.length > 1 ? hex : `0${hex}` + }).join('') } function hexToBytes(a): number[] { diff --git a/packages/ripple-keypairs/test/utils-test.js b/packages/ripple-keypairs/test/utils-test.js index 3fb8f632..5fe37726 100644 --- a/packages/ripple-keypairs/test/utils-test.js +++ b/packages/ripple-keypairs/test/utils-test.js @@ -11,4 +11,12 @@ describe('utils', () => { it('hexToBytes - DEADBEEF', () => { assert.deepEqual(utils.hexToBytes('DEADBEEF'), [222, 173, 190, 239]) }) + + it('bytesToHex - DEADBEEF', () => { + assert.deepEqual(utils.bytesToHex([222, 173, 190, 239]), 'DEADBEEF') + }); + + it('bytesToHex - DEADBEEF (Uint8Array)', () => { + assert.deepEqual(utils.bytesToHex(new Uint8Array([222, 173, 190, 239])), 'DEADBEEF') + }); })