class PersistBlockTask extends AbstractEthTask<Block> {

  public static Supplier<CompletableFuture<List<Block>>> forUnorderedBlocks(
      final ProtocolSchedule protocolSchedule,
      final ProtocolContext protocolContext,
      final EthContext ethContext,
      final List<Block> blocks,
      final HeaderValidationMode headerValidationMode,
      final MetricsSystem metricsSystem) {
    checkArgument(!blocks.isEmpty(), "No blocks to import provided");
    return () -> {
      final CompletableFuture<List<Block>> finalResult = new CompletableFuture<>();
      final List<Block> successfulImports = new ArrayList<>();
      final Iterator<PersistBlockTask> tasks =
          blocks.stream()
              .map(
                  block ->
                      PersistBlockTask.create(
                          protocolSchedule,
                          protocolContext,
                          ethContext,
                          block,
                          headerValidationMode,
                          metricsSystem))
              .iterator();

      CompletableFuture<Block> future = tasks.next().run();
      while (tasks.hasNext()) {
        final PersistBlockTask task = tasks.next();
        future =
            future
                .handle((r, t) -> r)
                .thenCompose(
                    r -> {
                      if (r != null) {
                        successfulImports.add(r);
                      }
                      return task.run();
                    });
      }
      future.whenComplete(
          (r, t) -> {
            if (r != null) {
              successfulImports.add(r);
            }
            if (successfulImports.size() > 0) {
              finalResult.complete(successfulImports);
            } else {
              finalResult.completeExceptionally(t);
            }
          });

      return finalResult;
    };
  }

  private  PersistBlockTask(
      final ProtocolSchedule protocolSchedule,
      final ProtocolContext protocolContext,
      final EthContext ethContext,
      final Block block,
      final HeaderValidationMode headerValidationMode,
      final MetricsSystem metricsSystem);

}