Skip to content

Commit 5de2096

Browse files
OttoAllmendingerllm-git
andcommitted
feat(utxo-staking): base64 encoding for Babylon protocol signatures
Add proper base64 and hex string handling for Babylon protocol signatures, returning consistently base64-encoded results from signMessage method. This maintains compatibility with Babylon expectations. Issue: BTC-2032 Co-authored-by: llm-git <[email protected]>
1 parent 0bb18bf commit 5de2096

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

modules/utxo-staking/src/babylon/delegationMessage.ts

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,38 @@ import { BabylonNetworkLike, toBitcoinJsNetwork } from './network';
1919

2020
export type ValueWithTypeUrl<T> = { typeUrl: string; value: T };
2121

22+
/**
23+
* Decode a hex or base64 encoded string and check if the length is valid.
24+
* @param v
25+
* @param encoding
26+
*/
27+
function decodeCheck(v: string, encoding: 'hex' | 'base64') {
28+
const result = Buffer.from(v, encoding);
29+
if (result.toString(encoding).length !== v.length) {
30+
throw new Error(`Invalid ${encoding} encoding`);
31+
}
32+
return result;
33+
}
34+
35+
/**
36+
* Convert a Buffer or string to a base64 encoded string.
37+
* @param v
38+
*/
39+
function toBase64(v: Buffer | string) {
40+
if (typeof v === 'string') {
41+
for (const encoding of ['base64', 'hex'] as const) {
42+
try {
43+
return toBase64(decodeCheck(v, encoding));
44+
} catch (e) {
45+
// try next
46+
}
47+
}
48+
throw new Error(`Invalid base64 or hex encoding: ${v}`);
49+
}
50+
51+
return v.toString('base64');
52+
}
53+
2254
export function getSignedPsbt(
2355
psbt: bitcoinjslib.Psbt,
2456
descriptor: Descriptor,
@@ -106,6 +138,12 @@ export function getBtcProviderForECKey(
106138
}
107139

108140
return {
141+
/**
142+
* @param signingStep
143+
* @param message
144+
* @param type
145+
* @returns Base64 encoded string
146+
*/
109147
async signMessage(
110148
signingStep: vendor.SigningStep,
111149
message: string,
@@ -114,9 +152,9 @@ export function getBtcProviderForECKey(
114152
assert(signingStep === 'proof-of-possession');
115153
switch (type) {
116154
case 'ecdsa':
117-
return stakerKey.sign(Buffer.from(message, 'hex')).toString('hex');
155+
return toBase64(stakerKey.sign(Buffer.from(message, 'hex')));
118156
case 'bip322-simple':
119-
return signBip322Simple(message);
157+
return toBase64(signBip322Simple(message));
120158
default:
121159
throw new Error(`unexpected signing step: ${signingStep}`);
122160
}

0 commit comments

Comments
 (0)