From ae4ba8bec1688194c3bcd1dcfd5069a55cda08c5 Mon Sep 17 00:00:00 2001 From: texuf Date: Sat, 11 Jan 2025 23:03:21 -0800 Subject: [PATCH] Move bigIntToBytes to the utils (dlog) package (#2021) I need to use it in the crypto package --- packages/dlog/src/binary.ts | 18 ++++++++++++++++++ packages/sdk/src/sign.ts | 26 +++++++------------------- 2 files changed, 25 insertions(+), 19 deletions(-) diff --git a/packages/dlog/src/binary.ts b/packages/dlog/src/binary.ts index 874a51a62a..eea89a8ada 100644 --- a/packages/dlog/src/binary.ts +++ b/packages/dlog/src/binary.ts @@ -60,3 +60,21 @@ export function bin_equal( } return equalsBytes(a, b) } + +// Returns the absolute value of this BigInt as a big-endian byte array +export function bigIntToBytes(value: bigint): Uint8Array { + const abs = value < 0n ? -value : value + // Calculate the byte length needed to represent the BigInt + const byteLength = Math.ceil(abs.toString(16).length / 2) + + // Create a buffer of the required length + const buffer = new Uint8Array(byteLength) + + // Fill the buffer with the big-endian representation of the BigInt + let temp = abs + for (let i = byteLength - 1; i >= 0; i--) { + buffer[i] = Number(temp & 0xffn) // Extract last 8 bits + temp >>= 8n // Shift right by 8 bits + } + return buffer +} diff --git a/packages/sdk/src/sign.ts b/packages/sdk/src/sign.ts index aba0dc3db4..103e688459 100644 --- a/packages/sdk/src/sign.ts +++ b/packages/sdk/src/sign.ts @@ -1,5 +1,11 @@ import { PlainMessage } from '@bufbuild/protobuf' -import { bin_equal, bin_fromHexString, bin_toHexString, check } from '@river-build/dlog' +import { + bigIntToBytes, + bin_equal, + bin_fromHexString, + bin_toHexString, + check, +} from '@river-build/dlog' import { isDefined, assert, hasElements } from './check' import { Envelope, @@ -305,24 +311,6 @@ function bigintToUint8Array64(num: bigint, endianMode: 'bigEndian' | 'littleEndi return new Uint8Array(buffer) } -// Returns the absolute value of this BigInt as a big-endian byte array -function bigIntToBytes(value: bigint): Uint8Array { - const abs = value < 0n ? -value : value - // Calculate the byte length needed to represent the BigInt - const byteLength = Math.ceil(abs.toString(16).length / 2) - - // Create a buffer of the required length - const buffer = new Uint8Array(byteLength) - - // Fill the buffer with the big-endian representation of the BigInt - let temp = abs - for (let i = byteLength - 1; i >= 0; i--) { - buffer[i] = Number(temp & 0xffn) // Extract last 8 bits - temp >>= 8n // Shift right by 8 bits - } - return buffer -} - function pushByteToUint8Array(arr: Uint8Array, byte: number): Uint8Array { const ret = new Uint8Array(arr.length + 1) ret.set(arr)