# A container for the ElectrumX server
#
# ElectrumX indexes a bitcoind and answers the Electrum protocol: address
# history, UTXOs, transaction broadcast. BitDeals uses it for payment detection
# (ДС) and for UTXO lookup and broadcast (ГС).
#
# Installed from the upstream git tag, pinned below. The venv is built in the
# first stage with the rocksdb headers, and only the runtime library follows it
# into the final image.

FROM python:3.14-trixie AS builder

ARG ELECTRUMX_VERSION=2.0.0

WORKDIR /usr/src/app

RUN apt-get update \
 && apt-get install -yq --no-install-suggests --no-install-recommends \
    build-essential git librocksdb-dev pkg-config \
 && rm -rf /var/lib/apt/lists/*

RUN python -m venv venv \
 && venv/bin/pip install --no-cache-dir \
    "e_x[rocksdb] @ git+https://github.com/spesmilo/electrumx.git@${ELECTRUMX_VERSION}"


FROM python:3.14-slim-trixie

# Electrum protocol, plaintext TCP. SSL is served on 50002 when SERVICES asks
# for it; the RPC (8000) stays on localhost and is what the health check uses.
EXPOSE 50001/tcp
EXPOSE 50002/tcp

ENV USER_UID=2000
ENV USER_GID=2000
ENV HOME=/home/electrumx
# /data, not the home directory: this is the path the image this one replaces
# (lukechilds/electrumx) used, so a compose file keeps its volume line. The
# index itself has to be rebuilt anyway — see README, "Notes".
ENV DB_DIRECTORY=/data

# librocksdb9.10 is the runtime half of librocksdb-dev above; openssl is only
# for the self-signed certificate the entrypoint generates on demand.
RUN apt-get update \
 && apt-get install -yq --no-install-suggests --no-install-recommends \
    librocksdb9.10 openssl gosu \
 && rm -rf /var/lib/apt/lists/*

COPY --from=builder /usr/src/app/venv /usr/src/app/venv
COPY ./docker/run.sh /usr/local/bin/
COPY ./docker/healthy_check.sh /usr/local/bin/

# Exec-form ENTRYPOINT/HEALTHCHECK targets: a clone on a filesystem that does
# not carry the executable bit would otherwise build an unstartable image.
RUN chmod +x /usr/local/bin/run.sh /usr/local/bin/healthy_check.sh

# electrumx_server and electrumx_rpc live in the venv; putting it on PATH keeps
# both this file and the scripts free of the full path.
ENV PATH=/usr/src/app/venv/bin:$PATH

# groupadd, not addgroup: the slim images dropped the adduser package.
RUN groupadd --gid $USER_GID electrumx \
 && useradd --uid $USER_UID --gid $USER_GID --skel /dev/null --create-home --home-dir $HOME electrumx

VOLUME ${DB_DIRECTORY}
WORKDIR ${HOME}

ENTRYPOINT ["/usr/local/bin/run.sh"]

# The server starts serving only after it has caught up with the daemon, and on
# mainnet the first index takes days. The start period covers a restart on an
# existing index, not a first run — for that, watch the logs.
HEALTHCHECK --interval=30s --timeout=10s --start-period=300s --retries=3 \
  CMD ["/usr/local/bin/healthy_check.sh"]
