Skip to content

Commit db4ee77

Browse files
committed
improve ecsign logic
1 parent 059ce3b commit db4ee77

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

src/signature.ts

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,24 @@ export function ecsign(msgHash: Buffer, privateKey: Buffer, chainId: any): any {
2828
const r = Buffer.from(signature.slice(0, 32))
2929
const s = Buffer.from(signature.slice(32, 64))
3030

31-
if (!chainId) {
32-
return { r, s, v: recovery + 27 }
33-
} else {
34-
const chainIdBN = toType(chainId, TypeOutput.BN)
35-
const vValue = chainIdBN
36-
.muln(2)
37-
.addn(35)
38-
.addn(recovery)
39-
const v = typeof chainId === 'number' ? vValue.toNumber() : vValue.toArrayLike(Buffer)
31+
if (!chainId || typeof chainId === 'number') {
32+
// return legacy type ECDSASignature (deprecated in favor of ECDSASignatureBuffer to handle large chainIds)
33+
if (chainId && !Number.isSafeInteger(chainId)) {
34+
throw new Error(
35+
'The provided number is greater than MAX_SAFE_INTEGER (please use an alternative input type)'
36+
)
37+
}
38+
const v = chainId ? recovery + (chainId * 2 + 35) : recovery + 27
4039
return { r, s, v }
4140
}
41+
42+
const chainIdBN = toType(chainId, TypeOutput.BN)
43+
const v = chainIdBN
44+
.muln(2)
45+
.addn(35)
46+
.addn(recovery)
47+
.toArrayLike(Buffer)
48+
return { r, s, v }
4249
}
4350

4451
function calculateSigRecovery(v: BNLike, chainId?: BNLike): BN {

0 commit comments

Comments
 (0)