Skip to content

Commit

Permalink
Update bigIntToHex to take an expected length
Browse files Browse the repository at this point in the history
  • Loading branch information
r-n-o committed Oct 17, 2023
1 parent 8f6df72 commit ee45879
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
13 changes: 8 additions & 5 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -396,13 +396,16 @@ <h2>Message log</h2>
/**
* Converts a `BigInt` into a hex encoded string
* @param {BigInt} num
* @param {number} length expected length of the resulting hex string
* @return {string}
*/
var bigIntToHex = function(num) {
var bigIntToHex = function(num, length) {
var hexString = num.toString(16);
// Add an extra 0 to the start of the string to get a valid hex string (even length)
// (e.g. 0x0123 instead of 0x123)
return hexString.padStart(Math.ceil(hexString.length/2)*2, 0)
if (hexString.length > length) {
throw new Error("number cannot fit in a hex string of " + length + " characters");
}
// Add an extra 0 to the start of the string to get to `length`
return hexString.padStart(length, 0)
}

/**
Expand Down Expand Up @@ -457,7 +460,7 @@ <h2>Message log</h2>
throw new Error("y is out of range");
}

var uncompressedHexString = "04" + bigIntToHex(x) + bigIntToHex(y);
var uncompressedHexString = "04" + bigIntToHex(x, 64) + bigIntToHex(y, 64);
return uint8arrayFromHexString(uncompressedHexString)
}

Expand Down
9 changes: 6 additions & 3 deletions index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,12 @@ describe("TKHQ", () => {
})

it("contains bigIntToHex", () => {
expect(TKHQ.bigIntToHex(BigInt(1))).toEqual("01");
expect(TKHQ.bigIntToHex(BigInt(23))).toEqual("17");
expect(TKHQ.bigIntToHex(BigInt(255))).toEqual("ff");
expect(TKHQ.bigIntToHex(BigInt(1, 1))).toEqual("1");
expect(TKHQ.bigIntToHex(BigInt(1), 2)).toEqual("01");
expect(TKHQ.bigIntToHex(BigInt(1), 4)).toEqual("0001");
expect(TKHQ.bigIntToHex(BigInt(23), 2)).toEqual("17");
expect(TKHQ.bigIntToHex(BigInt(255), 2)).toEqual("ff");
expect(() => { TKHQ.bigIntToHex(BigInt(256), 2) }).toThrow("number cannot fit in a hex string of 2 characters");
})

it("logs messages and sends messages up", async () => {
Expand Down

0 comments on commit ee45879

Please sign in to comment.