@@ -19,6 +19,38 @@ import { BabylonNetworkLike, toBitcoinJsNetwork } from './network';
1919
2020export 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+
2254export 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