Skip to content

Commit 61aa6a1

Browse files
Merge pull request #5816 from BitGo/BTC-1933.add-xonly-pubkey-utils
feat(utxo-core): add toXOnlyPublicKey utility function
2 parents b2a5fea + bc527b5 commit 61aa6a1

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

modules/utxo-core/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ export * as descriptor from './descriptor';
33
export * as testutil from './testutil';
44
export * from './dustThreshold';
55
export * from './Output';
6+
export * from './xOnlyPubkey';
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export function toXOnlyPublicKey(b: Buffer): Buffer {
2+
if (b.length === 33) {
3+
if (b[0] === 0x02 || b[0] === 0x03) {
4+
return b.subarray(1);
5+
} else {
6+
throw new Error(`invalid pubkey leading byte ${b.subarray(0, 1).toString('hex')}`);
7+
}
8+
}
9+
10+
if (b.length === 32) {
11+
return b;
12+
}
13+
14+
throw new Error(`invalid pubkey buffer length ${b.length}`);
15+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import assert from 'assert';
2+
3+
import { toXOnlyPublicKey } from '../src';
4+
5+
describe('xOnlyPubkey', function () {
6+
it('converts to X-Only pubkey', function () {
7+
const buf32 = Buffer.alloc(32, 0);
8+
assert.deepStrictEqual(toXOnlyPublicKey(Buffer.concat([Buffer.from([0x02]), buf32])), buf32);
9+
assert.deepStrictEqual(toXOnlyPublicKey(Buffer.concat([Buffer.from([0x03]), buf32])), buf32);
10+
assert.deepStrictEqual(toXOnlyPublicKey(buf32), buf32);
11+
assert.throws(() => toXOnlyPublicKey(Buffer.concat([Buffer.from([0x04]), buf32])));
12+
assert.throws(() => toXOnlyPublicKey(Buffer.alloc(31)));
13+
});
14+
});

0 commit comments

Comments
 (0)