# `BitcoinElixir.Electrum.Connection`
[🔗](https://github.com/cashlet-labs/bitcoin-elixir/blob/v0.1.0/lib/bitcoin_elixir/electrum/connection.ex#L1)

A long-lived connection to an Electrum server, for requests and live
notifications. It reconnects with backoff, moves to the next server when one
fails, and subscribes again after every reconnect.

    {:ok, conn} = BitcoinElixir.Electrum.Connection.start_link(servers: BitcoinElixir.Electrum.default_servers(:mainnet))
    {:ok, status} = BitcoinElixir.Electrum.Connection.subscribe_scripthash(conn, scripthash)
    # later, in the calling process:
    #   {:electrum, ^conn, {:scripthash, ^scripthash, new_status}}

Messages sent to subscribers:

  * `{:electrum, conn, {:scripthash, scripthash, status}}`: the address's
    history changed (`status` is `nil` for an address with no history)
  * `{:electrum, conn, {:header, %{"height" => h, "hex" => hex}}}`: a new block
  * `{:electrum, conn, :reconnected}`: the connection was replaced; statuses
    may have changed while it was down, so re-check what you watch

Subscribers are monitored; a subscription ends when its process exits.

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `request`

```elixir
@spec request(GenServer.server(), String.t(), list(), timeout()) ::
  {:ok, term()} | {:error, term()}
```

Send a request and wait for its result.

# `server`

The server in use, or `nil` while reconnecting.

# `start_link`

Options: `:servers` (required), `:name`, `:timeout` per request in
milliseconds (default 15 s).

# `subscribe_headers`

```elixir
@spec subscribe_headers(GenServer.server()) :: {:ok, map()} | {:error, term()}
```

Get new block headers. Returns the current tip.

# `subscribe_scripthash`

```elixir
@spec subscribe_scripthash(GenServer.server(), String.t()) ::
  {:ok, String.t() | nil} | {:error, term()}
```

Watch an address by its scripthash. Returns its current status.

# `unsubscribe_scripthash`

```elixir
@spec unsubscribe_scripthash(GenServer.server(), String.t()) :: :ok
```

Stop watching an address.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
