2018-12-29 14:49:35 +01:00
|
|
|
import { Payment, PaymentOpts } from './index' // eslint-disable-line
|
2018-12-28 16:00:52 +01:00
|
|
|
import * as bscript from '../script'
|
|
|
|
import * as lazy from './lazy'
|
|
|
|
import { bitcoin as BITCOIN_NETWORK } from '../networks'
|
2018-07-11 09:27:44 +02:00
|
|
|
const typef = require('typeforce')
|
2018-12-29 14:49:35 +01:00
|
|
|
const OPS = bscript.OPS
|
2018-07-11 09:27:44 +02:00
|
|
|
|
2018-12-28 16:00:52 +01:00
|
|
|
function stacksEqual (a: Array<Buffer>, b: Array<Buffer>): boolean {
|
2018-07-11 09:27:44 +02:00
|
|
|
if (a.length !== b.length) return false
|
|
|
|
|
|
|
|
return a.every(function (x, i) {
|
|
|
|
return x.equals(b[i])
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// output: OP_RETURN ...
|
2018-12-29 08:10:36 +01:00
|
|
|
export function p2data (a: Payment, opts?: PaymentOpts): Payment {
|
2018-07-11 09:27:44 +02:00
|
|
|
if (
|
|
|
|
!a.data &&
|
|
|
|
!a.output
|
|
|
|
) throw new TypeError('Not enough data')
|
2018-08-28 07:21:18 +02:00
|
|
|
opts = Object.assign({ validate: true }, opts || {})
|
2018-07-11 09:27:44 +02:00
|
|
|
|
|
|
|
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
|
2018-12-28 16:00:52 +01:00
|
|
|
const o = <Payment>{ network }
|
2018-07-11 09:27:44 +02:00
|
|
|
|
|
|
|
lazy.prop(o, 'output', function () {
|
|
|
|
if (!a.data) return
|
2018-12-29 13:39:19 +01:00
|
|
|
return bscript.compile((<Array<Buffer | number>>[OPS.OP_RETURN]).concat(a.data))
|
2018-07-11 09:27:44 +02:00
|
|
|
})
|
|
|
|
lazy.prop(o, 'data', function () {
|
|
|
|
if (!a.output) return
|
2018-12-28 17:55:07 +01:00
|
|
|
return (<Array<Buffer | number>>bscript.decompile(a.output)).slice(1)
|
2018-07-11 09:27:44 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
// extended validation
|
|
|
|
if (opts.validate) {
|
|
|
|
if (a.output) {
|
|
|
|
const chunks = bscript.decompile(a.output)
|
2018-12-28 17:55:07 +01:00
|
|
|
if ((<Array<Buffer | number>>chunks)[0] !== OPS.OP_RETURN) throw new TypeError('Output is invalid')
|
|
|
|
if (!(<Array<Buffer | number>>chunks).slice(1).every(typef.Buffer)) throw new TypeError('Output is invalid')
|
2018-07-11 09:27:44 +02:00
|
|
|
|
2018-12-28 17:55:07 +01:00
|
|
|
if (a.data && !stacksEqual(a.data, <Array<Buffer>>o.data)) throw new TypeError('Data mismatch')
|
2018-07-11 09:27:44 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return Object.assign(o, a)
|
|
|
|
}
|