Transaction.fromBuffer constructor

Transaction.fromBuffer(Uint8List buffer)

Creates transaction from its hex representation stored in list of integers

Implementation

factory Transaction.fromBuffer(Uint8List buffer) {
  var offset = 0;
  ByteData bytes = buffer.buffer.asByteData();
  Uint8List readSlice(n) {
    offset += n;
    return buffer.sublist(offset - n, offset);
  }

  int readUInt32() {
    final i = bytes.getUint32(offset, Endian.little);
    offset += 4;
    return i;
  }

  int readInt32() {
    final i = bytes.getInt32(offset, Endian.little);
    offset += 4;
    return i;
  }

  int readUInt64() {
    final i = bytes.getUint64(offset, Endian.little);
    offset += 8;
    return i;
  }

  int readVarInt() {
    final vi = varuint.decode(buffer, offset);
    offset += varuint.encodingLength(vi);
    return vi;
  }

  Uint8List readVarSlice() {
    return readSlice(readVarInt());
  }

  final tx = new Transaction(readInt32(), readUInt32());

  final vinLen = readVarInt();
  for (var i = 0; i < vinLen; ++i) {
    tx.inputs.add(new Input(
      hash: readSlice(32),
      index: readUInt32(),
      script: readVarSlice(),
      sequence: readUInt32()));
  }
  final voutLen = readVarInt();
  for (var i = 0; i < voutLen; ++i) {
    tx.outputs.add(new Output(value: readUInt64(), script: readVarSlice()));
  }

  if (offset != buffer.length)
    throw new ArgumentError('Transaction has unexpected data');
  return tx;
}