-
Notifications
You must be signed in to change notification settings - Fork 272
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
OttoAllmendinger
wants to merge
2
commits into
master
Choose a base branch
from
BTC-1351.utxo-bin-psbt-subcommand
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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]", | ||
|
@@ -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": { | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
); | ||
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()); | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | ||
} | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check warning
Code scanning / CodeQL
Superfluous trailing arguments Warning