Skip to content

Commit 29a775f

Browse files
committed
Catch error raised by msgPack.decode when format is not recognised
Instead of throwing an error, return null when decoding failed
1 parent eb26d38 commit 29a775f

File tree

3 files changed

+32
-10
lines changed

3 files changed

+32
-10
lines changed

src/extraData.ts

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,30 @@ export function encode(extraData: ExtraData): string {
3030
}
3131

3232
export function decode(encodedExtraData: string): ExtraData {
33-
if (encodedExtraData.startsWith(MSG_PACK_ID)) {
34-
const extraData: ExtraDataEncoding = msgPack.decode(
35-
hexToArray(encodedExtraData.slice(MSG_PACK_ID.length))
36-
)
37-
return {
38-
paymentRequestId: arrayToHex(extraData.prId),
39-
messageId: arrayToHex(extraData.mgId)
40-
}
41-
} else {
33+
if (!encodedExtraData.startsWith(MSG_PACK_ID)) {
4234
return null
4335
}
36+
37+
const encodedExtraDataArray = hexToArray(
38+
encodedExtraData.slice(MSG_PACK_ID.length)
39+
)
40+
41+
let extraData: ExtraDataEncoding
42+
try {
43+
extraData = msgPack.decode(encodedExtraDataArray)
44+
} catch (error) {
45+
if (error instanceof RangeError) {
46+
// The encodedExtraData starts with MSG_PACK_ID but does not follow the expected format
47+
return null
48+
} else {
49+
throw error
50+
}
51+
}
52+
53+
return {
54+
paymentRequestId: arrayToHex(extraData.prId),
55+
messageId: arrayToHex(extraData.mgId)
56+
}
4457
}
4558

4659
function remove0xPrefix(hexString) {

tests/e2e/Payment.test.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -498,7 +498,10 @@ describe('e2e', () => {
498498
network.address,
499499
user3.address,
500500
transferValue,
501-
{ extraData, addMessageId: false }
501+
{
502+
extraData,
503+
addMessageId: false
504+
}
502505
)
503506
await tl1.payment.confirm(transfer.rawTx)
504507
await wait()

tests/unit/extraData.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,5 +25,11 @@ describe('unit', () => {
2525
}
2626
expect(extraData).to.be.deep.eq(decode(encode(extraData)))
2727
})
28+
29+
it('should not get an error when decoding wrongly formed extra data', () => {
30+
const encodedExtraData = '0x544c4d501' + '12345678'.repeat(10)
31+
const decoded = decode(encodedExtraData)
32+
expect(decoded).to.equal(null)
33+
})
2834
})
2935
})

0 commit comments

Comments
 (0)