Browse Source

Move Transaction to ES6

v4
junderw 6 years ago
parent
commit
17c89fdc5e
No known key found for this signature in database GPG Key ID: B256185D3A971908
  1. 773
      src/transaction.js

773
src/transaction.js

@ -7,35 +7,20 @@ const typeforce = require('typeforce')
const types = require('./types') const types = require('./types')
const varuint = require('varuint-bitcoin') const varuint = require('varuint-bitcoin')
function varSliceSize (someScript) { const varSliceSize = (someScript) => {
const length = someScript.length const length = someScript.length
return varuint.encodingLength(length) + length return varuint.encodingLength(length) + length
} }
function vectorSize (someVector) { const vectorSize = (someVector) => {
const length = someVector.length const length = someVector.length
return varuint.encodingLength(length) + someVector.reduce(function (sum, witness) { return varuint.encodingLength(length) + someVector.reduce((sum, witness) => {
return sum + varSliceSize(witness) return sum + varSliceSize(witness)
}, 0) }, 0)
} }
function Transaction () {
this.version = 1
this.locktime = 0
this.ins = []
this.outs = []
}
Transaction.DEFAULT_SEQUENCE = 0xffffffff
Transaction.SIGHASH_ALL = 0x01
Transaction.SIGHASH_NONE = 0x02
Transaction.SIGHASH_SINGLE = 0x03
Transaction.SIGHASH_ANYONECANPAY = 0x80
Transaction.ADVANCED_TRANSACTION_MARKER = 0x00
Transaction.ADVANCED_TRANSACTION_FLAG = 0x01
const EMPTY_SCRIPT = Buffer.allocUnsafe(0) const EMPTY_SCRIPT = Buffer.allocUnsafe(0)
const EMPTY_WITNESS = [] const EMPTY_WITNESS = []
const ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex') const ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex')
@ -46,447 +31,525 @@ const BLANK_OUTPUT = {
valueBuffer: VALUE_UINT64_MAX valueBuffer: VALUE_UINT64_MAX
} }
Transaction.fromBuffer = function (buffer, __noStrict) { class Transaction {
let offset = 0 constructor () {
function readSlice (n) { this.version = 1
offset += n this.locktime = 0
return buffer.slice(offset - n, offset) this.ins = []
this.outs = []
} }
function readUInt32 () { static get DEFAULT_SEQUENCE () {
const i = buffer.readUInt32LE(offset) return 0xffffffff
offset += 4
return i
} }
static get SIGHASH_ALL () {
function readInt32 () { return 0x01
const i = buffer.readInt32LE(offset)
offset += 4
return i
} }
static get SIGHASH_NONE () {
function readUInt64 () { return 0x02
const i = bufferutils.readUInt64LE(buffer, offset)
offset += 8
return i
} }
static get SIGHASH_SINGLE () {
function readVarInt () { return 0x03
const vi = varuint.decode(buffer, offset)
offset += varuint.decode.bytes
return vi
} }
static get SIGHASH_ANYONECANPAY () {
function readVarSlice () { return 0x80
return readSlice(readVarInt()) }
static get ADVANCED_TRANSACTION_MARKER () {
return 0x00
}
static get ADVANCED_TRANSACTION_FLAG () {
return 0x01
} }
function readVector () { isCoinbase () {
const count = readVarInt() return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash)
const vector = []
for (var i = 0; i < count; i++) vector.push(readVarSlice())
return vector
} }
const tx = new Transaction() addInput (hash, index, sequence, scriptSig) {
tx.version = readInt32() typeforce(types.tuple(
types.Hash256bit,
types.UInt32,
types.maybe(types.UInt32),
types.maybe(types.Buffer)
), arguments)
const marker = buffer.readUInt8(offset) if (types.Null(sequence)) {
const flag = buffer.readUInt8(offset + 1) sequence = Transaction.DEFAULT_SEQUENCE
}
let hasWitnesses = false // Add the input and return the input's index
if (marker === Transaction.ADVANCED_TRANSACTION_MARKER && return (this.ins.push({
flag === Transaction.ADVANCED_TRANSACTION_FLAG) { hash: hash,
offset += 2 index: index,
hasWitnesses = true script: scriptSig || EMPTY_SCRIPT,
sequence: sequence,
witness: EMPTY_WITNESS
}) - 1)
} }
const vinLen = readVarInt() addOutput (scriptPubKey, value) {
for (var i = 0; i < vinLen; ++i) { typeforce(types.tuple(types.Buffer, types.Satoshi), arguments)
tx.ins.push({
hash: readSlice(32), // Add the output and return the output's index
index: readUInt32(), return (this.outs.push({
script: readVarSlice(), script: scriptPubKey,
sequence: readUInt32(), value: value
witness: EMPTY_WITNESS }) - 1)
})
} }
const voutLen = readVarInt() hasWitnesses () {
for (i = 0; i < voutLen; ++i) { return this.ins.some((x) => {
tx.outs.push({ return x.witness.length !== 0
value: readUInt64(),
script: readVarSlice()
}) })
} }
if (hasWitnesses) { weight () {
for (i = 0; i < vinLen; ++i) { const base = this.__byteLength(false)
tx.ins[i].witness = readVector() const total = this.__byteLength(true)
} return base * 3 + total
}
// was this pointless? virtualSize () {
if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data') return Math.ceil(this.weight() / 4)
} }
tx.locktime = readUInt32() byteLength () {
return this.__byteLength(true)
}
if (__noStrict) return tx __byteLength (__allowWitness) {
if (offset !== buffer.length) throw new Error('Transaction has unexpected data') const hasWitnesses = __allowWitness && this.hasWitnesses()
return (
(hasWitnesses ? 10 : 8) +
varuint.encodingLength(this.ins.length) +
varuint.encodingLength(this.outs.length) +
this.ins.reduce((sum, input) => {
return sum + 40 + varSliceSize(input.script)
}, 0) +
this.outs.reduce((sum, output) => {
return sum + 8 + varSliceSize(output.script)
}, 0) +
(hasWitnesses ? this.ins.reduce((sum, input) => {
return sum + vectorSize(input.witness)
}, 0) : 0)
)
}
return tx clone () {
} const newTx = new Transaction()
newTx.version = this.version
newTx.locktime = this.locktime
newTx.ins = this.ins.map((txIn) => {
return {
hash: txIn.hash,
index: txIn.index,
script: txIn.script,
sequence: txIn.sequence,
witness: txIn.witness
}
})
Transaction.fromHex = function (hex) { newTx.outs = this.outs.map((txOut) => {
return Transaction.fromBuffer(Buffer.from(hex, 'hex')) return {
} script: txOut.script,
value: txOut.value
}
})
Transaction.isCoinbaseHash = function (buffer) { return newTx
typeforce(types.Hash256bit, buffer)
for (var i = 0; i < 32; ++i) {
if (buffer[i] !== 0) return false
} }
return true
}
Transaction.prototype.isCoinbase = function () { /**
return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) * Hash transaction for signing a specific input.
} *
* Bitcoin uses a different hash for each signed transaction input.
* This method copies the transaction, makes the necessary changes based on the
* hashType, and then hashes the result.
* This hash can then be used to sign the provided transaction input.
*/
hashForSignature (inIndex, prevOutScript, hashType) {
typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments)
// https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
if (inIndex >= this.ins.length) return ONE
// ignore OP_CODESEPARATOR
const ourScript = bscript.compile(bscript.decompile(prevOutScript).filter((x) => {
return x !== opcodes.OP_CODESEPARATOR
}))
const txTmp = this.clone()
// SIGHASH_NONE: ignore all outputs? (wildcard payee)
if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) {
txTmp.outs = []
// ignore sequence numbers (except at inIndex)
txTmp.ins.forEach((input, i) => {
if (i === inIndex) return
input.sequence = 0
})
// SIGHASH_SINGLE: ignore all outputs, except at the same index?
} else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) {
// https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
if (inIndex >= this.outs.length) return ONE
// truncate outputs after
txTmp.outs.length = inIndex + 1
// "blank" outputs before
for (var i = 0; i < inIndex; i++) {
txTmp.outs[i] = BLANK_OUTPUT
}
// ignore sequence numbers (except at inIndex)
txTmp.ins.forEach((input, y) => {
if (y === inIndex) return
input.sequence = 0
})
}
Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) { // SIGHASH_ANYONECANPAY: ignore inputs entirely?
typeforce(types.tuple( if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
types.Hash256bit, txTmp.ins = [txTmp.ins[inIndex]]
types.UInt32, txTmp.ins[0].script = ourScript
types.maybe(types.UInt32),
types.maybe(types.Buffer) // SIGHASH_ALL: only ignore input scripts
), arguments) } else {
// "blank" others input scripts
if (types.Null(sequence)) { txTmp.ins.forEach((input) => {
sequence = Transaction.DEFAULT_SEQUENCE input.script = EMPTY_SCRIPT
} })
txTmp.ins[inIndex].script = ourScript
// Add the input and return the input's index }
return (this.ins.push({
hash: hash,
index: index,
script: scriptSig || EMPTY_SCRIPT,
sequence: sequence,
witness: EMPTY_WITNESS
}) - 1)
}
Transaction.prototype.addOutput = function (scriptPubKey, value) { // serialize and hash
typeforce(types.tuple(types.Buffer, types.Satoshi), arguments) const buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4)
buffer.writeInt32LE(hashType, buffer.length - 4)
txTmp.__toBuffer(buffer, 0, false)
// Add the output and return the output's index return bcrypto.hash256(buffer)
return (this.outs.push({ }
script: scriptPubKey,
value: value
}) - 1)
}
Transaction.prototype.hasWitnesses = function () { hashForWitnessV0 (inIndex, prevOutScript, value, hashType) {
return this.ins.some(function (x) { typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments)
return x.witness.length !== 0
})
}
Transaction.prototype.weight = function () { let tbuffer, toffset
const base = this.__byteLength(false)
const total = this.__byteLength(true)
return base * 3 + total
}
Transaction.prototype.virtualSize = function () { const writeSlice = (slice) => {
return Math.ceil(this.weight() / 4) toffset += slice.copy(tbuffer, toffset)
} }
Transaction.prototype.byteLength = function () { const writeUInt32 = (i) => {
return this.__byteLength(true) toffset = tbuffer.writeUInt32LE(i, toffset)
} }
Transaction.prototype.__byteLength = function (__allowWitness) { const writeUInt64 = (i) => {
const hasWitnesses = __allowWitness && this.hasWitnesses() toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset)
}
return (
(hasWitnesses ? 10 : 8) +
varuint.encodingLength(this.ins.length) +
varuint.encodingLength(this.outs.length) +
this.ins.reduce(function (sum, input) { return sum + 40 + varSliceSize(input.script) }, 0) +
this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) +
(hasWitnesses ? this.ins.reduce(function (sum, input) { return sum + vectorSize(input.witness) }, 0) : 0)
)
}
Transaction.prototype.clone = function () { const writeVarInt = (i) => {
const newTx = new Transaction() varuint.encode(i, tbuffer, toffset)
newTx.version = this.version toffset += varuint.encode.bytes
newTx.locktime = this.locktime
newTx.ins = this.ins.map(function (txIn) {
return {
hash: txIn.hash,
index: txIn.index,
script: txIn.script,
sequence: txIn.sequence,
witness: txIn.witness
} }
})
newTx.outs = this.outs.map(function (txOut) { const writeVarSlice = (slice) => {
return { writeVarInt(slice.length)
script: txOut.script, writeSlice(slice)
value: txOut.value
} }
})
return newTx let hashOutputs = ZERO
} let hashPrevouts = ZERO
let hashSequence = ZERO
/** if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) {
* Hash transaction for signing a specific input. tbuffer = Buffer.allocUnsafe(36 * this.ins.length)
* toffset = 0
* Bitcoin uses a different hash for each signed transaction input.
* This method copies the transaction, makes the necessary changes based on the
* hashType, and then hashes the result.
* This hash can then be used to sign the provided transaction input.
*/
Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) {
typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments)
// https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 this.ins.forEach((txIn) => {
if (inIndex >= this.ins.length) return ONE writeSlice(txIn.hash)
writeUInt32(txIn.index)
})
// ignore OP_CODESEPARATOR hashPrevouts = bcrypto.hash256(tbuffer)
const ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) { }
return x !== opcodes.OP_CODESEPARATOR
}))
const txTmp = this.clone() if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) &&
(hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
(hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
tbuffer = Buffer.allocUnsafe(4 * this.ins.length)
toffset = 0
// SIGHASH_NONE: ignore all outputs? (wildcard payee) this.ins.forEach((txIn) => {
if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { writeUInt32(txIn.sequence)
txTmp.outs = [] })
// ignore sequence numbers (except at inIndex) hashSequence = bcrypto.hash256(tbuffer)
txTmp.ins.forEach(function (input, i) { }
if (i === inIndex) return
input.sequence = 0 if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
}) (hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
const txOutsSize = this.outs.reduce((sum, output) => {
return sum + 8 + varSliceSize(output.script)
}, 0)
tbuffer = Buffer.allocUnsafe(txOutsSize)
toffset = 0
// SIGHASH_SINGLE: ignore all outputs, except at the same index? this.outs.forEach((out) => {
} else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { writeUInt64(out.value)
// https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 writeVarSlice(out.script)
if (inIndex >= this.outs.length) return ONE })
// truncate outputs after hashOutputs = bcrypto.hash256(tbuffer)
txTmp.outs.length = inIndex + 1 } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) {
const output = this.outs[inIndex]
// "blank" outputs before tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script))
for (var i = 0; i < inIndex; i++) { toffset = 0
txTmp.outs[i] = BLANK_OUTPUT writeUInt64(output.value)
writeVarSlice(output.script)
hashOutputs = bcrypto.hash256(tbuffer)
} }
// ignore sequence numbers (except at inIndex) tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript))
txTmp.ins.forEach(function (input, y) { toffset = 0
if (y === inIndex) return
input.sequence = 0 const input = this.ins[inIndex]
}) writeUInt32(this.version)
writeSlice(hashPrevouts)
writeSlice(hashSequence)
writeSlice(input.hash)
writeUInt32(input.index)
writeVarSlice(prevOutScript)
writeUInt64(value)
writeUInt32(input.sequence)
writeSlice(hashOutputs)
writeUInt32(this.locktime)
writeUInt32(hashType)
return bcrypto.hash256(tbuffer)
} }
// SIGHASH_ANYONECANPAY: ignore inputs entirely? getHash () {
if (hashType & Transaction.SIGHASH_ANYONECANPAY) { return bcrypto.hash256(this.__toBuffer(undefined, undefined, false))
txTmp.ins = [txTmp.ins[inIndex]] }
txTmp.ins[0].script = ourScript
// SIGHASH_ALL: only ignore input scripts getId () {
} else { // transaction hash's are displayed in reverse order
// "blank" others input scripts return this.getHash().reverse().toString('hex')
txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT })
txTmp.ins[inIndex].script = ourScript
} }
// serialize and hash toBuffer (buffer, initialOffset) {
const buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4) return this.__toBuffer(buffer, initialOffset, true)
buffer.writeInt32LE(hashType, buffer.length - 4) }
txTmp.__toBuffer(buffer, 0, false)
return bcrypto.hash256(buffer) __toBuffer (buffer, initialOffset, __allowWitness) {
} if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness))
Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value, hashType) { let offset = initialOffset || 0
typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments)
let tbuffer, toffset const writeSlice = (slice) => {
function writeSlice (slice) { toffset += slice.copy(tbuffer, toffset) } offset += slice.copy(buffer, offset)
function writeUInt32 (i) { toffset = tbuffer.writeUInt32LE(i, toffset) } }
function writeUInt64 (i) { toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset) }
function writeVarInt (i) {
varuint.encode(i, tbuffer, toffset)
toffset += varuint.encode.bytes
}
function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
let hashOutputs = ZERO const writeUInt8 = (i) => {
let hashPrevouts = ZERO offset = buffer.writeUInt8(i, offset)
let hashSequence = ZERO }
if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { const writeUInt32 = (i) => {
tbuffer = Buffer.allocUnsafe(36 * this.ins.length) offset = buffer.writeUInt32LE(i, offset)
toffset = 0 }
const writeInt32 = (i) => {
offset = buffer.writeInt32LE(i, offset)
}
const writeUInt64 = (i) => {
offset = bufferutils.writeUInt64LE(buffer, i, offset)
}
const writeVarInt = (i) => {
varuint.encode(i, buffer, offset)
offset += varuint.encode.bytes
}
const writeVarSlice = (slice) => {
writeVarInt(slice.length)
writeSlice(slice)
}
const writeVector = (vector) => {
writeVarInt(vector.length)
vector.forEach(writeVarSlice)
}
writeInt32(this.version)
const hasWitnesses = __allowWitness && this.hasWitnesses()
this.ins.forEach(function (txIn) { if (hasWitnesses) {
writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER)
writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG)
}
writeVarInt(this.ins.length)
this.ins.forEach((txIn) => {
writeSlice(txIn.hash) writeSlice(txIn.hash)
writeUInt32(txIn.index) writeUInt32(txIn.index)
writeVarSlice(txIn.script)
writeUInt32(txIn.sequence)
}) })
hashPrevouts = bcrypto.hash256(tbuffer) writeVarInt(this.outs.length)
} this.outs.forEach((txOut) => {
if (!txOut.valueBuffer) {
if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) && writeUInt64(txOut.value)
(hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && } else {
(hashType & 0x1f) !== Transaction.SIGHASH_NONE) { writeSlice(txOut.valueBuffer)
tbuffer = Buffer.allocUnsafe(4 * this.ins.length) }
toffset = 0
this.ins.forEach(function (txIn) { writeVarSlice(txOut.script)
writeUInt32(txIn.sequence)
}) })
hashSequence = bcrypto.hash256(tbuffer) if (hasWitnesses) {
this.ins.forEach((input) => {
writeVector(input.witness)
})
}
writeUInt32(this.locktime)
// avoid slicing unless necessary
if (initialOffset !== undefined) return buffer.slice(initialOffset, offset)
return buffer
} }
if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && toHex () {
(hashType & 0x1f) !== Transaction.SIGHASH_NONE) { return this.toBuffer().toString('hex')
const txOutsSize = this.outs.reduce(function (sum, output) { }
return sum + 8 + varSliceSize(output.script)
}, 0)
tbuffer = Buffer.allocUnsafe(txOutsSize) setInputScript (index, scriptSig) {
toffset = 0 typeforce(types.tuple(types.Number, types.Buffer), arguments)
this.outs.forEach(function (out) { this.ins[index].script = scriptSig
writeUInt64(out.value) }
writeVarSlice(out.script)
})
hashOutputs = bcrypto.hash256(tbuffer) setWitness (index, witness) {
} else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) { typeforce(types.tuple(types.Number, [types.Buffer]), arguments)
const output = this.outs[inIndex]
tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script)) this.ins[index].witness = witness
toffset = 0 }
writeUInt64(output.value)
writeVarSlice(output.script)
hashOutputs = bcrypto.hash256(tbuffer)
}
tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript))
toffset = 0
const input = this.ins[inIndex]
writeUInt32(this.version)
writeSlice(hashPrevouts)
writeSlice(hashSequence)
writeSlice(input.hash)
writeUInt32(input.index)
writeVarSlice(prevOutScript)
writeUInt64(value)
writeUInt32(input.sequence)
writeSlice(hashOutputs)
writeUInt32(this.locktime)
writeUInt32(hashType)
return bcrypto.hash256(tbuffer)
} }
Transaction.prototype.getHash = function () { Transaction.fromBuffer = (buffer, __noStrict) => {
return bcrypto.hash256(this.__toBuffer(undefined, undefined, false)) let offset = 0
}
Transaction.prototype.getId = function () { const readSlice = (n) => {
// transaction hash's are displayed in reverse order offset += n
return this.getHash().reverse().toString('hex') return buffer.slice(offset - n, offset)
} }
Transaction.prototype.toBuffer = function (buffer, initialOffset) { const readUInt32 = () => {
return this.__toBuffer(buffer, initialOffset, true) const i = buffer.readUInt32LE(offset)
} offset += 4
return i
}
Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitness) { const readInt32 = () => {
if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness)) const i = buffer.readInt32LE(offset)
offset += 4
return i
}
let offset = initialOffset || 0 const readUInt64 = () => {
function writeSlice (slice) { offset += slice.copy(buffer, offset) } const i = bufferutils.readUInt64LE(buffer, offset)
function writeUInt8 (i) { offset = buffer.writeUInt8(i, offset) } offset += 8
function writeUInt32 (i) { offset = buffer.writeUInt32LE(i, offset) } return i
function writeInt32 (i) { offset = buffer.writeInt32LE(i, offset) }
function writeUInt64 (i) { offset = bufferutils.writeUInt64LE(buffer, i, offset) }
function writeVarInt (i) {
varuint.encode(i, buffer, offset)
offset += varuint.encode.bytes
} }
function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
function writeVector (vector) { writeVarInt(vector.length); vector.forEach(writeVarSlice) }
writeInt32(this.version) const readVarInt = () => {
const vi = varuint.decode(buffer, offset)
offset += varuint.decode.bytes
return vi
}
const hasWitnesses = __allowWitness && this.hasWitnesses() const readVarSlice = () => {
return readSlice(readVarInt())
}
if (hasWitnesses) { const readVector = () => {
writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER) const count = readVarInt()
writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG) const vector = []
for (var i = 0; i < count; i++) vector.push(readVarSlice())
return vector
} }
writeVarInt(this.ins.length) const tx = new Transaction()
tx.version = readInt32()
this.ins.forEach(function (txIn) { const marker = buffer.readUInt8(offset)
writeSlice(txIn.hash) const flag = buffer.readUInt8(offset + 1)
writeUInt32(txIn.index)
writeVarSlice(txIn.script)
writeUInt32(txIn.sequence)
})
writeVarInt(this.outs.length) let hasWitnesses = false
this.outs.forEach(function (txOut) { if (marker === Transaction.ADVANCED_TRANSACTION_MARKER &&
if (!txOut.valueBuffer) { flag === Transaction.ADVANCED_TRANSACTION_FLAG) {
writeUInt64(txOut.value) offset += 2
} else { hasWitnesses = true
writeSlice(txOut.valueBuffer) }
}
writeVarSlice(txOut.script) const vinLen = readVarInt()
}) for (var i = 0; i < vinLen; ++i) {
tx.ins.push({
hash: readSlice(32),
index: readUInt32(),
script: readVarSlice(),
sequence: readUInt32(),
witness: EMPTY_WITNESS
})
}
if (hasWitnesses) { const voutLen = readVarInt()
this.ins.forEach(function (input) { for (i = 0; i < voutLen; ++i) {
writeVector(input.witness) tx.outs.push({
value: readUInt64(),
script: readVarSlice()
}) })
} }
writeUInt32(this.locktime) if (hasWitnesses) {
for (i = 0; i < vinLen; ++i) {
tx.ins[i].witness = readVector()
}
// avoid slicing unless necessary // was this pointless?
if (initialOffset !== undefined) return buffer.slice(initialOffset, offset) if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data')
return buffer }
}
Transaction.prototype.toHex = function () { tx.locktime = readUInt32()
return this.toBuffer().toString('hex')
}
Transaction.prototype.setInputScript = function (index, scriptSig) { if (__noStrict) return tx
typeforce(types.tuple(types.Number, types.Buffer), arguments) if (offset !== buffer.length) throw new Error('Transaction has unexpected data')
this.ins[index].script = scriptSig return tx
} }
Transaction.prototype.setWitness = function (index, witness) { Transaction.fromHex = (hex) => {
typeforce(types.tuple(types.Number, [types.Buffer]), arguments) return Transaction.fromBuffer(Buffer.from(hex, 'hex'))
}
this.ins[index].witness = witness Transaction.isCoinbaseHash = (buffer) => {
typeforce(types.Hash256bit, buffer)
for (var i = 0; i < 32; ++i) {
if (buffer[i] !== 0) return false
}
return true
} }
module.exports = Transaction module.exports = Transaction

Loading…
Cancel
Save