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

BTC 1351.utxo bin psbt subcommand #4997

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
3 changes: 2 additions & 1 deletion modules/utxo-bin/bin/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#!/usr/bin/env node
import * as yargs from 'yargs';

import { cmdParseTx, cmdParseScript, cmdBip32, cmdAddress } from '../src/commands';
import { cmdParseTx, cmdParseScript, cmdBip32, cmdPsbt, cmdAddress } from '../src/commands';

yargs
.command(cmdParseTx)
.command(cmdAddress)
.command(cmdParseScript)
.command(cmdPsbt)
.command(cmdBip32)
.strict()
.demandCommand()
Expand Down
2 changes: 2 additions & 0 deletions modules/utxo-bin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@bitgo/blockapis": "^1.10.5",
"@bitgo/statics": "^50.1.0",
"@bitgo/utxo-lib": "^11.0.0",
"@bitgo/wasm-miniscript": "^1.8.0",
"archy": "^1.0.0",
"bech32": "^2.0.0",
"bitcoinjs-lib": "npm:@bitgo-forks/[email protected]",
Expand All @@ -39,6 +40,7 @@
"chalk": "4",
"clipboardy-cjs": "^3.0.0",
"elliptic": "^6.5.2",
"io-ts": "^2.2.21",
"yargs": "^17.3.1"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions modules/utxo-bin/src/args/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './format';
export * from './parseString';
export * from './walletKeys';
export * from './parseNetwork';
Expand Down
42 changes: 42 additions & 0 deletions modules/utxo-bin/src/commands/cmdAddress/cmdGenerate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import { CommandModule } from 'yargs';
import { getNetworkOptionsDemand, keyOptions, KeyOptions } from '../../args';
import {
formatAddressTree,
formatDescriptorAddress,
formatFixedScriptAddress,
generateDescriptorAddress,
generateFixedScriptAddress,
getDescriptorAddressPlaceholderDescription,
getFixedScriptAddressPlaceholderDescription,
getRange,
parseIndexRange,
Expand Down Expand Up @@ -74,3 +77,42 @@ export const cmdGenerateFixedScript: CommandModule<unknown, ArgsGenerateAddressF
}
},
};

type ArgsGenerateDescriptorAddress = {
network: utxolib.Network;
descriptor: string;
format: string;
} & IndexLimitOptions;

export const cmdFromDescriptor: CommandModule<unknown, ArgsGenerateDescriptorAddress> = {
command: 'fromDescriptor [descriptor]',
describe: 'generate address from descriptor',
builder(b) {
return b
.options(getNetworkOptionsDemand('bitcoin'))
.positional('descriptor', {
type: 'string',
demandOption: true,
})
.options({
format: {
type: 'string',
description: `Format string.\nPlaceholders:\n${getDescriptorAddressPlaceholderDescription()}`,
default: '%i\t%a',
},
})
.options(indexLimitOptions);
},
handler(argv) {
for (const address of generateDescriptorAddress({
...argv,
index: getIndexRangeFromArgv(argv),
})) {
if (argv.format === 'tree') {
console.log(formatAddressTree(address));
} else {
console.log(formatDescriptorAddress(address, argv.format));
}
}
},
};
2 changes: 1 addition & 1 deletion modules/utxo-bin/src/commands/cmdParseTx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export const cmdParseTx = {
throw new Error(`no txdata`);
}

const bytes = stringToBuffer(string, 'hex');
const bytes = stringToBuffer(string, ['hex', 'base64']);

let tx = utxolib.bitgo.isPsbt(bytes)
? utxolib.bitgo.createPsbtFromBuffer(bytes, argv.network)
Expand Down
233 changes: 233 additions & 0 deletions modules/utxo-bin/src/commands/cmdPsbt/cmdPsbtCreate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
import * as fs from 'fs/promises';
import { Buffer } from 'buffer';

import * as t from 'io-ts';
import * as yargs from 'yargs';
import { CommandModule } from 'yargs';
import * as utxolib from '@bitgo/utxo-lib';
import * as blockapis from '@bitgo/blockapis';

import { fetchPrevOutputs, getClient } from '../../fetch';
import { getNetworkOptionsDemand, getRootWalletKeys, isWalletKeyName, keyOptions, KeyOptions } from '../../args';

type WalletUnspent = utxolib.bitgo.WalletUnspent<bigint>;
type Output = { script: Buffer; value: bigint };
type PartialWalletUnspent = Omit<WalletUnspent, 'value' | 'address'>;

export type ArgsCreateTx = KeyOptions & {
network: utxolib.Network;
unspents?: string;
unspent?: string[];
chain?: string[];
index?: string[];
output?: string[];
signer: string;
cosigner: string;
};

async function toWalletUnspents(
httpClient: blockapis.HttpClient,
unspents: PartialWalletUnspent[],
network: utxolib.Network
): Promise<WalletUnspent[]> {
const prevOutputs = await fetchPrevOutputs(
httpClient,
unspents.map((u) => utxolib.bitgo.parseOutputId(u.id)),
network

Check warning

Code scanning / CodeQL

Superfluous trailing arguments Warning

Superfluous argument passed to
function fetchPrevOutputs
.
);
return Promise.all(
unspents.map(async (u, i) => {
return {
id: u.id,
chain: u.chain,
index: u.index,
value: prevOutputs[i].value,
address: utxolib.address.fromOutputScript(prevOutputs[i].script, network),
};
})
);
}

function parseOutput(v: string, network: utxolib.Network): Output {
const parts = v.split(':');
let script: Buffer;
let value: bigint;
if (parts.length === 3) {
if (parts[0] === 'hex') {
script = Buffer.from(parts[1], 'hex');
value = BigInt(parseFloat(parts[2]));
} else {
throw new Error(`invalid output specifier ${v}`);
}
} else if (parts.length === 2) {
script = utxolib.address.toOutputScript(parts[0], network);
value = BigInt(parseFloat(parts[1]));
} else {
throw new Error(`invalid output specifier ${v}`);
}

return { script, value };
}

function createFixedScriptTxWithUnspents(
network: utxolib.Network,
rootWalletKeys: utxolib.bitgo.RootWalletKeys,
unspents: WalletUnspent[],
outputs: Output[],
{
signer,
cosigner,
}: {
signer: utxolib.bitgo.KeyName;
cosigner: utxolib.bitgo.KeyName;
}
): utxolib.Psbt {
const psbt = utxolib.bitgo.createPsbtForNetwork({ network });
for (const u of unspents) {
utxolib.bitgo.addWalletUnspentToPsbt(psbt, u, rootWalletKeys, signer, cosigner);
}
for (const output of outputs) {
psbt.addOutput(output);
}
return psbt;
}

function isStringArray(arr: unknown[]): arr is string[] {
return arr.every((x) => typeof x === 'string');
}

async function readWalletUnspents(file: string): Promise<WalletUnspent[]> {
const json = JSON.parse(await fs.readFile(file, 'utf8'));
const Unspent = t.type({
id: t.string,
address: t.string,
chain: t.number,
index: t.number,
valueString: t.string,
});
if (!t.array(Unspent).is(json)) {
throw new Error(`invalid unspents json`);
}
return json.map((u) => {
if (!utxolib.bitgo.isChainCode(u.chain)) {
throw new Error(`invalid chain code ${u.chain}`);
}
return {
id: u.id,
address: u.address,
chain: u.chain,
index: u.index,
value: BigInt(u.valueString),
};
});
}

async function toWalletUnspentsFromArgs(
client: blockapis.HttpClient,
args: {
unspent?: string[];
chain?: string[];
index?: string[];
},
network: utxolib.Network
): Promise<WalletUnspent[]> {
if (!args.unspent || !isStringArray(args.unspent)) {
throw new Error(`invalid unspent array`);
}
if (!args.chain || !isStringArray(args.chain)) {
throw new Error(`invalid chain array`);
}
if (!args.index || !isStringArray(args.index)) {
throw new Error(`invalid index array`);
}
if (args.unspent.length !== args.chain.length || args.unspent.length !== args.index.length) {
throw new Error(`unspent, chain and index arrays must have the same length`);
}
return toWalletUnspents(
client,
args.unspent.map((id, i) => {
if (!args.chain?.[i] || !args.index?.[i]) {
throw new Error('chain and index are required for each unspent');
}
const chain = parseInt(args.chain?.[i], 10);
const index = parseInt(args.index?.[i], 10);
if (isNaN(chain) || isNaN(index)) {
throw new Error('chain and index must be numbers');
}
if (!utxolib.bitgo.isChainCode(chain)) {
throw new Error('invalid chain');
}
return { id, chain, index };
}),
network
);
}

export async function createFixedScriptTx(args: ArgsCreateTx, httpClient: blockapis.HttpClient): Promise<utxolib.Psbt> {
const rootWalletKeys = getRootWalletKeys(args);

let unspents: WalletUnspent[];
if (args.unspents) {
if (args.unspent) {
throw new Error('cannot specify both unspents and unspent');
}
unspents = await readWalletUnspents(args.unspents);
} else {
unspents = await toWalletUnspentsFromArgs(httpClient, args, args.network);
}

if (!args.output || !isStringArray(args.output)) {
throw new Error(`invalid output array`);
}

const outputs = args.output.map((v) => parseOutput(v, args.network));
if (!isWalletKeyName(args.signer)) {
throw new Error('invalid signer');
}
if (!isWalletKeyName(args.cosigner)) {
throw new Error('invalid cosigner');
}

return createFixedScriptTxWithUnspents(
args.network,
rootWalletKeys,
await toWalletUnspents(httpClient, unspents, args.network),
outputs,
{
signer: args.signer,
cosigner: args.cosigner,
}
);
}

export const cmdCreateFixedScriptTx: CommandModule<
unknown,
ArgsCreateTx & {
cache: boolean;
}
> = {
command: 'createFixedScript',
describe: 'create psbt based on fixed-script unspents and outputs',
builder(b: yargs.Argv<unknown>): yargs.Argv<
ArgsCreateTx & {
cache: boolean;
}
> {
return b
.option('cache', { type: 'boolean', default: false })
.option(getNetworkOptionsDemand())
.options(keyOptions)
.option('unspents', { type: 'string', description: 'json file with unspents' })
.option('unspent', { type: 'string', array: true })
.option('chain', { type: 'string', array: true })
.option('index', { type: 'string', array: true })
.option('output', { type: 'string', array: true })
.option('signer', { type: 'string', default: 'user' })
.option('cosigner', { type: 'string', default: 'bitgo' });
},
async handler(argv) {
const httpClient = await getClient({ cache: argv.cache });
const psbt = await createFixedScriptTx(argv, httpClient);
console.log(psbt.toBase64());
},
};
41 changes: 41 additions & 0 deletions modules/utxo-bin/src/commands/cmdPsbt/cmdPsbtSign.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { CommandModule, Argv } from 'yargs';
import * as utxolib from '@bitgo/utxo-lib';

import { argToString, getNetworkOptionsDemand, readStringOptions, ReadStringOptions, stringToBuffer } from '../../args';

export type ArgsSignPsbt = ReadStringOptions & {
network: utxolib.Network;
key: string[];
};

export const cmdSignPsbt: CommandModule<unknown, ArgsSignPsbt> = {
command: 'sign [psbt]',
describe: 'sign psbt',
builder(b: Argv<unknown>): Argv<ArgsSignPsbt> {
return b
.options(readStringOptions)
.options(getNetworkOptionsDemand())
.option('key', { type: 'string', demandOption: true, array: true })
.option('finalize', { type: 'boolean', default: false })
.option('extract', { type: 'boolean', default: false });
},
async handler(argv) {
const data = await argToString(argv);
if (!data) {
throw new Error('missing psbt');
}
const buffer = stringToBuffer(data, ['hex', 'base64']);
const psbt = utxolib.Psbt.fromBuffer(buffer, { network: argv.network });
for (const k of argv.key) {
psbt.signAllInputsHD(utxolib.bip32.fromBase58(k));
}
if (argv.finalize) {
psbt.finalizeAllInputs();
}
if (argv.extract) {
console.log(psbt.extractTransaction().toHex());
} else {
console.log(psbt.toBase64());
}
},
};
15 changes: 15 additions & 0 deletions modules/utxo-bin/src/commands/cmdPsbt/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Argv, CommandModule } from 'yargs';

import { cmdSignPsbt } from './cmdPsbtSign';
import { cmdCreateFixedScriptTx } from './cmdPsbtCreate';

export const cmdPsbt: CommandModule<unknown, unknown> = {
command: 'psbt <command>',
describe: 'psbt commands',
builder(b: Argv<unknown>): Argv<unknown> {
return b.strict().command(cmdCreateFixedScriptTx).command(cmdSignPsbt);
},
handler(): void {
// do nothing
},
};
3 changes: 3 additions & 0 deletions modules/utxo-bin/src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@ export * from './cmdParseTx';
export * from './cmdAddress';
export * from './cmdParseScript';
export * from './cmdBip32';
export * from './cmdAddress';
export * from './cmdBip32';
export * from './cmdPsbt';
Loading
Loading