compile method

Uint8List compile(
  1. dynamic _chunks
)

Compile script

_chunks should be Uint8List, List

Implementation

Uint8List compile(dynamic _chunks) {
  if (_chunks is Uint8List) return _chunks;

  if (_chunks is! List) {
    throw Exception('Chunks must be List');
  }

  int bufferSize = _chunks.fold(0, (accum, chunk) {
    // data chunk
    if (chunk is Uint8List) {
      // adhere to BIP62.3, minimal push policy
      if (chunk.length == 1 && _asMinimalOP(chunk) != null) {
        return accum + 1;
      }

      return accum + pushdata.encodingLength(chunk.length) + chunk.length;
    }

    return accum + 1;
  });

  Uint8List buffer = Uint8List(bufferSize);
  BufferWriter writer = BufferWriter.fromTypedData(buffer);

  for (var chunk in _chunks) {
    // data chunk
    if (chunk is Uint8List) {
      final opcode = _asMinimalOP(chunk);
      if (opcode != null) {
        writer.setUInt8(opcode);
        continue;
      }

      writer.offset += pushdata.encode(buffer, chunk.length, writer.offset);
      writer.setSlice(chunk);
    } else {
      writer.setUInt8(chunk);
    }
  }

  if (writer.offset != buffer.length) {
    throw Exception('Could not decode chunks');
  }
  return buffer;
}