bitcoinjs-lib/ts_src/payments/p2pk.ts

79 lines
2.2 KiB
TypeScript
Raw Permalink Normal View History

2019-03-07 04:47:26 +01:00
import { bitcoin as BITCOIN_NETWORK } from '../networks';
2019-03-03 15:07:49 +01:00
import * as bscript from '../script';
import { isPoint, typeforce as typef } from '../types';
2019-03-07 04:47:26 +01:00
import { Payment, PaymentOpts, StackFunction } from './index';
2019-03-03 15:07:49 +01:00
import * as lazy from './lazy';
const OPS = bscript.OPS;
// input: {signature}
// output: {pubKey} OP_CHECKSIG
2019-03-03 15:07:49 +01:00
export function p2pk(a: Payment, opts?: PaymentOpts): Payment {
if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature)
throw new TypeError('Not enough data');
opts = Object.assign({ validate: true }, opts || {});
2019-03-03 15:07:49 +01:00
typef(
{
network: typef.maybe(typef.Object),
output: typef.maybe(typef.Buffer),
pubkey: typef.maybe(isPoint),
2019-03-03 15:07:49 +01:00
signature: typef.maybe(bscript.isCanonicalScriptSignature),
input: typef.maybe(typef.Buffer),
},
a,
);
2019-03-07 04:47:26 +01:00
const _chunks = lazy.value(() => {
2019-03-03 15:07:49 +01:00
return bscript.decompile(a.input!);
2019-03-07 04:47:26 +01:00
}) as StackFunction;
2019-03-03 15:07:49 +01:00
const network = a.network || BITCOIN_NETWORK;
2019-07-11 07:49:26 +02:00
const o: Payment = { name: 'p2pk', network };
2019-03-07 04:47:26 +01:00
lazy.prop(o, 'output', () => {
2019-03-03 15:07:49 +01:00
if (!a.pubkey) return;
return bscript.compile([a.pubkey, OPS.OP_CHECKSIG]);
});
2019-03-07 04:47:26 +01:00
lazy.prop(o, 'pubkey', () => {
2019-03-03 15:07:49 +01:00
if (!a.output) return;
return a.output.slice(1, -1);
});
2019-03-07 04:47:26 +01:00
lazy.prop(o, 'signature', () => {
2019-03-03 15:07:49 +01:00
if (!a.input) return;
2019-03-07 04:47:26 +01:00
return _chunks()[0] as Buffer;
2019-03-03 15:07:49 +01:00
});
2019-03-07 04:47:26 +01:00
lazy.prop(o, 'input', () => {
2019-03-03 15:07:49 +01:00
if (!a.signature) return;
return bscript.compile([a.signature]);
});
2019-03-07 04:47:26 +01:00
lazy.prop(o, 'witness', () => {
2019-03-03 15:07:49 +01:00
if (!o.input) return;
return [];
});
// extended validation
if (opts.validate) {
if (a.output) {
2019-03-03 15:07:49 +01:00
if (a.output[a.output.length - 1] !== OPS.OP_CHECKSIG)
throw new TypeError('Output is invalid');
if (!isPoint(o.pubkey)) throw new TypeError('Output pubkey is invalid');
2019-03-03 15:07:49 +01:00
if (a.pubkey && !a.pubkey.equals(o.pubkey!))
throw new TypeError('Pubkey mismatch');
}
if (a.signature) {
2019-03-03 15:07:49 +01:00
if (a.input && !a.input.equals(o.input!))
throw new TypeError('Signature mismatch');
}
if (a.input) {
2019-03-03 15:07:49 +01:00
if (_chunks().length !== 1) throw new TypeError('Input is invalid');
if (!bscript.isCanonicalScriptSignature(o.signature!))
throw new TypeError('Input has invalid signature');
}
}
2019-03-03 15:07:49 +01:00
return Object.assign(o, a);
}