2019-06-24 12:20:15 +02:00
|
|
|
import { Psbt as PsbtBase } from 'bip174';
|
2019-07-04 04:26:23 +02:00
|
|
|
import {
|
|
|
|
PartialSig,
|
|
|
|
PsbtInput,
|
2019-07-04 06:33:08 +02:00
|
|
|
TransactionInput,
|
2019-07-04 04:26:23 +02:00
|
|
|
TransactionOutput,
|
|
|
|
} from 'bip174/src/lib/interfaces';
|
2019-07-01 12:57:35 +02:00
|
|
|
import { checkForInput } from 'bip174/src/lib/utils';
|
2019-07-04 04:26:23 +02:00
|
|
|
import { toOutputScript } from './address';
|
2019-07-04 06:33:08 +02:00
|
|
|
import { reverseBuffer } from './bufferutils';
|
2019-07-02 13:17:37 +02:00
|
|
|
import { hash160 } from './crypto';
|
2019-07-03 08:34:18 +02:00
|
|
|
import { Signer, SignerAsync } from './ecpair';
|
2019-07-04 04:26:23 +02:00
|
|
|
import { bitcoin as btcNetwork, Network } from './networks';
|
2019-06-27 13:19:15 +02:00
|
|
|
import * as payments from './payments';
|
2019-07-01 11:55:18 +02:00
|
|
|
import * as bscript from './script';
|
2019-06-26 12:55:02 +02:00
|
|
|
import { Transaction } from './transaction';
|
2019-07-03 08:13:36 +02:00
|
|
|
const varuint = require('varuint-bitcoin');
|
2019-06-24 12:20:15 +02:00
|
|
|
|
2019-07-02 08:03:24 +02:00
|
|
|
export class Psbt extends PsbtBase {
|
2019-07-04 07:33:36 +02:00
|
|
|
static fromTransaction<T extends typeof PsbtBase>(
|
|
|
|
this: T,
|
|
|
|
txBuf: Buffer,
|
|
|
|
): InstanceType<T> {
|
|
|
|
const tx = Transaction.fromBuffer(txBuf);
|
2019-07-04 07:45:50 +02:00
|
|
|
checkTxEmpty(tx);
|
2019-07-04 07:33:36 +02:00
|
|
|
const psbt = new this() as Psbt;
|
|
|
|
psbt.__TX = tx;
|
|
|
|
let inputCount = tx.ins.length;
|
|
|
|
let outputCount = tx.outs.length;
|
|
|
|
while (inputCount > 0) {
|
|
|
|
psbt.inputs.push({
|
|
|
|
keyVals: [],
|
|
|
|
});
|
|
|
|
inputCount--;
|
|
|
|
}
|
|
|
|
while (outputCount > 0) {
|
|
|
|
psbt.outputs.push({
|
|
|
|
keyVals: [],
|
|
|
|
});
|
|
|
|
outputCount--;
|
|
|
|
}
|
|
|
|
return psbt as InstanceType<T>;
|
|
|
|
}
|
|
|
|
static fromBuffer<T extends typeof PsbtBase>(
|
|
|
|
this: T,
|
|
|
|
buffer: Buffer,
|
|
|
|
): InstanceType<T> {
|
|
|
|
let tx: Transaction | undefined;
|
|
|
|
const txCountGetter = (
|
|
|
|
txBuf: Buffer,
|
|
|
|
): {
|
|
|
|
inputCount: number;
|
|
|
|
outputCount: number;
|
|
|
|
} => {
|
|
|
|
tx = Transaction.fromBuffer(txBuf);
|
2019-07-04 07:45:50 +02:00
|
|
|
checkTxEmpty(tx);
|
2019-07-04 07:33:36 +02:00
|
|
|
return {
|
|
|
|
inputCount: tx.ins.length,
|
|
|
|
outputCount: tx.outs.length,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
const psbt = super.fromBuffer(buffer, txCountGetter) as Psbt;
|
|
|
|
psbt.__TX = tx!;
|
|
|
|
return psbt as InstanceType<T>;
|
|
|
|
}
|
2019-07-04 06:33:08 +02:00
|
|
|
private __TX: Transaction;
|
|
|
|
private __TX_BUF_CACHE?: Buffer;
|
2019-07-04 04:26:23 +02:00
|
|
|
private opts: PsbtOpts;
|
|
|
|
constructor(opts: PsbtOptsOptional = {}) {
|
2019-07-02 08:03:24 +02:00
|
|
|
super();
|
2019-07-04 06:33:08 +02:00
|
|
|
// set defaults
|
2019-07-04 04:26:23 +02:00
|
|
|
this.opts = Object.assign({}, DEFAULT_OPTS, opts);
|
2019-07-04 06:33:08 +02:00
|
|
|
this.__TX = Transaction.fromBuffer(this.globalMap.unsignedTx!);
|
2019-07-04 06:42:34 +02:00
|
|
|
this.setVersion(2);
|
2019-07-04 06:33:08 +02:00
|
|
|
|
|
|
|
// set cache
|
|
|
|
const self = this;
|
|
|
|
delete this.globalMap.unsignedTx;
|
|
|
|
Object.defineProperty(this.globalMap, 'unsignedTx', {
|
|
|
|
enumerable: true,
|
|
|
|
get(): Buffer {
|
|
|
|
if (self.__TX_BUF_CACHE !== undefined) {
|
|
|
|
return self.__TX_BUF_CACHE;
|
|
|
|
} else {
|
|
|
|
self.__TX_BUF_CACHE = self.__TX.toBuffer();
|
|
|
|
return self.__TX_BUF_CACHE;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
set(data: Buffer): void {
|
|
|
|
self.__TX_BUF_CACHE = data;
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
// Make data hidden when enumerating
|
|
|
|
const dpew = (
|
|
|
|
obj: any,
|
|
|
|
attr: string,
|
|
|
|
enumerable: boolean,
|
|
|
|
writable: boolean,
|
|
|
|
): any =>
|
|
|
|
Object.defineProperty(obj, attr, {
|
|
|
|
enumerable,
|
|
|
|
writable,
|
|
|
|
});
|
2019-07-04 07:33:36 +02:00
|
|
|
dpew(this, '__TX', false, true);
|
2019-07-04 06:33:08 +02:00
|
|
|
dpew(this, '__TX_BUF_CACHE', false, true);
|
|
|
|
dpew(this, 'opts', false, true);
|
2019-07-02 08:03:24 +02:00
|
|
|
}
|
|
|
|
|
2019-07-04 06:42:34 +02:00
|
|
|
setVersion(version: number): this {
|
|
|
|
this.__TX.version = version;
|
|
|
|
this.__TX_BUF_CACHE = undefined;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
setLocktime(locktime: number): this {
|
|
|
|
this.__TX.locktime = locktime;
|
|
|
|
this.__TX_BUF_CACHE = undefined;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
2019-07-04 06:33:08 +02:00
|
|
|
addInput(inputData: TransactionInput): this {
|
|
|
|
const self = this;
|
|
|
|
const inputAdder = (
|
|
|
|
_inputData: TransactionInput,
|
|
|
|
txBuf: Buffer,
|
|
|
|
): Buffer => {
|
|
|
|
if (
|
|
|
|
!txBuf ||
|
|
|
|
(_inputData as any).hash === undefined ||
|
|
|
|
(_inputData as any).index === undefined ||
|
|
|
|
(!Buffer.isBuffer((_inputData as any).hash) &&
|
|
|
|
typeof (_inputData as any).hash !== 'string') ||
|
|
|
|
typeof (_inputData as any).index !== 'number'
|
|
|
|
) {
|
|
|
|
throw new Error('Error adding input.');
|
|
|
|
}
|
|
|
|
const prevHash = Buffer.isBuffer(_inputData.hash)
|
|
|
|
? _inputData.hash
|
|
|
|
: reverseBuffer(Buffer.from(_inputData.hash, 'hex'));
|
|
|
|
self.__TX.ins.push({
|
|
|
|
hash: prevHash,
|
|
|
|
index: _inputData.index,
|
|
|
|
script: Buffer.alloc(0),
|
|
|
|
sequence: _inputData.sequence || Transaction.DEFAULT_SEQUENCE,
|
|
|
|
witness: [],
|
|
|
|
});
|
|
|
|
console.log(self.__TX);
|
|
|
|
return self.__TX.toBuffer();
|
|
|
|
};
|
|
|
|
return super.addInput(inputData, inputAdder);
|
|
|
|
}
|
|
|
|
|
|
|
|
addOutput(outputData: TransactionOutput): this {
|
2019-07-04 04:26:23 +02:00
|
|
|
const { address } = outputData as any;
|
|
|
|
if (typeof address === 'string') {
|
|
|
|
const { network } = this.opts;
|
|
|
|
const script = toOutputScript(address, network);
|
|
|
|
outputData = Object.assign(outputData, { script });
|
|
|
|
}
|
2019-07-04 06:33:08 +02:00
|
|
|
const self = this;
|
|
|
|
const outputAdder = (
|
|
|
|
_outputData: TransactionOutput,
|
|
|
|
txBuf: Buffer,
|
|
|
|
): Buffer => {
|
|
|
|
if (
|
|
|
|
!txBuf ||
|
|
|
|
(_outputData as any).script === undefined ||
|
|
|
|
(_outputData as any).value === undefined ||
|
|
|
|
!Buffer.isBuffer((_outputData as any).script) ||
|
|
|
|
typeof (_outputData as any).value !== 'number'
|
|
|
|
) {
|
|
|
|
throw new Error('Error adding output.');
|
|
|
|
}
|
|
|
|
self.__TX.outs.push({
|
|
|
|
script: (_outputData as any).script!,
|
|
|
|
value: _outputData.value,
|
|
|
|
});
|
|
|
|
console.log(self.__TX);
|
|
|
|
return self.__TX.toBuffer();
|
|
|
|
};
|
|
|
|
return super.addOutput(outputData, true, outputAdder);
|
2019-07-04 04:26:23 +02:00
|
|
|
}
|
|
|
|
|
2019-07-03 08:13:36 +02:00
|
|
|
extractTransaction(): Transaction {
|
|
|
|
if (!this.inputs.every(isFinalized)) throw new Error('Not finalized');
|
2019-07-04 07:33:36 +02:00
|
|
|
const tx = this.__TX.clone();
|
2019-07-03 08:13:36 +02:00
|
|
|
this.inputs.forEach((input, idx) => {
|
|
|
|
if (input.finalScriptSig) tx.ins[idx].script = input.finalScriptSig;
|
|
|
|
if (input.finalScriptWitness) {
|
2019-07-03 11:42:31 +02:00
|
|
|
tx.ins[idx].witness = scriptWitnessToWitnessStack(
|
|
|
|
input.finalScriptWitness,
|
|
|
|
);
|
2019-07-03 08:13:36 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
return tx;
|
|
|
|
}
|
|
|
|
|
|
|
|
finalizeAllInputs(): {
|
|
|
|
result: boolean;
|
|
|
|
inputResults: boolean[];
|
|
|
|
} {
|
|
|
|
const inputResults = range(this.inputs.length).map(idx =>
|
|
|
|
this.finalizeInput(idx),
|
|
|
|
);
|
|
|
|
const result = inputResults.every(val => val === true);
|
|
|
|
return {
|
|
|
|
result,
|
|
|
|
inputResults,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
finalizeInput(inputIndex: number): boolean {
|
2019-07-02 08:03:24 +02:00
|
|
|
const input = checkForInput(this.inputs, inputIndex);
|
2019-07-03 08:13:36 +02:00
|
|
|
const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput(
|
2019-07-02 08:03:24 +02:00
|
|
|
inputIndex,
|
|
|
|
input,
|
2019-07-04 07:33:36 +02:00
|
|
|
this.__TX,
|
2019-07-02 08:03:24 +02:00
|
|
|
);
|
|
|
|
if (!script) return false;
|
2019-07-03 08:13:36 +02:00
|
|
|
|
2019-07-02 08:03:24 +02:00
|
|
|
const scriptType = classifyScript(script);
|
2019-07-03 08:13:36 +02:00
|
|
|
if (!canFinalize(input, script, scriptType)) return false;
|
2019-07-02 08:18:00 +02:00
|
|
|
|
2019-07-03 08:34:18 +02:00
|
|
|
const { finalScriptSig, finalScriptWitness } = getFinalScripts(
|
2019-07-03 08:13:36 +02:00
|
|
|
script,
|
|
|
|
scriptType,
|
|
|
|
input.partialSig!,
|
2019-07-03 08:34:18 +02:00
|
|
|
isSegwit,
|
|
|
|
isP2SH,
|
|
|
|
isP2WSH,
|
2019-07-03 08:13:36 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
if (finalScriptSig)
|
|
|
|
this.addFinalScriptSigToInput(inputIndex, finalScriptSig);
|
|
|
|
if (finalScriptWitness)
|
|
|
|
this.addFinalScriptWitnessToInput(inputIndex, finalScriptWitness);
|
|
|
|
if (!finalScriptSig && !finalScriptWitness) return false;
|
|
|
|
|
|
|
|
this.clearFinalizedInput(inputIndex);
|
|
|
|
return true;
|
2019-07-02 08:03:24 +02:00
|
|
|
}
|
|
|
|
|
2019-07-04 07:33:36 +02:00
|
|
|
signInput(inputIndex: number, keyPair: Signer): this {
|
2019-07-03 08:13:36 +02:00
|
|
|
if (!keyPair || !keyPair.publicKey)
|
|
|
|
throw new Error('Need Signer to sign input');
|
2019-07-03 08:34:18 +02:00
|
|
|
const { hash, sighashType } = getHashAndSighashType(
|
|
|
|
this.inputs,
|
2019-07-02 13:17:37 +02:00
|
|
|
inputIndex,
|
2019-07-03 08:34:18 +02:00
|
|
|
keyPair.publicKey,
|
2019-07-04 07:33:36 +02:00
|
|
|
this.__TX,
|
2019-07-02 13:17:37 +02:00
|
|
|
);
|
2019-07-02 08:03:24 +02:00
|
|
|
|
|
|
|
const partialSig = {
|
2019-07-03 08:34:18 +02:00
|
|
|
pubkey: keyPair.publicKey,
|
2019-07-02 08:03:24 +02:00
|
|
|
signature: bscript.signature.encode(keyPair.sign(hash), sighashType),
|
|
|
|
};
|
|
|
|
|
|
|
|
return this.addPartialSigToInput(inputIndex, partialSig);
|
|
|
|
}
|
2019-07-03 08:34:18 +02:00
|
|
|
|
2019-07-03 08:48:56 +02:00
|
|
|
signInputAsync(inputIndex: number, keyPair: SignerAsync): Promise<void> {
|
2019-07-04 06:52:48 +02:00
|
|
|
return new Promise(
|
|
|
|
(resolve, reject): void => {
|
|
|
|
if (!keyPair || !keyPair.publicKey)
|
|
|
|
return reject(new Error('Need Signer to sign input'));
|
|
|
|
const { hash, sighashType } = getHashAndSighashType(
|
|
|
|
this.inputs,
|
|
|
|
inputIndex,
|
|
|
|
keyPair.publicKey,
|
2019-07-04 07:33:36 +02:00
|
|
|
this.__TX,
|
2019-07-04 06:52:48 +02:00
|
|
|
);
|
2019-07-03 08:34:18 +02:00
|
|
|
|
2019-07-04 06:52:48 +02:00
|
|
|
Promise.resolve(keyPair.sign(hash)).then(signature => {
|
|
|
|
const partialSig = {
|
|
|
|
pubkey: keyPair.publicKey,
|
|
|
|
signature: bscript.signature.encode(signature, sighashType),
|
|
|
|
};
|
2019-07-03 08:34:18 +02:00
|
|
|
|
2019-07-04 06:52:48 +02:00
|
|
|
this.addPartialSigToInput(inputIndex, partialSig);
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
},
|
|
|
|
);
|
2019-07-03 08:34:18 +02:00
|
|
|
}
|
2019-07-02 08:03:24 +02:00
|
|
|
}
|
|
|
|
|
2019-07-03 08:13:36 +02:00
|
|
|
//
|
|
|
|
//
|
|
|
|
//
|
|
|
|
//
|
|
|
|
// Helper functions
|
|
|
|
//
|
|
|
|
//
|
|
|
|
//
|
|
|
|
//
|
|
|
|
|
2019-07-04 04:26:23 +02:00
|
|
|
interface PsbtOptsOptional {
|
|
|
|
network?: Network;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface PsbtOpts {
|
|
|
|
network: Network;
|
|
|
|
}
|
|
|
|
|
|
|
|
const DEFAULT_OPTS = {
|
|
|
|
network: btcNetwork,
|
|
|
|
};
|
|
|
|
|
2019-07-03 08:13:36 +02:00
|
|
|
function isFinalized(input: PsbtInput): boolean {
|
|
|
|
return !!input.finalScriptSig || !!input.finalScriptWitness;
|
|
|
|
}
|
|
|
|
|
2019-07-03 08:34:18 +02:00
|
|
|
function getHashAndSighashType(
|
|
|
|
inputs: PsbtInput[],
|
|
|
|
inputIndex: number,
|
|
|
|
pubkey: Buffer,
|
2019-07-04 07:33:36 +02:00
|
|
|
unsignedTx: Transaction,
|
2019-07-03 08:34:18 +02:00
|
|
|
): {
|
|
|
|
hash: Buffer;
|
|
|
|
sighashType: number;
|
|
|
|
} {
|
|
|
|
const input = checkForInput(inputs, inputIndex);
|
2019-07-04 07:33:36 +02:00
|
|
|
const { hash, sighashType, script } = getHashForSig(
|
|
|
|
inputIndex,
|
|
|
|
input,
|
|
|
|
unsignedTx,
|
|
|
|
);
|
2019-07-03 08:34:18 +02:00
|
|
|
checkScriptForPubkey(pubkey, script);
|
|
|
|
return {
|
|
|
|
hash,
|
|
|
|
sighashType,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function getFinalScripts(
|
|
|
|
script: Buffer,
|
|
|
|
scriptType: string,
|
|
|
|
partialSig: PartialSig[],
|
|
|
|
isSegwit: boolean,
|
|
|
|
isP2SH: boolean,
|
|
|
|
isP2WSH: boolean,
|
|
|
|
): {
|
|
|
|
finalScriptSig: Buffer | undefined;
|
|
|
|
finalScriptWitness: Buffer | undefined;
|
|
|
|
} {
|
|
|
|
let finalScriptSig: Buffer | undefined;
|
|
|
|
let finalScriptWitness: Buffer | undefined;
|
|
|
|
|
|
|
|
// Wow, the payments API is very handy
|
|
|
|
const payment: payments.Payment = getPayment(script, scriptType, partialSig);
|
|
|
|
const p2wsh = !isP2WSH ? null : payments.p2wsh({ redeem: payment });
|
|
|
|
const p2sh = !isP2SH ? null : payments.p2sh({ redeem: p2wsh || payment });
|
|
|
|
|
|
|
|
if (isSegwit) {
|
|
|
|
if (p2wsh) {
|
|
|
|
finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness!);
|
|
|
|
} else {
|
|
|
|
finalScriptWitness = witnessStackToScriptWitness(payment.witness!);
|
|
|
|
}
|
|
|
|
if (p2sh) {
|
2019-07-03 11:42:31 +02:00
|
|
|
finalScriptSig = p2sh.input;
|
2019-07-03 08:34:18 +02:00
|
|
|
}
|
|
|
|
} else {
|
2019-07-03 11:42:31 +02:00
|
|
|
if (p2sh) {
|
|
|
|
finalScriptSig = p2sh.input;
|
|
|
|
} else {
|
|
|
|
finalScriptSig = payment.input;
|
|
|
|
}
|
2019-07-03 08:34:18 +02:00
|
|
|
}
|
|
|
|
return {
|
|
|
|
finalScriptSig,
|
|
|
|
finalScriptWitness,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-07-03 11:42:31 +02:00
|
|
|
function getSortedSigs(script: Buffer, partialSig: PartialSig[]): Buffer[] {
|
|
|
|
const p2ms = payments.p2ms({ output: script });
|
|
|
|
// for each pubkey in order of p2ms script
|
|
|
|
return p2ms
|
|
|
|
.pubkeys!.map(pk => {
|
|
|
|
// filter partialSig array by pubkey being equal
|
|
|
|
return (
|
|
|
|
partialSig.filter(ps => {
|
|
|
|
return ps.pubkey.equals(pk);
|
|
|
|
})[0] || {}
|
|
|
|
).signature;
|
|
|
|
// Any pubkey without a match will return undefined
|
|
|
|
// this last filter removes all the undefined items in the array.
|
|
|
|
})
|
|
|
|
.filter(v => !!v);
|
|
|
|
}
|
|
|
|
|
2019-07-03 08:13:36 +02:00
|
|
|
function getPayment(
|
|
|
|
script: Buffer,
|
|
|
|
scriptType: string,
|
|
|
|
partialSig: PartialSig[],
|
|
|
|
): payments.Payment {
|
|
|
|
let payment: payments.Payment;
|
|
|
|
switch (scriptType) {
|
|
|
|
case 'multisig':
|
2019-07-03 11:42:31 +02:00
|
|
|
const sigs = getSortedSigs(script, partialSig);
|
2019-07-03 08:13:36 +02:00
|
|
|
payment = payments.p2ms({
|
|
|
|
output: script,
|
2019-07-03 11:42:31 +02:00
|
|
|
signatures: sigs,
|
2019-07-03 08:13:36 +02:00
|
|
|
});
|
|
|
|
break;
|
|
|
|
case 'pubkey':
|
|
|
|
payment = payments.p2pk({
|
|
|
|
output: script,
|
|
|
|
signature: partialSig[0].signature,
|
|
|
|
});
|
|
|
|
break;
|
|
|
|
case 'pubkeyhash':
|
|
|
|
payment = payments.p2pkh({
|
|
|
|
output: script,
|
|
|
|
pubkey: partialSig[0].pubkey,
|
|
|
|
signature: partialSig[0].signature,
|
|
|
|
});
|
|
|
|
break;
|
|
|
|
case 'witnesspubkeyhash':
|
|
|
|
payment = payments.p2wpkh({
|
|
|
|
output: script,
|
|
|
|
pubkey: partialSig[0].pubkey,
|
|
|
|
signature: partialSig[0].signature,
|
|
|
|
});
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
return payment!;
|
|
|
|
}
|
|
|
|
|
|
|
|
function canFinalize(
|
|
|
|
input: PsbtInput,
|
|
|
|
script: Buffer,
|
|
|
|
scriptType: string,
|
|
|
|
): boolean {
|
|
|
|
switch (scriptType) {
|
|
|
|
case 'pubkey':
|
|
|
|
case 'pubkeyhash':
|
|
|
|
case 'witnesspubkeyhash':
|
|
|
|
return hasSigs(1, input.partialSig);
|
|
|
|
case 'multisig':
|
|
|
|
const p2ms = payments.p2ms({ output: script });
|
|
|
|
return hasSigs(p2ms.m!, input.partialSig);
|
|
|
|
default:
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function checkScriptForPubkey(pubkey: Buffer, script: Buffer): void {
|
|
|
|
const pubkeyHash = hash160(pubkey);
|
|
|
|
|
|
|
|
const decompiled = bscript.decompile(script);
|
|
|
|
if (decompiled === null) throw new Error('Unknown script error');
|
|
|
|
|
|
|
|
const hasKey = decompiled.some(element => {
|
|
|
|
if (typeof element === 'number') return false;
|
|
|
|
return element.equals(pubkey) || element.equals(pubkeyHash);
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!hasKey) {
|
|
|
|
throw new Error(
|
|
|
|
`Can not sign for this input with the key ${pubkey.toString('hex')}`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-02 08:03:24 +02:00
|
|
|
interface HashForSigData {
|
|
|
|
script: Buffer;
|
|
|
|
hash: Buffer;
|
|
|
|
sighashType: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
const getHashForSig = (
|
|
|
|
inputIndex: number,
|
|
|
|
input: PsbtInput,
|
2019-07-04 07:33:36 +02:00
|
|
|
unsignedTx: Transaction,
|
2019-07-02 08:03:24 +02:00
|
|
|
): HashForSigData => {
|
|
|
|
const sighashType = input.sighashType || Transaction.SIGHASH_ALL;
|
|
|
|
let hash: Buffer;
|
|
|
|
let script: Buffer;
|
|
|
|
|
|
|
|
if (input.nonWitnessUtxo) {
|
|
|
|
const nonWitnessUtxoTx = Transaction.fromBuffer(input.nonWitnessUtxo);
|
|
|
|
|
|
|
|
const prevoutHash = unsignedTx.ins[inputIndex].hash;
|
|
|
|
const utxoHash = nonWitnessUtxoTx.getHash();
|
|
|
|
|
|
|
|
// If a non-witness UTXO is provided, its hash must match the hash specified in the prevout
|
|
|
|
if (!prevoutHash.equals(utxoHash)) {
|
|
|
|
throw new Error(
|
|
|
|
`Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const prevoutIndex = unsignedTx.ins[inputIndex].index;
|
|
|
|
const prevout = nonWitnessUtxoTx.outs[prevoutIndex];
|
|
|
|
|
|
|
|
if (input.redeemScript) {
|
|
|
|
// If a redeemScript is provided, the scriptPubKey must be for that redeemScript
|
|
|
|
checkRedeemScript(inputIndex, prevout.script, input.redeemScript);
|
|
|
|
script = input.redeemScript;
|
|
|
|
hash = unsignedTx.hashForSignature(
|
|
|
|
inputIndex,
|
|
|
|
input.redeemScript,
|
|
|
|
sighashType,
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
script = prevout.script;
|
|
|
|
hash = unsignedTx.hashForSignature(
|
|
|
|
inputIndex,
|
|
|
|
prevout.script,
|
|
|
|
sighashType,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
} else if (input.witnessUtxo) {
|
|
|
|
let _script: Buffer; // so we don't shadow the `let script` above
|
|
|
|
if (input.redeemScript) {
|
|
|
|
// If a redeemScript is provided, the scriptPubKey must be for that redeemScript
|
|
|
|
checkRedeemScript(
|
|
|
|
inputIndex,
|
|
|
|
input.witnessUtxo.script,
|
|
|
|
input.redeemScript,
|
|
|
|
);
|
|
|
|
_script = input.redeemScript;
|
|
|
|
} else {
|
|
|
|
_script = input.witnessUtxo.script;
|
|
|
|
}
|
|
|
|
if (isP2WPKH(_script)) {
|
|
|
|
// P2WPKH uses the P2PKH template for prevoutScript when signing
|
|
|
|
const signingScript = payments.p2pkh({ hash: _script.slice(2) }).output!;
|
|
|
|
hash = unsignedTx.hashForWitnessV0(
|
|
|
|
inputIndex,
|
|
|
|
signingScript,
|
|
|
|
input.witnessUtxo.value,
|
|
|
|
sighashType,
|
|
|
|
);
|
|
|
|
script = _script;
|
|
|
|
} else {
|
|
|
|
if (!input.witnessScript)
|
|
|
|
throw new Error('Segwit input needs witnessScript if not P2WPKH');
|
|
|
|
checkWitnessScript(inputIndex, _script, input.witnessScript);
|
|
|
|
hash = unsignedTx.hashForWitnessV0(
|
|
|
|
inputIndex,
|
2019-07-03 11:42:31 +02:00
|
|
|
input.witnessScript,
|
2019-07-02 08:03:24 +02:00
|
|
|
input.witnessUtxo.value,
|
|
|
|
sighashType,
|
|
|
|
);
|
|
|
|
// want to make sure the script we return is the actual meaningful script
|
|
|
|
script = input.witnessScript;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
throw new Error('Need a Utxo input item for signing');
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
script,
|
|
|
|
sighashType,
|
|
|
|
hash,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2019-07-01 11:55:18 +02:00
|
|
|
type ScriptCheckerFunction = (idx: number, spk: Buffer, rs: Buffer) => void;
|
|
|
|
|
|
|
|
const scriptCheckerFactory = (
|
|
|
|
payment: any,
|
|
|
|
paymentScriptName: string,
|
|
|
|
): ScriptCheckerFunction => (
|
2019-06-28 13:21:32 +02:00
|
|
|
inputIndex: number,
|
|
|
|
scriptPubKey: Buffer,
|
|
|
|
redeemScript: Buffer,
|
|
|
|
): void => {
|
2019-07-01 11:55:18 +02:00
|
|
|
const redeemScriptOutput = payment({
|
2019-06-28 13:21:32 +02:00
|
|
|
redeem: { output: redeemScript },
|
|
|
|
}).output as Buffer;
|
|
|
|
|
2019-06-28 13:26:42 +02:00
|
|
|
if (!scriptPubKey.equals(redeemScriptOutput)) {
|
2019-06-28 13:21:32 +02:00
|
|
|
throw new Error(
|
2019-07-01 11:55:18 +02:00
|
|
|
`${paymentScriptName} for input #${inputIndex} doesn't match the scriptPubKey in the prevout`,
|
2019-06-28 13:21:32 +02:00
|
|
|
);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-07-01 11:55:18 +02:00
|
|
|
const checkRedeemScript = scriptCheckerFactory(payments.p2sh, 'Redeem script');
|
|
|
|
const checkWitnessScript = scriptCheckerFactory(
|
|
|
|
payments.p2wsh,
|
|
|
|
'Witness script',
|
|
|
|
);
|
|
|
|
|
2019-07-02 08:03:24 +02:00
|
|
|
type isPaymentFunction = (script: Buffer) => boolean;
|
|
|
|
|
|
|
|
const isPaymentFactory = (payment: any): isPaymentFunction => (
|
|
|
|
script: Buffer,
|
|
|
|
): boolean => {
|
2019-07-01 11:55:18 +02:00
|
|
|
try {
|
2019-07-01 12:57:35 +02:00
|
|
|
payment({ output: script });
|
2019-07-01 11:55:18 +02:00
|
|
|
return true;
|
|
|
|
} catch (err) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
};
|
2019-07-02 08:03:24 +02:00
|
|
|
const isP2WPKH = isPaymentFactory(payments.p2wpkh);
|
|
|
|
const isP2PKH = isPaymentFactory(payments.p2pkh);
|
|
|
|
const isP2MS = isPaymentFactory(payments.p2ms);
|
|
|
|
const isP2PK = isPaymentFactory(payments.p2pk);
|
|
|
|
|
|
|
|
const classifyScript = (script: Buffer): string => {
|
|
|
|
if (isP2WPKH(script)) return 'witnesspubkeyhash';
|
|
|
|
if (isP2PKH(script)) return 'pubkeyhash';
|
|
|
|
if (isP2MS(script)) return 'multisig';
|
|
|
|
if (isP2PK(script)) return 'pubkey';
|
|
|
|
return 'nonstandard';
|
|
|
|
};
|
2019-07-01 11:55:18 +02:00
|
|
|
|
2019-07-03 08:13:36 +02:00
|
|
|
interface GetScriptReturn {
|
|
|
|
script: Buffer | null;
|
|
|
|
isSegwit: boolean;
|
|
|
|
isP2SH: boolean;
|
|
|
|
isP2WSH: boolean;
|
|
|
|
}
|
2019-07-01 12:57:35 +02:00
|
|
|
function getScriptFromInput(
|
|
|
|
inputIndex: number,
|
|
|
|
input: PsbtInput,
|
2019-07-04 07:33:36 +02:00
|
|
|
unsignedTx: Transaction,
|
2019-07-03 08:13:36 +02:00
|
|
|
): GetScriptReturn {
|
|
|
|
const res: GetScriptReturn = {
|
|
|
|
script: null,
|
|
|
|
isSegwit: false,
|
|
|
|
isP2SH: false,
|
|
|
|
isP2WSH: false,
|
|
|
|
};
|
2019-07-01 12:57:35 +02:00
|
|
|
if (input.nonWitnessUtxo) {
|
|
|
|
if (input.redeemScript) {
|
2019-07-03 08:13:36 +02:00
|
|
|
res.isP2SH = true;
|
|
|
|
res.script = input.redeemScript;
|
2019-07-01 12:57:35 +02:00
|
|
|
} else {
|
|
|
|
const nonWitnessUtxoTx = Transaction.fromBuffer(input.nonWitnessUtxo);
|
|
|
|
const prevoutIndex = unsignedTx.ins[inputIndex].index;
|
2019-07-03 08:13:36 +02:00
|
|
|
res.script = nonWitnessUtxoTx.outs[prevoutIndex].script;
|
2019-07-01 12:57:35 +02:00
|
|
|
}
|
|
|
|
} else if (input.witnessUtxo) {
|
2019-07-03 08:13:36 +02:00
|
|
|
res.isSegwit = true;
|
|
|
|
res.isP2SH = !!input.redeemScript;
|
|
|
|
res.isP2WSH = !!input.witnessScript;
|
2019-07-01 12:57:35 +02:00
|
|
|
if (input.witnessScript) {
|
2019-07-03 08:13:36 +02:00
|
|
|
res.script = input.witnessScript;
|
2019-07-01 12:57:35 +02:00
|
|
|
} else if (input.redeemScript) {
|
2019-07-03 11:42:31 +02:00
|
|
|
res.script = payments.p2wpkh({
|
2019-07-03 08:13:36 +02:00
|
|
|
hash: input.redeemScript.slice(2),
|
|
|
|
}).output!;
|
2019-07-01 12:57:35 +02:00
|
|
|
} else {
|
2019-07-03 11:42:31 +02:00
|
|
|
res.script = payments.p2wpkh({
|
2019-07-03 08:13:36 +02:00
|
|
|
hash: input.witnessUtxo.script.slice(2),
|
|
|
|
}).output!;
|
2019-07-01 12:57:35 +02:00
|
|
|
}
|
|
|
|
}
|
2019-07-03 08:13:36 +02:00
|
|
|
return res;
|
2019-07-01 12:57:35 +02:00
|
|
|
}
|
2019-07-03 08:13:36 +02:00
|
|
|
|
|
|
|
const hasSigs = (neededSigs: number, partialSig?: any[]): boolean => {
|
|
|
|
if (!partialSig) return false;
|
|
|
|
if (partialSig.length > neededSigs) throw new Error('Too many signatures');
|
|
|
|
return partialSig.length === neededSigs;
|
|
|
|
};
|
|
|
|
|
|
|
|
function witnessStackToScriptWitness(witness: Buffer[]): Buffer {
|
|
|
|
let buffer = Buffer.allocUnsafe(0);
|
|
|
|
|
|
|
|
function writeSlice(slice: Buffer): void {
|
|
|
|
buffer = Buffer.concat([buffer, Buffer.from(slice)]);
|
|
|
|
}
|
|
|
|
|
|
|
|
function writeVarInt(i: number): void {
|
|
|
|
const currentLen = buffer.length;
|
|
|
|
const varintLen = varuint.encodingLength(i);
|
|
|
|
|
|
|
|
buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]);
|
|
|
|
varuint.encode(i, buffer, currentLen);
|
|
|
|
}
|
|
|
|
|
|
|
|
function writeVarSlice(slice: Buffer): void {
|
|
|
|
writeVarInt(slice.length);
|
|
|
|
writeSlice(slice);
|
|
|
|
}
|
|
|
|
|
|
|
|
function writeVector(vector: Buffer[]): void {
|
|
|
|
writeVarInt(vector.length);
|
|
|
|
vector.forEach(writeVarSlice);
|
|
|
|
}
|
|
|
|
|
|
|
|
writeVector(witness);
|
|
|
|
|
|
|
|
return buffer;
|
|
|
|
}
|
|
|
|
|
2019-07-03 11:42:31 +02:00
|
|
|
function scriptWitnessToWitnessStack(buffer: Buffer): Buffer[] {
|
|
|
|
let offset = 0;
|
|
|
|
|
|
|
|
function readSlice(n: number): Buffer {
|
|
|
|
offset += n;
|
|
|
|
return buffer.slice(offset - n, offset);
|
|
|
|
}
|
|
|
|
|
|
|
|
function readVarInt(): number {
|
|
|
|
const vi = varuint.decode(buffer, offset);
|
|
|
|
offset += varuint.decode.bytes;
|
|
|
|
return vi;
|
|
|
|
}
|
|
|
|
|
|
|
|
function readVarSlice(): Buffer {
|
|
|
|
return readSlice(readVarInt());
|
|
|
|
}
|
|
|
|
|
|
|
|
function readVector(): Buffer[] {
|
|
|
|
const count = readVarInt();
|
|
|
|
const vector: Buffer[] = [];
|
|
|
|
for (let i = 0; i < count; i++) vector.push(readVarSlice());
|
|
|
|
return vector;
|
|
|
|
}
|
|
|
|
|
|
|
|
return readVector();
|
|
|
|
}
|
|
|
|
|
2019-07-03 08:13:36 +02:00
|
|
|
const range = (n: number): number[] => [...Array(n).keys()];
|
2019-07-04 07:45:50 +02:00
|
|
|
|
|
|
|
function checkTxEmpty(tx: Transaction): void {
|
|
|
|
const isEmpty = tx.ins.every(
|
|
|
|
input =>
|
|
|
|
input.script &&
|
|
|
|
input.script.length === 0 &&
|
|
|
|
input.witness &&
|
|
|
|
input.witness.length === 0,
|
|
|
|
);
|
|
|
|
if (!isEmpty) {
|
|
|
|
throw new Error('Format Error: Transaction ScriptSigs are not empty');
|
|
|
|
}
|
|
|
|
}
|