@Nullable
  public Bytes writeContainer(@Nullable final Bytes auxData) {
    // do not write invalid containers
    if (invalidReason != null) {
      return null;
    }

    try {
      ByteArrayOutputStream baos =
          new ByteArrayOutputStream(container.size() + dataLength - data.size());
      DataOutputStream out = new DataOutputStream(baos);

      // EOF header
      out.writeByte(EOF_PREFIX_BYTE);
      out.writeByte(0);
      out.writeByte(version);

      // Types header
      out.writeByte(SECTION_TYPES);
      out.writeShort(codeSections.length * 4);

      // Code header
      out.writeByte(SECTION_CODE);
      out.writeShort(codeSections.length);
      for (CodeSection cs : codeSections) {
        out.writeShort(cs.length);
      }

      // Subcontainers header
      if (subContainers != null && subContainers.length > 0) {
        out.writeByte(SECTION_CONTAINER);
        out.writeShort(subContainers.length);
        for (EOFLayout container : subContainers) {
          out.writeShort(container.container.size());
        }
      }

      // Data header
      out.writeByte(SECTION_DATA);
      if (auxData == null) {
        out.writeShort(dataLength);
      } else {
        int newSize = data.size() + auxData.size();
        if (newSize < dataLength) {
          // aux data must cover claimed data lengths.
          return null;
        }
        out.writeShort(newSize);
      }

      // header end
      out.writeByte(0);

      // Types information
      for (CodeSection cs : codeSections) {
        out.writeByte(cs.inputs);
        if (cs.returning) {
          out.writeByte(cs.outputs);
        } else {
          out.writeByte(0x80);
        }
        out.writeShort(cs.maxStackHeight);
      }

      // Code sections
      for (CodeSection cs : codeSections) {
        out.write(container.slice(cs.entryPoint, cs.length).toArray());
      }

      // Subcontainers
      if (subContainers != null) {
        for (EOFLayout container : subContainers) {
          out.write(container.container.toArrayUnsafe());
        }
      }

      // data
      out.write(data.toArrayUnsafe());
      if (auxData != null) {
        out.write(auxData.toArrayUnsafe());
      }

      return Bytes.wrap(baos.toByteArray());
    } catch (IOException ioe) {
      // ByteArrayOutputStream should never throw, so something has gone very wrong.  Wrap as
      // runtime
      // and re-throw.
      throw new RuntimeException(ioe);
    }
  }
Re-writes the container with optional auxiliary data.

@param auxData the auxiliary data
@return Null if there was an error (validation or otherwise) , or the bytes of the re-written
    container.
evm/src/main/java/org/hyperledger/besu/evm/code/EOFLayout.java