Add BufferReader to Transaction and fix tests

This commit is contained in:
junderw 2020-01-15 10:50:33 +09:00
parent 91e6c8abc3
commit 06674b19fe
No known key found for this signature in database
GPG key ID: B256185D3A971908
5 changed files with 40 additions and 113 deletions

View file

@ -1,6 +1,5 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const bufferutils = require('./bufferutils');
const bufferutils_1 = require('./bufferutils');
const bcrypto = require('./crypto');
const bscript = require('./script');
@ -47,80 +46,48 @@ class Transaction {
this.outs = [];
}
static fromBuffer(buffer, _NO_STRICT) {
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 (let i = 0; i < count; i++) vector.push(readVarSlice());
return vector;
}
const bufferReader = new bufferutils_1.BufferReader(buffer);
const tx = new Transaction();
tx.version = readInt32();
const marker = buffer.readUInt8(offset);
const flag = buffer.readUInt8(offset + 1);
tx.version = bufferReader.readInt32();
const marker = bufferReader.readUInt8();
const flag = bufferReader.readUInt8();
let hasWitnesses = false;
if (
marker === Transaction.ADVANCED_TRANSACTION_MARKER &&
flag === Transaction.ADVANCED_TRANSACTION_FLAG
) {
offset += 2;
hasWitnesses = true;
} else {
bufferReader.offset -= 2;
}
const vinLen = readVarInt();
const vinLen = bufferReader.readVarInt();
for (let i = 0; i < vinLen; ++i) {
tx.ins.push({
hash: readSlice(32),
index: readUInt32(),
script: readVarSlice(),
sequence: readUInt32(),
hash: bufferReader.readSlice(32),
index: bufferReader.readUInt32(),
script: bufferReader.readVarSlice(),
sequence: bufferReader.readUInt32(),
witness: EMPTY_WITNESS,
});
}
const voutLen = readVarInt();
const voutLen = bufferReader.readVarInt();
for (let i = 0; i < voutLen; ++i) {
tx.outs.push({
value: readUInt64(),
script: readVarSlice(),
value: bufferReader.readUInt64(),
script: bufferReader.readVarSlice(),
});
}
if (hasWitnesses) {
for (let i = 0; i < vinLen; ++i) {
tx.ins[i].witness = readVector();
tx.ins[i].witness = bufferReader.readVector();
}
// was this pointless?
if (!tx.hasWitnesses())
throw new Error('Transaction has superfluous witness data');
}
tx.locktime = readUInt32();
tx.locktime = bufferReader.readUInt32();
if (_NO_STRICT) return tx;
if (offset !== buffer.length)
if (bufferReader.offset !== buffer.length)
throw new Error('Transaction has unexpected data');
return tx;
}