toBytes method

Uint8List toBytes({
  1. bool segwit = false,
})

Serializes Transaction to bytes

Implementation

Uint8List toBytes({bool segwit = false}) {
  DynamicByteTracker data = DynamicByteTracker();
  try {
    data.add(version);
    if (segwit) {
      data.add([0x00, 0x01]);
    }
    final txInCountBytes = encodeVarint(inputs.length);
    final txOutCountBytes = encodeVarint(outputs.length);

    data.add(txInCountBytes);
    for (final txIn in inputs) {
      data.add(txIn.toBytes());
    }
    data.add(txOutCountBytes);
    for (final txOut in outputs) {
      data.add(txOut.toBytes());
    }
    if (segwit) {
      for (final wit in witnesses) {
        final witnessesCountBytes = Uint8List.fromList([wit.stack.length]);
        data.add(witnessesCountBytes);
        data.add(wit.toBytes());
      }
    }
    data.add(locktime);
    return data.toBytes();
  } finally {
    data.close();
  }
}