Skip to content

Commit 9dbd8ef

Browse files
authored
fix(tlock): reject malformed hex input (#179)
Co-authored-by: emrekayat <237104270+emrekayat@users.noreply.github.com>
1 parent 257c10d commit 9dbd8ef

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

packages/tlock/src/commitment.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
commitment,
77
decodeBidPreimage,
88
encodeBidPreimage,
9+
fromHex,
910
i128ToBeBytes,
1011
toHex,
1112
} from "./commitment.js";
@@ -51,3 +52,23 @@ test("rejects out-of-range and malformed inputs", () => {
5152
assert.throws(() => encodeBidPreimage(1n, new Uint8Array(31)));
5253
assert.throws(() => decodeBidPreimage(new Uint8Array(47)));
5354
});
55+
56+
test("fromHex decodes lowercase, uppercase, and prefixed values", () => {
57+
const expected = [0xab, 0xcd, 0xef];
58+
assert.deepEqual([...fromHex("abcdef")], expected);
59+
assert.deepEqual([...fromHex("ABCDEF")], expected);
60+
assert.deepEqual([...fromHex("0xAbCdEf")], expected);
61+
assert.deepEqual([...fromHex("0XABCDEF")], expected);
62+
});
63+
64+
test("fromHex accepts empty input as an empty byte array", () => {
65+
assert.deepEqual([...fromHex("")], []);
66+
assert.deepEqual([...fromHex("0x")], []);
67+
});
68+
69+
test("fromHex rejects odd-length and non-hex input", () => {
70+
assert.throws(() => fromHex("abc"), /odd hex length/);
71+
assert.throws(() => fromHex("zz"), /invalid hex characters/);
72+
assert.throws(() => fromHex("12 3"), /invalid hex characters/);
73+
assert.throws(() => fromHex("0x12gg"), /invalid hex characters/);
74+
});

packages/tlock/src/commitment.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,11 @@ export function toHex(bytes: Uint8Array): string {
7878
}
7979

8080
export function fromHex(hex: string): Uint8Array {
81-
const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
81+
const clean = /^0x/i.test(hex) ? hex.slice(2) : hex;
8282
if (clean.length % 2 !== 0) throw new Error("odd hex length");
83+
if (!/^[0-9a-fA-F]*$/.test(clean)) {
84+
throw new Error("invalid hex characters");
85+
}
8386
const out = new Uint8Array(clean.length / 2);
8487
for (let i = 0; i < out.length; i++) {
8588
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);

0 commit comments

Comments
 (0)