Browse Source

Merge pull request #1086 from bitcoinjs/refactorTransaction

Move Transaction to ES6 class syntax
v4
Jonathan Underwood 6 years ago
committed by GitHub
parent
commit
5e1ae82a5d
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 409
      src/transaction.js

409
src/transaction.js

@ -16,26 +16,11 @@ function varSliceSize (someScript) {
function vectorSize (someVector) { function 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,114 +31,41 @@ 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 () {
const i = buffer.readUInt32LE(offset)
offset += 4
return i
}
function readInt32 () {
const i = buffer.readInt32LE(offset)
offset += 4
return i
}
function readUInt64 () {
const i = bufferutils.readUInt64LE(buffer, offset)
offset += 8
return i
}
function readVarInt () {
const vi = varuint.decode(buffer, offset)
offset += varuint.decode.bytes
return vi
}
function readVarSlice () {
return readSlice(readVarInt())
} }
function readVector () { static get DEFAULT_SEQUENCE () {
const count = readVarInt() return 0xffffffff
const vector = []
for (var i = 0; i < count; i++) vector.push(readVarSlice())
return vector
} }
static get SIGHASH_ALL () {
const tx = new Transaction() return 0x01
tx.version = readInt32()
const marker = buffer.readUInt8(offset)
const flag = buffer.readUInt8(offset + 1)
let hasWitnesses = false
if (marker === Transaction.ADVANCED_TRANSACTION_MARKER &&
flag === Transaction.ADVANCED_TRANSACTION_FLAG) {
offset += 2
hasWitnesses = true
} }
static get SIGHASH_NONE () {
const vinLen = readVarInt() return 0x02
for (var i = 0; i < vinLen; ++i) {
tx.ins.push({
hash: readSlice(32),
index: readUInt32(),
script: readVarSlice(),
sequence: readUInt32(),
witness: EMPTY_WITNESS
})
} }
static get SIGHASH_SINGLE () {
const voutLen = readVarInt() return 0x03
for (i = 0; i < voutLen; ++i) {
tx.outs.push({
value: readUInt64(),
script: readVarSlice()
})
} }
static get SIGHASH_ANYONECANPAY () {
if (hasWitnesses) { return 0x80
for (i = 0; i < vinLen; ++i) {
tx.ins[i].witness = readVector()
} }
static get ADVANCED_TRANSACTION_MARKER () {
// was this pointless? return 0x00
if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data')
} }
static get ADVANCED_TRANSACTION_FLAG () {
tx.locktime = readUInt32() return 0x01
if (__noStrict) return tx
if (offset !== buffer.length) throw new Error('Transaction has unexpected data')
return tx
}
Transaction.fromHex = function (hex) {
return Transaction.fromBuffer(Buffer.from(hex, 'hex'))
}
Transaction.isCoinbaseHash = function (buffer) {
typeforce(types.Hash256bit, buffer)
for (var i = 0; i < 32; ++i) {
if (buffer[i] !== 0) return false
} }
return true
}
Transaction.prototype.isCoinbase = function () { isCoinbase () {
return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash)
} }
Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) { addInput (hash, index, sequence, scriptSig) {
typeforce(types.tuple( typeforce(types.tuple(
types.Hash256bit, types.Hash256bit,
types.UInt32, types.UInt32,
@ -173,9 +85,9 @@ Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) {
sequence: sequence, sequence: sequence,
witness: EMPTY_WITNESS witness: EMPTY_WITNESS
}) - 1) }) - 1)
} }
Transaction.prototype.addOutput = function (scriptPubKey, value) { addOutput (scriptPubKey, value) {
typeforce(types.tuple(types.Buffer, types.Satoshi), arguments) typeforce(types.tuple(types.Buffer, types.Satoshi), arguments)
// Add the output and return the output's index // Add the output and return the output's index
@ -183,47 +95,53 @@ Transaction.prototype.addOutput = function (scriptPubKey, value) {
script: scriptPubKey, script: scriptPubKey,
value: value value: value
}) - 1) }) - 1)
} }
Transaction.prototype.hasWitnesses = function () { hasWitnesses () {
return this.ins.some(function (x) { return this.ins.some((x) => {
return x.witness.length !== 0 return x.witness.length !== 0
}) })
} }
Transaction.prototype.weight = function () { weight () {
const base = this.__byteLength(false) const base = this.__byteLength(false)
const total = this.__byteLength(true) const total = this.__byteLength(true)
return base * 3 + total return base * 3 + total
} }
Transaction.prototype.virtualSize = function () { virtualSize () {
return Math.ceil(this.weight() / 4) return Math.ceil(this.weight() / 4)
} }
Transaction.prototype.byteLength = function () { byteLength () {
return this.__byteLength(true) return this.__byteLength(true)
} }
Transaction.prototype.__byteLength = function (__allowWitness) { __byteLength (__allowWitness) {
const hasWitnesses = __allowWitness && this.hasWitnesses() const hasWitnesses = __allowWitness && this.hasWitnesses()
return ( return (
(hasWitnesses ? 10 : 8) + (hasWitnesses ? 10 : 8) +
varuint.encodingLength(this.ins.length) + varuint.encodingLength(this.ins.length) +
varuint.encodingLength(this.outs.length) + varuint.encodingLength(this.outs.length) +
this.ins.reduce(function (sum, input) { return sum + 40 + varSliceSize(input.script) }, 0) + this.ins.reduce((sum, input) => {
this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) + return sum + 40 + varSliceSize(input.script)
(hasWitnesses ? this.ins.reduce(function (sum, input) { return sum + vectorSize(input.witness) }, 0) : 0) }, 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)
) )
} }
Transaction.prototype.clone = function () { clone () {
const newTx = new Transaction() const newTx = new Transaction()
newTx.version = this.version newTx.version = this.version
newTx.locktime = this.locktime newTx.locktime = this.locktime
newTx.ins = this.ins.map(function (txIn) { newTx.ins = this.ins.map((txIn) => {
return { return {
hash: txIn.hash, hash: txIn.hash,
index: txIn.index, index: txIn.index,
@ -233,7 +151,7 @@ Transaction.prototype.clone = function () {
} }
}) })
newTx.outs = this.outs.map(function (txOut) { newTx.outs = this.outs.map((txOut) => {
return { return {
script: txOut.script, script: txOut.script,
value: txOut.value value: txOut.value
@ -241,9 +159,9 @@ Transaction.prototype.clone = function () {
}) })
return newTx return newTx
} }
/** /**
* Hash transaction for signing a specific input. * Hash transaction for signing a specific input.
* *
* Bitcoin uses a different hash for each signed transaction input. * Bitcoin uses a different hash for each signed transaction input.
@ -251,14 +169,14 @@ Transaction.prototype.clone = function () {
* hashType, and then hashes the result. * hashType, and then hashes the result.
* This hash can then be used to sign the provided transaction input. * This hash can then be used to sign the provided transaction input.
*/ */
Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) { hashForSignature (inIndex, prevOutScript, hashType) {
typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments) 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 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
if (inIndex >= this.ins.length) return ONE if (inIndex >= this.ins.length) return ONE
// ignore OP_CODESEPARATOR // ignore OP_CODESEPARATOR
const ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) { const ourScript = bscript.compile(bscript.decompile(prevOutScript).filter((x) => {
return x !== opcodes.OP_CODESEPARATOR return x !== opcodes.OP_CODESEPARATOR
})) }))
@ -269,7 +187,7 @@ Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashT
txTmp.outs = [] txTmp.outs = []
// ignore sequence numbers (except at inIndex) // ignore sequence numbers (except at inIndex)
txTmp.ins.forEach(function (input, i) { txTmp.ins.forEach((input, i) => {
if (i === inIndex) return if (i === inIndex) return
input.sequence = 0 input.sequence = 0
@ -289,7 +207,7 @@ Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashT
} }
// ignore sequence numbers (except at inIndex) // ignore sequence numbers (except at inIndex)
txTmp.ins.forEach(function (input, y) { txTmp.ins.forEach((input, y) => {
if (y === inIndex) return if (y === inIndex) return
input.sequence = 0 input.sequence = 0
@ -304,7 +222,9 @@ Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashT
// SIGHASH_ALL: only ignore input scripts // SIGHASH_ALL: only ignore input scripts
} else { } else {
// "blank" others input scripts // "blank" others input scripts
txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT }) txTmp.ins.forEach((input) => {
input.script = EMPTY_SCRIPT
})
txTmp.ins[inIndex].script = ourScript txTmp.ins[inIndex].script = ourScript
} }
@ -314,20 +234,34 @@ Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashT
txTmp.__toBuffer(buffer, 0, false) txTmp.__toBuffer(buffer, 0, false)
return bcrypto.hash256(buffer) return bcrypto.hash256(buffer)
} }
Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value, hashType) { hashForWitnessV0 (inIndex, prevOutScript, value, hashType) {
typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments) typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments)
let tbuffer, toffset let tbuffer, toffset
function writeSlice (slice) { toffset += slice.copy(tbuffer, toffset) }
function writeUInt32 (i) { toffset = tbuffer.writeUInt32LE(i, toffset) } function writeSlice (slice) {
function writeUInt64 (i) { toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset) } toffset += slice.copy(tbuffer, toffset)
}
function writeUInt32 (i) {
toffset = tbuffer.writeUInt32LE(i, toffset)
}
function writeUInt64 (i) {
toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset)
}
function writeVarInt (i) { function writeVarInt (i) {
varuint.encode(i, tbuffer, toffset) varuint.encode(i, tbuffer, toffset)
toffset += varuint.encode.bytes toffset += varuint.encode.bytes
} }
function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
function writeVarSlice (slice) {
writeVarInt(slice.length)
writeSlice(slice)
}
let hashOutputs = ZERO let hashOutputs = ZERO
let hashPrevouts = ZERO let hashPrevouts = ZERO
@ -337,7 +271,7 @@ Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value
tbuffer = Buffer.allocUnsafe(36 * this.ins.length) tbuffer = Buffer.allocUnsafe(36 * this.ins.length)
toffset = 0 toffset = 0
this.ins.forEach(function (txIn) { this.ins.forEach((txIn) => {
writeSlice(txIn.hash) writeSlice(txIn.hash)
writeUInt32(txIn.index) writeUInt32(txIn.index)
}) })
@ -351,7 +285,7 @@ Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value
tbuffer = Buffer.allocUnsafe(4 * this.ins.length) tbuffer = Buffer.allocUnsafe(4 * this.ins.length)
toffset = 0 toffset = 0
this.ins.forEach(function (txIn) { this.ins.forEach((txIn) => {
writeUInt32(txIn.sequence) writeUInt32(txIn.sequence)
}) })
@ -360,14 +294,14 @@ Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value
if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
(hashType & 0x1f) !== Transaction.SIGHASH_NONE) { (hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
const txOutsSize = this.outs.reduce(function (sum, output) { const txOutsSize = this.outs.reduce((sum, output) => {
return sum + 8 + varSliceSize(output.script) return sum + 8 + varSliceSize(output.script)
}, 0) }, 0)
tbuffer = Buffer.allocUnsafe(txOutsSize) tbuffer = Buffer.allocUnsafe(txOutsSize)
toffset = 0 toffset = 0
this.outs.forEach(function (out) { this.outs.forEach((out) => {
writeUInt64(out.value) writeUInt64(out.value)
writeVarSlice(out.script) writeVarSlice(out.script)
}) })
@ -400,36 +334,60 @@ Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value
writeUInt32(this.locktime) writeUInt32(this.locktime)
writeUInt32(hashType) writeUInt32(hashType)
return bcrypto.hash256(tbuffer) return bcrypto.hash256(tbuffer)
} }
Transaction.prototype.getHash = function () { getHash () {
return bcrypto.hash256(this.__toBuffer(undefined, undefined, false)) return bcrypto.hash256(this.__toBuffer(undefined, undefined, false))
} }
Transaction.prototype.getId = function () { getId () {
// transaction hash's are displayed in reverse order // transaction hash's are displayed in reverse order
return this.getHash().reverse().toString('hex') return this.getHash().reverse().toString('hex')
} }
Transaction.prototype.toBuffer = function (buffer, initialOffset) { toBuffer (buffer, initialOffset) {
return this.__toBuffer(buffer, initialOffset, true) return this.__toBuffer(buffer, initialOffset, true)
} }
Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitness) { __toBuffer (buffer, initialOffset, __allowWitness) {
if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness)) if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness))
let offset = initialOffset || 0 let offset = initialOffset || 0
function writeSlice (slice) { offset += slice.copy(buffer, offset) }
function writeUInt8 (i) { offset = buffer.writeUInt8(i, offset) } function writeSlice (slice) {
function writeUInt32 (i) { offset = buffer.writeUInt32LE(i, offset) } offset += slice.copy(buffer, offset)
function writeInt32 (i) { offset = buffer.writeInt32LE(i, offset) } }
function writeUInt64 (i) { offset = bufferutils.writeUInt64LE(buffer, i, offset) }
function writeUInt8 (i) {
offset = buffer.writeUInt8(i, offset)
}
function writeUInt32 (i) {
offset = buffer.writeUInt32LE(i, offset)
}
function writeInt32 (i) {
offset = buffer.writeInt32LE(i, offset)
}
function writeUInt64 (i) {
offset = bufferutils.writeUInt64LE(buffer, i, offset)
}
function writeVarInt (i) { function writeVarInt (i) {
varuint.encode(i, buffer, offset) varuint.encode(i, buffer, offset)
offset += varuint.encode.bytes offset += varuint.encode.bytes
} }
function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
function writeVector (vector) { writeVarInt(vector.length); vector.forEach(writeVarSlice) } function writeVarSlice (slice) {
writeVarInt(slice.length)
writeSlice(slice)
}
function writeVector (vector) {
writeVarInt(vector.length)
vector.forEach(writeVarSlice)
}
writeInt32(this.version) writeInt32(this.version)
@ -442,7 +400,7 @@ Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitne
writeVarInt(this.ins.length) writeVarInt(this.ins.length)
this.ins.forEach(function (txIn) { this.ins.forEach((txIn) => {
writeSlice(txIn.hash) writeSlice(txIn.hash)
writeUInt32(txIn.index) writeUInt32(txIn.index)
writeVarSlice(txIn.script) writeVarSlice(txIn.script)
@ -450,7 +408,7 @@ Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitne
}) })
writeVarInt(this.outs.length) writeVarInt(this.outs.length)
this.outs.forEach(function (txOut) { this.outs.forEach((txOut) => {
if (!txOut.valueBuffer) { if (!txOut.valueBuffer) {
writeUInt64(txOut.value) writeUInt64(txOut.value)
} else { } else {
@ -461,7 +419,7 @@ Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitne
}) })
if (hasWitnesses) { if (hasWitnesses) {
this.ins.forEach(function (input) { this.ins.forEach((input) => {
writeVector(input.witness) writeVector(input.witness)
}) })
} }
@ -471,22 +429,127 @@ Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitne
// avoid slicing unless necessary // avoid slicing unless necessary
if (initialOffset !== undefined) return buffer.slice(initialOffset, offset) if (initialOffset !== undefined) return buffer.slice(initialOffset, offset)
return buffer return buffer
} }
Transaction.prototype.toHex = function () { toHex () {
return this.toBuffer().toString('hex') return this.toBuffer().toString('hex')
} }
Transaction.prototype.setInputScript = function (index, scriptSig) { setInputScript (index, scriptSig) {
typeforce(types.tuple(types.Number, types.Buffer), arguments) typeforce(types.tuple(types.Number, types.Buffer), arguments)
this.ins[index].script = scriptSig this.ins[index].script = scriptSig
} }
Transaction.prototype.setWitness = function (index, witness) { setWitness (index, witness) {
typeforce(types.tuple(types.Number, [types.Buffer]), arguments) typeforce(types.tuple(types.Number, [types.Buffer]), arguments)
this.ins[index].witness = witness this.ins[index].witness = witness
}
}
Transaction.fromBuffer = (buffer, __noStrict) => {
let offset = 0
function readSlice (n) {
offset += n
return buffer.slice(offset - n, offset)
}
function readUInt32 () {
const i = buffer.readUInt32LE(offset)
offset += 4
return i
}
function readInt32 () {
const i = buffer.readInt32LE(offset)
offset += 4
return i
}
function readUInt64 () {
const i = bufferutils.readUInt64LE(buffer, offset)
offset += 8
return i
}
function readVarInt () {
const vi = varuint.decode(buffer, offset)
offset += varuint.decode.bytes
return vi
}
function readVarSlice () {
return readSlice(readVarInt())
}
function readVector () {
const count = readVarInt()
const vector = []
for (var i = 0; i < count; i++) vector.push(readVarSlice())
return vector
}
const tx = new Transaction()
tx.version = readInt32()
const marker = buffer.readUInt8(offset)
const flag = buffer.readUInt8(offset + 1)
let hasWitnesses = false
if (marker === Transaction.ADVANCED_TRANSACTION_MARKER &&
flag === Transaction.ADVANCED_TRANSACTION_FLAG) {
offset += 2
hasWitnesses = true
}
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
})
}
const voutLen = readVarInt()
for (i = 0; i < voutLen; ++i) {
tx.outs.push({
value: readUInt64(),
script: readVarSlice()
})
}
if (hasWitnesses) {
for (i = 0; i < vinLen; ++i) {
tx.ins[i].witness = readVector()
}
// was this pointless?
if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data')
}
tx.locktime = readUInt32()
if (__noStrict) return tx
if (offset !== buffer.length) throw new Error('Transaction has unexpected data')
return tx
}
Transaction.fromHex = (hex) => {
return Transaction.fromBuffer(Buffer.from(hex, 'hex'))
}
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