bitcoinjs-lib/ts_src/payments/embed.ts

59 lines
1.6 KiB
TypeScript
Raw Normal View History

import { bitcoin as BITCOIN_NETWORK } from '../networks';
2019-03-03 15:07:49 +01:00
import * as bscript from '../script';
import { typeforce as typef } from '../types';
import { Payment, PaymentOpts, Stack } from './index';
2019-03-03 15:07:49 +01:00
import * as lazy from './lazy';
2019-03-03 15:07:49 +01:00
const OPS = bscript.OPS;
function stacksEqual(a: Buffer[], b: Buffer[]): boolean {
2019-03-03 15:07:49 +01:00
if (a.length !== b.length) return false;
return a.every((x, i) => {
2019-03-03 15:07:49 +01:00
return x.equals(b[i]);
});
2018-07-11 09:27:44 +02:00
}
// output: OP_RETURN ...
2019-03-03 15:07:49 +01:00
export function p2data(a: Payment, opts?: PaymentOpts): Payment {
if (!a.data && !a.output) throw new TypeError('Not enough data');
opts = Object.assign({ validate: true }, opts || {});
typef(
{
network: typef.maybe(typef.Object),
output: typef.maybe(typef.Buffer),
data: typef.maybe(typef.arrayOf(typef.Buffer)),
},
a,
);
const network = a.network || BITCOIN_NETWORK;
2019-07-11 07:49:26 +02:00
const o = { name: 'embed', network } as Payment;
2019-03-03 15:07:49 +01:00
lazy.prop(o, 'output', () => {
2019-03-03 15:07:49 +01:00
if (!a.data) return;
return bscript.compile(([OPS.OP_RETURN] as Stack).concat(a.data));
2019-03-03 15:07:49 +01:00
});
lazy.prop(o, 'data', () => {
2019-03-03 15:07:49 +01:00
if (!a.output) return;
return bscript.decompile(a.output)!.slice(1);
});
2018-07-11 09:27:44 +02:00
// extended validation
if (opts.validate) {
if (a.output) {
2019-03-03 15:07:49 +01:00
const chunks = bscript.decompile(a.output);
if (chunks![0] !== OPS.OP_RETURN)
throw new TypeError('Output is invalid');
if (!chunks!.slice(1).every(typef.Buffer))
throw new TypeError('Output is invalid');
if (a.data && !stacksEqual(a.data, o.data as Buffer[]))
2019-03-03 15:07:49 +01:00
throw new TypeError('Data mismatch');
2018-07-11 09:27:44 +02:00
}
}
2019-03-03 15:07:49 +01:00
return Object.assign(o, a);
2018-07-11 09:27:44 +02:00
}