Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RAW_P2TR address type with signing capability #17

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/address/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { bitcoin } from "../bitcoin-core";
import { NetworkType, toPsbtNetwork } from "../network";
import { AddressType } from "../types";
import {toXOnly} from "../utils";

/**
* Convert public key to bitcoin payment object.
Expand Down Expand Up @@ -38,6 +39,11 @@ export function publicKeyToPayment(
network,
redeem: data,
});
} else if (type === AddressType.RAW_P2TR) {
return bitcoin.payments.p2tr({
pubkey: toXOnly(pubkey),
network,
});
}
}

Expand Down
40 changes: 35 additions & 5 deletions src/keyring/simple-keyring.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { isTaprootInput } from "bitcoinjs-lib/src/psbt/bip371";
import { isTaprootInput, serializeTaprootSignature } from "bitcoinjs-lib/src/psbt/bip371";
import { bech32 } from "bech32";
import { decode } from "bs58check";
import { EventEmitter } from "events";
import { ECPair, ECPairInterface, bitcoin } from "../bitcoin-core";
import {
signMessageOfDeterministicECDSA,
verifyMessageOfECDSA,
} from "../message";
import { tweakSigner } from "../utils";
import {toXOnly, tweakSigner} from "../utils";

const type = "Simple Key Pair";

Expand All @@ -31,7 +32,10 @@ export class SimpleKeyring extends EventEmitter {

this.wallets = privateKeys.map((key) => {
let buf: Buffer;
if (key.length === 64) {
if (key.startsWith('nsec')) {
const { words } = bech32.decode(key)
buf = Buffer.from(new Uint8Array(bech32.fromWords(words)))
} else if (key.length === 64) {
// privateKey
buf = Buffer.from(key, "hex");
} else {
Expand Down Expand Up @@ -66,17 +70,43 @@ export class SimpleKeyring extends EventEmitter {
publicKey: string;
sighashTypes?: number[];
disableTweakSigner?: boolean;
rawTaprootPubkey?: boolean;
}[],
opts?: any
) {
inputs.forEach((input) => {
const keyPair = this._getPrivateKeyFor(input.publicKey);
const isTapInput = isTaprootInput(psbt.data.inputs[input.index]);
if (
isTaprootInput(psbt.data.inputs[input.index]) &&
!input.disableTweakSigner
isTapInput &&
!input.disableTweakSigner &&
!input.rawTaprootPubkey
) {
const signer = tweakSigner(keyPair, opts);
psbt.signInput(input.index, signer, input.sighashTypes);
} else if (isTapInput && input.rawTaprootPubkey) {
const inputAddressInfo = bitcoin.payments.p2tr({
pubkey: toXOnly(Buffer.from(input.publicKey, 'hex')),
network: this.network,
});
let hashType
if (!input.sighashTypes) {
hashType = bitcoin.Transaction.SIGHASH_DEFAULT
} else if (input.sighashTypes.length > 1) {
throw new Error('Only one sighash type is supported for raw taproot inputs')
} else {
hashType = input.sighashTypes[0]
}
const hashForSigning = (psbt as any).__CACHE.__TX.hashForWitnessV1(
input.index,
[inputAddressInfo.output],
[psbt.data.inputs[input.index].witnessUtxo.value],
hashType
);
const signature = keyPair.signSchnorr(hashForSigning);
psbt.updateInput(input.index, {
tapKeySig: serializeTaprootSignature(signature)
})
} else {
const signer = keyPair;
psbt.signInput(input.index, signer, input.sighashTypes);
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,5 @@ export enum AddressType {
P2WSH,
P2SH,
UNKNOWN,
RAW_P2TR, // for recoveries only
}
13 changes: 13 additions & 0 deletions test/address/address.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ const p2pkh_data = {
testnet_address: 'mxwqjnnPeuU5yY1yqJsDCQ9nYmicmGTBns',
}

const raw_p2tr_data = {
pubkey: '02a276a2f72b2581bbb325c9d51714bd65686a9af95d7df4d625b711d7203fd7ac',
mainnet_address: 'bc1p5fm29aetykqmhve9e823w99av45x4xhet47lf439kugawgpl67kqtgzm0z',
}

const invalid_data = {
pubkey: '',
mainnet_address: '',
Expand Down Expand Up @@ -106,6 +111,14 @@ describe('address', function () {
NetworkType.TESTNET
)
).eq(p2pkh_data.testnet_address, 'pubkey->p2pkh testnet')

expect(
publicKeyToAddress(
raw_p2tr_data.pubkey,
AddressType.RAW_P2TR,
NetworkType.MAINNET
)
).eq(raw_p2tr_data.mainnet_address, 'pubkey->raw_p2tr mainnet')
})
it('test function isValidAddress', async function () {
expect(
Expand Down
70 changes: 69 additions & 1 deletion test/keyring/simple-keyring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ const testAccount = {
address: "02b57a152325231723ee9faabba930108b19c11a391751572f380d71b447317ae7",
};

const testNsecAccount = {
nsec: "nsec17ynu3aayp7acykfe6fnrfwew30xlk5z2xa4kqvh6y3v5lkfc9gaqe8g5s6",
privateKey: "f127c8f7a40fbb825939d26634bb2e8bcdfb504a376b6032fa24594fd9382a3a",
publicKey: "02a276a2f72b2581bbb325c9d51714bd65686a9af95d7df4d625b711d7203fd7ac"
}

describe("bitcoin-simple-keyring", () => {
let keyring: SimpleKeyring;
beforeEach(() => {
Expand Down Expand Up @@ -40,6 +46,19 @@ describe("bitcoin-simple-keyring", () => {
});
});

describe("#handles an nsec formatted private key", function () {
it("properly imports nsec", async function () {
await keyring.deserialize([testNsecAccount.nsec]);
const publicKeys = await keyring.getAccounts();
console.log(publicKeys)
expect(publicKeys).length(1);
expect(publicKeys[0]).eq(testNsecAccount.publicKey);
const privateKeys = await keyring.serialize();
expect(privateKeys).length(1);
expect(privateKeys[0]).eq(testNsecAccount.privateKey);
});
});

describe("#constructor with a private key", function () {
it("has the correct addresses", async function () {
const newKeyring = new SimpleKeyring([testAccount.key]);
Expand Down Expand Up @@ -340,5 +359,54 @@ describe("bitcoin-simple-keyring", () => {
psbt.extractTransaction();
expect(psbt.getFee() == 500).to.be.true;
});

it("sign Raw P2TR input", async function () {
const network = bitcoin.networks.bitcoin;

const newKeyring = new SimpleKeyring();
await newKeyring.addAccounts(1);
const accounts = await newKeyring.getAccounts();
const pubkey = accounts[0];
const payment = bitcoin.payments.p2tr({
pubkey: toXOnly(Buffer.from(pubkey, "hex")),
network,
});

const prevoutHash = Buffer.from(
"0000000000000000000000000000000000000000000000000000000000000000",
"hex"
);
const value = 10000;
const prevoutIndex = 0xffffffff;
const sequence = 0;
const txToSpend = new bitcoin.Transaction();
txToSpend.version = 0;
txToSpend.addInput(prevoutHash, prevoutIndex, sequence);
txToSpend.addOutput(payment.output!, value);

const psbt = new bitcoin.Psbt({ network });
psbt.addInput({
hash: txToSpend.getHash(),
index: 0,
sequence: 0,
witnessUtxo: {
script: payment.output!,
value,
},
});
psbt.addOutput({
address: payment.address!,
value: value - 500,
});
await newKeyring.signTransaction(
psbt,
[{ index: 0, publicKey: pubkey, rawTaprootPubkey: true }],
{ network: bitcoin.networks.bitcoin }
);

psbt.finalizeAllInputs();
psbt.extractTransaction();
expect(psbt.getFee() == 500).to.be.true;
});
});
});
});