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

update the staking command #1

Open
wants to merge 4 commits into
base: main
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: 4 additions & 2 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ program
.description("Stake BTC")
.requiredOption("-acc, --account <account>", "The Bitcon address used to stake.")
.requiredOption("-privkey, --privatekey <privatekey>", "The private key used to sign the transaction, which should be associated with --account. Hex format.")
.requiredOption("-amt, --amount <amount>", "Amount of BTC to stake, measured in SAT.")
.option("-amt, --amount <amount>", "Amount of BTC to stake, measured in SAT, default to all amount of BTC")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

71 core

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0x4092f0eF91bF408aad7B611915A82537BAaa573b

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

71 core

.option("-bn, --bitcoinnetwork <bitcoinnetwork>", "The Bitcoin network to operate on, choose between 1~2. 1)Mainnet 2)Testnet, default to 1)Mainnet.")
.option("-cn, --corenetwork <corenetwork>", "The Core network to transmit the stake transaction to, choose between 1~3. 1)Mainnet 2)Devnet 3)Testnet, default to 1)Mainnet.")
.requiredOption("-lt, --locktime <locktime>", "The unix timestamp in seconds to lock the BTC assets up to. e.g. 1711983981")
Expand All @@ -55,7 +55,8 @@ program
.requiredOption("-vaddr, --validatoraddress <validatoraddress>", "Core validator address to stake to.")
.option("-w, --witness", "Use segwit or not.")
.option("-br, --bitcoinrpc <bitcoinrpc>", "The Bitcoin RPC service to use, default to https://mempool.space/. ")
.option("--fee <fee>", "Transaction fee s)slow a)average f)fast, please choose in (s, a ,f) OR a customized number in SAT, default to a)average.")
.option("--fee <fee>", "Transaction fee in every bytes s)slow a)average f)fast, please choose in (s, a ,f) OR a customized number in SAT, default to a)average.")
.option("-r, --redeemscript <redeemscript>", "The redeem script which was returned in the stake action.")
.action((args) => __awaiter(void 0, void 0, void 0, function* () {
const bitcoinnetwork = constant_1.BitcoinNetworkMap[args.bitcoinnetwork];
const corenetwork = constant_1.CoreNetworkMap[args.corenetwork];
Expand All @@ -73,6 +74,7 @@ program
witness: args.witness,
bitcoinRpc: args.bitcoinrpc,
fee: fee || args.fee,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0x4092f0eF91bF408aad7B611915A82537BAaa573b

redeemScript: args.redeemscript,
});
}));
program
Expand Down
12 changes: 9 additions & 3 deletions dist/src/address.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,23 @@ var __importStar = (this && this.__importStar) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAddressType = void 0;
const bitcoin = __importStar(require("bitcoinjs-lib"));
function getAddressType(address, network = bitcoin.networks.bitcoin) {
function getAddressType(address, network = bitcoin.networks.bitcoin, redeemScript) {
if (address.startsWith(`${network.bech32}1p`)) {
bitcoin.address.fromBech32(address);
return "p2tr";
}
if (address.startsWith(network.bech32)) {
bitcoin.address.fromBech32(address);
return "p2wpkh";
const decodeBech32 = bitcoin.address.fromBech32(address);
if (decodeBech32.data.length === 20)
return "p2wpkh";
if (decodeBech32.data.length === 32)
return "p2wsh";
}
const base58Data = bitcoin.address.fromBase58Check(address);
if (base58Data.version === Number(network.scriptHash)) {
if (redeemScript) {
return "p2sh";
}
return "p2sh-p2wpkh";
}
if (base58Data.version === Number(network.pubKeyHash)) {
Expand Down
10 changes: 4 additions & 6 deletions dist/src/stake.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ exports.stake = void 0;
const constant_1 = require("./constant");
const transaction_1 = require("./transaction");
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const stake = (_a) => __awaiter(void 0, [_a], void 0, function* ({ witness = false, lockTime, account, amount, validatorAddress, rewardAddress, privateKey, publicKey, coreNetwork = "mainnet", bitcoinNetwork = "mainnet", bitcoinRpc = "mempool", fee = "avg", }) {
const stake = (_a) => __awaiter(void 0, [_a], void 0, function* ({ witness = false, lockTime, account, amount, validatorAddress, rewardAddress, privateKey, publicKey, coreNetwork = "mainnet", bitcoinNetwork = "mainnet", bitcoinRpc = "mempool", fee = "avg", redeemScript, }) {
if (!lockTime) {
throw new Error("LockTime should not be empty");
}
Expand All @@ -29,16 +29,13 @@ const stake = (_a) => __awaiter(void 0, [_a], void 0, function* ({ witness = fal
if (!privateKey) {
throw new Error("privateKey should not be empty");
}
if (!amount) {
throw new Error("Amount should not be empty");
}
if (!validatorAddress) {
throw new Error("validatorAddress should not be empty");
}
if (!rewardAddress) {
throw new Error("rewardAddress should not be empty");
}
const { txId, scriptAddress, redeemScript } = yield (0, transaction_1.buildStakeTransaction)({
const { txId, scriptAddress, script } = yield (0, transaction_1.buildStakeTransaction)({
witness,
lockTime: Number(lockTime),
account,
Expand All @@ -52,9 +49,10 @@ const stake = (_a) => __awaiter(void 0, [_a], void 0, function* ({ witness = fal
coreNetwork,
bitcoinRpc,
fee,
redeemScript,
});
console.log(`txId: ${txId}`);
console.log(`address: ${scriptAddress}`);
console.log(`redeemScript: ${redeemScript}`);
console.log(`redeemScript: ${script}`);
});
exports.stake = stake;
113 changes: 94 additions & 19 deletions dist/src/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,13 @@ const validatorSignature = (pubkey, msghash, signature) => ECPair.fromPublicKey(
* @param {StakeParams} params - Stake parameters
* @returns {Promise<{ txId: string; scriptAddress: string; cltvScript: string; }>} - Transaction ID, script address, and CLTV script
*/
const buildStakeTransaction = (_a) => __awaiter(void 0, [_a], void 0, function* ({ witness, lockTime, account, amount, validatorAddress, rewardAddress, publicKey, privateKey, bitcoinNetwork, coreNetwork, type, bitcoinRpc, fee, }) {
const buildStakeTransaction = (_a) => __awaiter(void 0, [_a], void 0, function* ({ witness, lockTime, account, amount, validatorAddress, rewardAddress, publicKey, privateKey, bitcoinNetwork, coreNetwork, type, bitcoinRpc, fee, redeemScript, }) {
const chainId = constant_2.CoreChainNetworks[coreNetwork].chainId;
const network = bitcoinNetwork == "mainnet"
? bitcoin.networks.bitcoin
: bitcoin.networks.testnet;
let isRestaking = false;
let preStakeOptions;
const provider = new provider_1.Provider({
network,
bitcoinRpc,
Expand All @@ -71,9 +73,9 @@ const buildStakeTransaction = (_a) => __awaiter(void 0, [_a], void 0, function*
if (!publicKey) {
publicKey = keyPair.publicKey.toString("hex");
}
let addressType = (0, address_1.getAddressType)(account, network);
//We only support P2PKH P2WPKH P2SH-P2WPKH P2TR address
let payment;
let addressType = (0, address_1.getAddressType)(account, network, redeemScript);
if (addressType === "p2pkh") {
payment = bitcoin.payments.p2pkh({
pubkey: keyPair.publicKey,
Expand Down Expand Up @@ -102,6 +104,26 @@ const buildStakeTransaction = (_a) => __awaiter(void 0, [_a], void 0, function*
network,
});
}
else if (redeemScript) {
const redeemScriptBuf = Buffer.from(redeemScript.toString("hex"), "hex");
if (addressType === "p2sh") {
payment = bitcoin.payments.p2sh({
redeem: {
output: redeemScriptBuf,
network,
},
network,
});
}
else if (addressType === "p2wsh") {
payment = bitcoin.payments.p2wsh({
redeem: {
output: redeemScriptBuf,
network,
},
});
}
}
if (!payment) {
throw new Error("payment is undefined");
}
Expand All @@ -111,9 +133,27 @@ const buildStakeTransaction = (_a) => __awaiter(void 0, [_a], void 0, function*
if (!payment.output) {
throw new Error("failed to create redeem script");
}
//Re-staking
if (!!redeemScript && (addressType === "p2wsh" || addressType === "p2sh")) {
try {
const { options, type } = (0, script_1.parseCLTVScript)({
cltvScript: redeemScript,
witness: addressType === "p2wsh",
});
if (options.lockTime > 0 &&
type >= constant_1.RedeemScriptType.PUBLIC_KEY_SCRIPT &&
type <= constant_1.RedeemScriptType.MULTI_SIG_HASH_SCRIPT) {
isRestaking = true;
preStakeOptions = options;
}
}
catch (e) {
console.log(e);
}
}
const res = yield provider.getUTXOs(account);
const rawTxMap = {};
if (addressType === "p2pkh") {
if (addressType === "p2pkh" || addressType === "p2sh") {
for (let i = 0; i < res.length; i++) {
const utxo = res[i];
if (!rawTxMap[utxo.txid]) {
Expand All @@ -122,9 +162,11 @@ const buildStakeTransaction = (_a) => __awaiter(void 0, [_a], void 0, function*
}
}
}
const utxos = res.map((utxo) => (Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, utxo), (addressType.includes("p2pkh") && {
const utxos = res.map((utxo) => (Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, utxo), ((addressType.includes("p2pkh") || addressType === "p2sh") && {
nonWitnessUtxo: Buffer.from(rawTxMap[utxo.txid], "hex"),
})), ((addressType.includes("p2wpkh") || addressType.includes("p2tr")) && {
})), ((addressType.includes("p2wpkh") ||
addressType.includes("p2tr") ||
addressType.includes("p2wsh")) && {
witnessUtxo: {
script: addressType.includes("p2sh")
? payment.redeem.output
Expand All @@ -133,46 +175,46 @@ const buildStakeTransaction = (_a) => __awaiter(void 0, [_a], void 0, function*
},
})), (addressType.includes("p2sh") && {
redeemScript: payment.redeem.output,
})), (addressType.includes("p2wsh") && {
witnessScript: payment.redeem.output,
})), (addressType.includes("p2tr") && {
isTaproot: true,
})), { sequence: 0xffffffff - 1 })));
//time lock script
let redeemScript;
let script;
//P2PKH
if (type === constant_1.RedeemScriptType.PUBLIC_KEY_HASH_SCRIPT) {
redeemScript = script_1.CLTVScript.P2PKH({
script = script_1.CLTVScript.P2PKH({
lockTime,
pubkey: publicKey,
});
}
else {
//P2PK
redeemScript = script_1.CLTVScript.P2PK({
script = script_1.CLTVScript.P2PK({
lockTime,
pubkey: publicKey,
});
}
const lockScript = (witness ? bitcoin.payments.p2wsh : bitcoin.payments.p2sh)({
redeem: {
output: redeemScript,
output: script,
},
network,
}).output;
// Address for lock script
const scriptAddress = bitcoin.address.fromOutputScript(lockScript, network);
const targets = [
//time lock output
{
Object.assign(Object.assign({}, (amount && {
value: new bignumber_js_1.default(amount).toNumber(),
script: lockScript,
},
})), { script: lockScript }),
//OP_RETURN
{
script: (0, script_1.buildOPReturnScript)({
chainId,
validatorAddress,
rewardAddress, // 20 bytes
redeemScript: redeemScript.toString("hex"),
redeemScript: script.toString("hex"),
coreFee: 0,
isMultisig: false,
lockTime,
Expand All @@ -181,14 +223,40 @@ const buildStakeTransaction = (_a) => __awaiter(void 0, [_a], void 0, function*
value: 0,
},
];
let { inputs, outputs } = (0, coinselect_segwit_1.default)(utxos, targets, bytesFee, account);
let { inputs, outputs } = amount
? (0, coinselect_segwit_1.default)(utxos, targets, bytesFee, account)
: (0, split_1.default)(utxos, targets, bytesFee);
if (!inputs) {
throw new Error("insufficient balance");
}
if (!outputs) {
throw new Error("failed to caculate transaction fee");
}
if (isRestaking && preStakeOptions) {
let signatureSize = 0;
inputs.forEach(() => {
if (type === constant_1.RedeemScriptType.MULTI_SIG_SCRIPT &&
preStakeOptions.m &&
preStakeOptions.m >= 1) {
signatureSize += (72 * preStakeOptions.m) / (witness ? 4 : 1);
}
else if (type === constant_1.RedeemScriptType.PUBLIC_KEY_HASH_SCRIPT) {
signatureSize += (72 + 66) / (witness ? 4 : 1);
}
else if (type === constant_1.RedeemScriptType.PUBLIC_KEY_SCRIPT) {
signatureSize += 72 / (witness ? 4 : 1);
}
});
const signatureSizeFee = new bignumber_js_1.default(signatureSize)
.multipliedBy(new bignumber_js_1.default(bytesFee))
.toNumber();
outputs[0].value = Math.floor(outputs[0].value - signatureSizeFee);
}
const psbt = new bitcoin.Psbt({
network,
});
inputs === null || inputs === void 0 ? void 0 : inputs.forEach((input) => psbt.addInput(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ hash: typeof input.txid === "string" ? input.txid : Buffer.from(input.txid), index: input.vout }, (input.nonWitnessUtxo
isRestaking && preStakeOptions && psbt.setLocktime(preStakeOptions === null || preStakeOptions === void 0 ? void 0 : preStakeOptions.lockTime);
inputs === null || inputs === void 0 ? void 0 : inputs.forEach((input) => psbt.addInput(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ hash: typeof input.txid === "string" ? input.txid : Buffer.from(input.txid), index: input.vout }, (input.nonWitnessUtxo
? {
nonWitnessUtxo: Buffer.from(input.nonWitnessUtxo),
}
Expand All @@ -203,7 +271,7 @@ const buildStakeTransaction = (_a) => __awaiter(void 0, [_a], void 0, function*
? { redeemScript: Buffer.from(input.redeemScript) }
: {})), (input.witnessScript
? { witnessScript: Buffer.from(input.witnessScript) }
: {})), (input.isTaproot ? { tapInternalKey: payment.internalPubkey } : {}))));
: {})), (input.isTaproot ? { tapInternalKey: payment.internalPubkey } : {})), { sequence: 0xffffffff - 1 })));
const changeAddress = account;
outputs === null || outputs === void 0 ? void 0 : outputs.forEach((output) => {
var _a;
Expand All @@ -225,12 +293,19 @@ const buildStakeTransaction = (_a) => __awaiter(void 0, [_a], void 0, function*
!psbt.validateSignaturesOfAllInputs(validatorSignature)) {
throw new Error("signature is invalid");
}
psbt.finalizeAllInputs();
if (isRestaking) {
psbt.txInputs.forEach((input, idx) => {
psbt.finalizeInput(idx, script_1.finalCLTVScripts);
});
}
else {
psbt.finalizeAllInputs();
}
const txId = yield provider.broadcast(psbt.extractTransaction().toHex());
return {
txId,
scriptAddress,
redeemScript: redeemScript.toString("hex"),
script: script.toString("hex"),
};
});
exports.buildStakeTransaction = buildStakeTransaction;
Expand Down
11 changes: 8 additions & 3 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ program
"-privkey, --privatekey <privatekey>",
"The private key used to sign the transaction, which should be associated with --account. Hex format."
)
.requiredOption(
.option(
"-amt, --amount <amount>",
"Amount of BTC to stake, measured in SAT."
"Amount of BTC to stake, measured in SAT, default to all amount of BTC"
)

.option(
Expand Down Expand Up @@ -59,7 +59,11 @@ program
)
.option(
"--fee <fee>",
"Transaction fee s)slow a)average f)fast, please choose in (s, a ,f) OR a customized number in SAT, default to a)average."
"Transaction fee in every bytes s)slow a)average f)fast, please choose in (s, a ,f) OR a customized number in SAT, default to a)average."
)
.option(
"-r, --redeemscript <redeemscript>",
"The redeem script which was returned in the stake action."
)
.action(async (args) => {
const bitcoinnetwork = BitcoinNetworkMap[args.bitcoinnetwork];
Expand All @@ -79,6 +83,7 @@ program
witness: args.witness,
bitcoinRpc: args.bitcoinrpc,
fee: fee || args.fee,
redeemScript: args.redeemscript,
});
});

Expand Down
11 changes: 8 additions & 3 deletions src/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,23 @@ import * as bitcoin from "bitcoinjs-lib";

export function getAddressType(
address: string,
network = bitcoin.networks.bitcoin
network = bitcoin.networks.bitcoin,
redeemScript?: Buffer | string
) {
if (address.startsWith(`${network.bech32}1p`)) {
bitcoin.address.fromBech32(address);
return "p2tr";
}
if (address.startsWith(network.bech32)) {
bitcoin.address.fromBech32(address);
return "p2wpkh";
const decodeBech32 = bitcoin.address.fromBech32(address);
if (decodeBech32.data.length === 20) return "p2wpkh";
if (decodeBech32.data.length === 32) return "p2wsh";
}
const base58Data = bitcoin.address.fromBase58Check(address);
if (base58Data.version === Number(network.scriptHash)) {
if (redeemScript) {
return "p2sh";
}
return "p2sh-p2wpkh";
}
if (base58Data.version === Number(network.pubKeyHash)) {
Expand Down
Loading