Skip to content

Commit

Permalink
Move bigIntToBytes to the utils (dlog) package (#2021)
Browse files Browse the repository at this point in the history
I need to use it in the crypto package
  • Loading branch information
texuf authored Jan 12, 2025
1 parent 6357e7a commit ae4ba8b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 19 deletions.
18 changes: 18 additions & 0 deletions packages/dlog/src/binary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
26 changes: 7 additions & 19 deletions packages/sdk/src/sign.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit ae4ba8b

Please sign in to comment.