Browse Source

Refactor

- Clean up sign
- Get the meaningful script
- Search for pubkey and prevent sign if can't find self
- Tests failed, so comment out for now
psbt
junderw 6 years ago
parent
commit
f28e9cef71
No known key found for this signature in database GPG Key ID: B256185D3A971908
  1. 209
      src/psbt.js
  2. 252
      ts_src/psbt.ts

209
src/psbt.js

@ -2,64 +2,9 @@
Object.defineProperty(exports, '__esModule', { value: true });
const bip174_1 = require('bip174');
const utils_1 = require('bip174/src/lib/utils');
const classify = require('./classify');
const payments = require('./payments');
const bscript = require('./script');
const transaction_1 = require('./transaction');
const scriptCheckerFactory = (payment, paymentScriptName) => (
inputIndex,
scriptPubKey,
redeemScript,
) => {
const redeemScriptOutput = payment({
redeem: { output: redeemScript },
}).output;
if (!scriptPubKey.equals(redeemScriptOutput)) {
throw new Error(
`${paymentScriptName} for input #${inputIndex} doesn't match the scriptPubKey in the prevout`,
);
}
};
const checkRedeemScript = scriptCheckerFactory(payments.p2sh, 'Redeem script');
const checkWitnessScript = scriptCheckerFactory(
payments.p2wsh,
'Witness script',
);
const isPayment = (script, payment) => {
try {
payment({ output: script });
return true;
} catch (err) {
return false;
}
};
function getScriptFromInput(inputIndex, input, _unsignedTx) {
let script;
if (input.nonWitnessUtxo) {
if (input.redeemScript) {
script = input.redeemScript;
} else {
const unsignedTx = transaction_1.Transaction.fromBuffer(_unsignedTx);
const nonWitnessUtxoTx = transaction_1.Transaction.fromBuffer(
input.nonWitnessUtxo,
);
const prevoutIndex = unsignedTx.ins[inputIndex].index;
script = nonWitnessUtxoTx.outs[prevoutIndex].script;
}
} else if (input.witnessUtxo) {
if (input.witnessScript) {
script = input.witnessScript;
} else if (input.redeemScript) {
script = payments.p2pkh({ hash: input.redeemScript.slice(2) }).output;
} else {
script = payments.p2pkh({ hash: input.witnessUtxo.script.slice(2) })
.output;
}
} else {
return;
}
return script;
}
class Psbt extends bip174_1.Psbt {
constructor(network) {
super();
@ -73,7 +18,8 @@ class Psbt extends bip174_1.Psbt {
this.globalMap.unsignedTx,
);
if (!script) return false;
const scriptType = classify.output(script);
const scriptType = classifyScript(script);
// TODO: for each type
switch (scriptType) {
case 'pubkey':
return false;
@ -88,36 +34,45 @@ class Psbt extends bip174_1.Psbt {
}
}
signInput(inputIndex, keyPair) {
// TODO: Implement BIP174 pre-sign checks:
// https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#signer
//
// if non_witness_utxo.exists:
// assert(sha256d(non_witness_utxo) == psbt.tx.innput[i].prevout.hash)
// if redeemScript.exists:
// assert(non_witness_utxo.vout[psbt.tx.input[i].prevout.n].scriptPubKey == P2SH(redeemScript))
// sign_non_witness(redeemScript)
// else:
// sign_non_witness(non_witness_utxo.vout[psbt.tx.input[i].prevout.n].scriptPubKey)
// else if witness_utxo.exists:
// if redeemScript.exists:
// assert(witness_utxo.scriptPubKey == P2SH(redeemScript))
// script = redeemScript
// else:
// script = witness_utxo.scriptPubKey
// if IsP2WPKH(script):
// sign_witness(P2PKH(script[2:22]))
// else if IsP2WSH(script):
// assert(script == P2WSH(witnessScript))
// sign_witness(witnessScript)
// else:
// assert False
const input = this.inputs[inputIndex];
if (input === undefined) throw new Error(`No input #${inputIndex}`);
const unsignedTx = transaction_1.Transaction.fromBuffer(
const { hash, sighashType } = getHashForSig(
inputIndex,
input,
this.globalMap.unsignedTx,
);
const sighashType = input.sighashType || 0x01;
const pubkey = keyPair.publicKey;
// // TODO: throw error when the pubkey or pubkey hash is not found anywhere
// // in the script
// const pubkeyHash = hash160(keyPair.publicKey);
//
// 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')}`,
// );
// }
const partialSig = {
pubkey,
signature: bscript.signature.encode(keyPair.sign(hash), sighashType),
};
return this.addPartialSigToInput(inputIndex, partialSig);
}
}
exports.Psbt = Psbt;
const getHashForSig = (inputIndex, input, txBuf) => {
const unsignedTx = transaction_1.Transaction.fromBuffer(txBuf);
const sighashType =
input.sighashType || transaction_1.Transaction.SIGHASH_ALL;
let hash;
let script;
if (input.nonWitnessUtxo) {
const nonWitnessUtxoTx = transaction_1.Transaction.fromBuffer(
input.nonWitnessUtxo,
@ -135,12 +90,14 @@ class Psbt extends bip174_1.Psbt {
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,
@ -148,7 +105,7 @@ class Psbt extends bip174_1.Psbt {
);
}
} else if (input.witnessUtxo) {
let script;
let _script; // 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(
@ -156,38 +113,104 @@ class Psbt extends bip174_1.Psbt {
input.witnessUtxo.script,
input.redeemScript,
);
script = input.redeemScript;
_script = input.redeemScript;
} else {
script = input.witnessUtxo.script;
_script = input.witnessUtxo.script;
}
if (isPayment(script, payments.p2wpkh)) {
if (isP2WPKH(_script)) {
// P2WPKH uses the P2PKH template for prevoutScript when signing
const signingScript = payments.p2pkh({ hash: script.slice(2) }).output;
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);
checkWitnessScript(inputIndex, _script, input.witnessScript);
hash = unsignedTx.hashForWitnessV0(
inputIndex,
script,
_script,
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');
}
const partialSig = {
pubkey: keyPair.publicKey,
signature: bscript.signature.encode(keyPair.sign(hash), sighashType),
return {
script,
sighashType,
hash,
};
return this.addPartialSigToInput(inputIndex, partialSig);
};
const scriptCheckerFactory = (payment, paymentScriptName) => (
inputIndex,
scriptPubKey,
redeemScript,
) => {
const redeemScriptOutput = payment({
redeem: { output: redeemScript },
}).output;
if (!scriptPubKey.equals(redeemScriptOutput)) {
throw new Error(
`${paymentScriptName} for input #${inputIndex} doesn't match the scriptPubKey in the prevout`,
);
}
};
const checkRedeemScript = scriptCheckerFactory(payments.p2sh, 'Redeem script');
const checkWitnessScript = scriptCheckerFactory(
payments.p2wsh,
'Witness script',
);
const isPaymentFactory = payment => script => {
try {
payment({ output: script });
return true;
} catch (err) {
return false;
}
};
const isP2WPKH = isPaymentFactory(payments.p2wpkh);
const isP2PKH = isPaymentFactory(payments.p2pkh);
const isP2MS = isPaymentFactory(payments.p2ms);
const isP2PK = isPaymentFactory(payments.p2pk);
const classifyScript = script => {
if (isP2WPKH(script)) return 'witnesspubkeyhash';
if (isP2PKH(script)) return 'pubkeyhash';
if (isP2MS(script)) return 'multisig';
if (isP2PK(script)) return 'pubkey';
return 'nonstandard';
};
function getScriptFromInput(inputIndex, input, _unsignedTx) {
let script;
if (input.nonWitnessUtxo) {
if (input.redeemScript) {
script = input.redeemScript;
} else {
const unsignedTx = transaction_1.Transaction.fromBuffer(_unsignedTx);
const nonWitnessUtxoTx = transaction_1.Transaction.fromBuffer(
input.nonWitnessUtxo,
);
const prevoutIndex = unsignedTx.ins[inputIndex].index;
script = nonWitnessUtxoTx.outs[prevoutIndex].script;
}
} else if (input.witnessUtxo) {
if (input.witnessScript) {
script = input.witnessScript;
} else if (input.redeemScript) {
script = payments.p2pkh({ hash: input.redeemScript.slice(2) }).output;
} else {
script = payments.p2pkh({ hash: input.witnessUtxo.script.slice(2) })
.output;
}
} else {
return;
}
return script;
}
exports.Psbt = Psbt;

252
ts_src/psbt.ts

@ -1,79 +1,13 @@
import { Psbt as PsbtBase } from 'bip174';
import { PsbtInput } from 'bip174/src/lib/interfaces';
import { checkForInput } from 'bip174/src/lib/utils';
import * as classify from './classify';
// import { hash160 } from './crypto'; // TODO: used in pubkey check
import { Signer } from './ecpair';
import { Network } from './networks';
import * as payments from './payments';
import * as bscript from './script';
import { Transaction } from './transaction';
type ScriptCheckerFunction = (idx: number, spk: Buffer, rs: Buffer) => void;
const scriptCheckerFactory = (
payment: any,
paymentScriptName: string,
): ScriptCheckerFunction => (
inputIndex: number,
scriptPubKey: Buffer,
redeemScript: Buffer,
): void => {
const redeemScriptOutput = payment({
redeem: { output: redeemScript },
}).output as Buffer;
if (!scriptPubKey.equals(redeemScriptOutput)) {
throw new Error(
`${paymentScriptName} for input #${inputIndex} doesn't match the scriptPubKey in the prevout`,
);
}
};
const checkRedeemScript = scriptCheckerFactory(payments.p2sh, 'Redeem script');
const checkWitnessScript = scriptCheckerFactory(
payments.p2wsh,
'Witness script',
);
const isPayment = (script: Buffer, payment: any): boolean => {
try {
payment({ output: script });
return true;
} catch (err) {
return false;
}
};
function getScriptFromInput(
inputIndex: number,
input: PsbtInput,
_unsignedTx: Buffer,
): Buffer | undefined {
let script: Buffer;
if (input.nonWitnessUtxo) {
if (input.redeemScript) {
script = input.redeemScript;
} else {
const unsignedTx = Transaction.fromBuffer(_unsignedTx);
const nonWitnessUtxoTx = Transaction.fromBuffer(input.nonWitnessUtxo);
const prevoutIndex = unsignedTx.ins[inputIndex].index;
script = nonWitnessUtxoTx.outs[prevoutIndex].script;
}
} else if (input.witnessUtxo) {
if (input.witnessScript) {
script = input.witnessScript;
} else if (input.redeemScript) {
script = payments.p2pkh({ hash: input.redeemScript.slice(2) }).output!;
} else {
script = payments.p2pkh({ hash: input.witnessUtxo.script.slice(2) })
.output!;
}
} else {
return;
}
return script;
}
export class Psbt extends PsbtBase {
constructor(public network?: Network) {
super();
@ -87,7 +21,8 @@ export class Psbt extends PsbtBase {
this.globalMap.unsignedTx!,
);
if (!script) return false;
const scriptType = classify.output(script);
const scriptType = classifyScript(script);
// TODO: for each type
switch (scriptType) {
case 'pubkey':
return false;
@ -103,36 +38,57 @@ export class Psbt extends PsbtBase {
}
signInput(inputIndex: number, keyPair: Signer): Psbt {
// TODO: Implement BIP174 pre-sign checks:
// https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#signer
//
// if non_witness_utxo.exists:
// assert(sha256d(non_witness_utxo) == psbt.tx.innput[i].prevout.hash)
// if redeemScript.exists:
// assert(non_witness_utxo.vout[psbt.tx.input[i].prevout.n].scriptPubKey == P2SH(redeemScript))
// sign_non_witness(redeemScript)
// else:
// sign_non_witness(non_witness_utxo.vout[psbt.tx.input[i].prevout.n].scriptPubKey)
// else if witness_utxo.exists:
// if redeemScript.exists:
// assert(witness_utxo.scriptPubKey == P2SH(redeemScript))
// script = redeemScript
// else:
// script = witness_utxo.scriptPubKey
// if IsP2WPKH(script):
// sign_witness(P2PKH(script[2:22]))
// else if IsP2WSH(script):
// assert(script == P2WSH(witnessScript))
// sign_witness(witnessScript)
// else:
// assert False
const input = this.inputs[inputIndex];
if (input === undefined) throw new Error(`No input #${inputIndex}`);
const {
hash,
sighashType,
// script, // TODO: use for pubkey check below
} = getHashForSig(inputIndex, input, this.globalMap.unsignedTx!);
const pubkey = keyPair.publicKey;
// // TODO: throw error when the pubkey or pubkey hash is not found anywhere
// // in the script
// const pubkeyHash = hash160(keyPair.publicKey);
//
// 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')}`,
// );
// }
const partialSig = {
pubkey,
signature: bscript.signature.encode(keyPair.sign(hash), sighashType),
};
const unsignedTx = Transaction.fromBuffer(this.globalMap.unsignedTx!);
const sighashType = input.sighashType || 0x01;
return this.addPartialSigToInput(inputIndex, partialSig);
}
}
interface HashForSigData {
script: Buffer;
hash: Buffer;
sighashType: number;
}
const getHashForSig = (
inputIndex: number,
input: PsbtInput,
txBuf: Buffer,
): HashForSigData => {
const unsignedTx = Transaction.fromBuffer(txBuf);
const sighashType = input.sighashType || Transaction.SIGHASH_ALL;
let hash: Buffer;
let script: Buffer;
if (input.nonWitnessUtxo) {
const nonWitnessUtxoTx = Transaction.fromBuffer(input.nonWitnessUtxo);
@ -153,12 +109,14 @@ export class Psbt extends PsbtBase {
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,
@ -166,7 +124,7 @@ export class Psbt extends PsbtBase {
);
}
} else if (input.witnessUtxo) {
let script: Buffer;
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(
@ -174,39 +132,121 @@ export class Psbt extends PsbtBase {
input.witnessUtxo.script,
input.redeemScript,
);
script = input.redeemScript;
_script = input.redeemScript;
} else {
script = input.witnessUtxo.script;
_script = input.witnessUtxo.script;
}
if (isPayment(script, payments.p2wpkh)) {
if (isP2WPKH(_script)) {
// P2WPKH uses the P2PKH template for prevoutScript when signing
const signingScript = payments.p2pkh({ hash: script.slice(2) }).output!;
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);
checkWitnessScript(inputIndex, _script, input.witnessScript);
hash = unsignedTx.hashForWitnessV0(
inputIndex,
script,
_script,
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');
}
const partialSig = {
pubkey: keyPair.publicKey,
signature: bscript.signature.encode(keyPair.sign(hash), sighashType),
return {
script,
sighashType,
hash,
};
};
return this.addPartialSigToInput(inputIndex, partialSig);
type ScriptCheckerFunction = (idx: number, spk: Buffer, rs: Buffer) => void;
const scriptCheckerFactory = (
payment: any,
paymentScriptName: string,
): ScriptCheckerFunction => (
inputIndex: number,
scriptPubKey: Buffer,
redeemScript: Buffer,
): void => {
const redeemScriptOutput = payment({
redeem: { output: redeemScript },
}).output as Buffer;
if (!scriptPubKey.equals(redeemScriptOutput)) {
throw new Error(
`${paymentScriptName} for input #${inputIndex} doesn't match the scriptPubKey in the prevout`,
);
}
};
const checkRedeemScript = scriptCheckerFactory(payments.p2sh, 'Redeem script');
const checkWitnessScript = scriptCheckerFactory(
payments.p2wsh,
'Witness script',
);
type isPaymentFunction = (script: Buffer) => boolean;
const isPaymentFactory = (payment: any): isPaymentFunction => (
script: Buffer,
): boolean => {
try {
payment({ output: script });
return true;
} catch (err) {
return false;
}
};
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';
};
function getScriptFromInput(
inputIndex: number,
input: PsbtInput,
_unsignedTx: Buffer,
): Buffer | undefined {
let script: Buffer;
if (input.nonWitnessUtxo) {
if (input.redeemScript) {
script = input.redeemScript;
} else {
const unsignedTx = Transaction.fromBuffer(_unsignedTx);
const nonWitnessUtxoTx = Transaction.fromBuffer(input.nonWitnessUtxo);
const prevoutIndex = unsignedTx.ins[inputIndex].index;
script = nonWitnessUtxoTx.outs[prevoutIndex].script;
}
} else if (input.witnessUtxo) {
if (input.witnessScript) {
script = input.witnessScript;
} else if (input.redeemScript) {
script = payments.p2pkh({ hash: input.redeemScript.slice(2) }).output!;
} else {
script = payments.p2pkh({ hash: input.witnessUtxo.script.slice(2) })
.output!;
}
} else {
return;
}
return script;
}

Loading…
Cancel
Save