From 6789448c3b13b79044d274ee509fe631ee68cee6 Mon Sep 17 00:00:00 2001 From: Vladimir Svoboda Date: Wed, 11 Nov 2026 07:50:11 +0000 Subject: [PATCH] feat: add Esplora BTC balance providers --- README.md | 21 ++++++ blockapi/test/v2/api/test_esplora.py | 97 ++++++++++++++++++++++++++++ blockapi/v2/api/__init__.py | 1 + blockapi/v2/api/esplora.py | 92 ++++++++++++++++++++++++++ 4 files changed, 211 insertions(+) create mode 100644 blockapi/test/v2/api/test_esplora.py create mode 100644 blockapi/v2/api/esplora.py diff --git a/README.md b/README.md index cbee77ec..e6649e4c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,27 @@ # blockapi Library to interact with numerous cryptocurrency data APIs to get the basic info about account balance, transactions, staking informations, etc. + +### Confirmed Bitcoin balances with Esplora (v2) + +```python +from blockapi.v2.api import EsploraApi, MempoolSpaceApi + +api = EsploraApi() # https://blockstream.info/api/ +balances = api.get_balance('17vu4hEWtuPXFbJLPKtg4MFQnoohRE88v6') + +# Alternative endpoint, or your own Esplora instance: +alternative = MempoolSpaceApi() +custom = EsploraApi(base_url='https://example.com/api/') +``` + +These adapters return confirmed BTC only, excluding mempool changes. A valid +zero balance returns an empty list; HTTP, network, and malformed-response errors +are failures, not zero balances. Requests use 5-second connect and 15-second read +timeouts. Only individual addresses are supported; xpub/ypub/zpub wallets require +a provider with extended-key support. Selecting an alternative provider is +explicit: these classes do not automatically fail over or combine balances. + List of supported coins: | coin | API name | supported operations diff --git a/blockapi/test/v2/api/test_esplora.py b/blockapi/test/v2/api/test_esplora.py new file mode 100644 index 00000000..6672c49d --- /dev/null +++ b/blockapi/test/v2/api/test_esplora.py @@ -0,0 +1,97 @@ +from decimal import Decimal + +import pytest +from requests.exceptions import ConnectionError, ReadTimeout + +from blockapi.v2.api import EsploraApi, MempoolSpaceApi +from blockapi.v2.base import ApiException +from blockapi.v2.models import FetchResult + +ADDRESS = '17vu4hEWtuPXFbJLPKtg4MFQnoohRE88v6' + + +def response(funded=400000, spent=108101): + return { + 'address': ADDRESS, + 'chain_stats': {'funded_txo_sum': funded, 'spent_txo_sum': spent}, + 'mempool_stats': {'funded_txo_sum': 999999, 'spent_txo_sum': 123}, + } + + +@pytest.mark.parametrize( + 'api', + [ + EsploraApi(), + MempoolSpaceApi(), + EsploraApi(base_url='https://example.com/btc/api'), + ], +) +def test_confirmed_balance_and_endpoint(requests_mock, api): + requests_mock.get(api.base_url + 'address/' + ADDRESS, json=response()) + balances = api.get_balance(ADDRESS) + assert len(balances) == 1 + assert balances[0].balance == Decimal('0.00291899') + assert balances[0].raw == response() + assert requests_mock.last_request.timeout == (5, 15) + + +def test_zero_confirmed_balance_ignores_mempool(requests_mock): + api = EsploraApi() + requests_mock.get(api.base_url + 'address/' + ADDRESS, json=response(100, 100)) + assert api.get_balance(ADDRESS) == [] + + +@pytest.mark.parametrize('prefix', ['xpub', 'ypub', 'zpub', 'tpub', 'upub', 'vpub']) +def test_extended_key_rejected_without_http(requests_mock, prefix): + with pytest.raises(ApiException, match='extended public keys'): + EsploraApi().get_balance(prefix + 'example') + assert requests_mock.call_count == 0 + + +@pytest.mark.parametrize('status', [400, 429, 500, 503]) +def test_http_failure_is_not_zero_balance(requests_mock, status): + api = EsploraApi() + requests_mock.get(api.base_url + 'address/' + ADDRESS, status_code=status) + with pytest.raises(ApiException): + api.get_balance(ADDRESS) + + +@pytest.mark.parametrize('error', [ConnectionError('refused'), ReadTimeout('timeout')]) +def test_network_failure_is_not_zero_balance(requests_mock, error): + api = EsploraApi() + requests_mock.get(api.base_url + 'address/' + ADDRESS, exc=error) + with pytest.raises(ApiException): + api.get_balance(ADDRESS) + + +def test_invalid_json_is_fetch_error(requests_mock): + api = EsploraApi() + requests_mock.get( + api.base_url + 'address/' + ADDRESS, text='unavailable' + ) + with pytest.raises(ApiException, match='Invalid JSON'): + api.get_balance(ADDRESS) + + +@pytest.mark.parametrize( + 'data', + [ + None, + {}, + [], + {'chain_stats': {}}, + response(-1, 0), + response(0, 1), + response('100', 0), + response(True, 0), + response(1.5, 0), + ], +) +def test_malformed_totals_are_not_zero_balance(data): + with pytest.raises(ApiException, match='Invalid Esplora response'): + EsploraApi().parse_balances(FetchResult(data=data)) + + +def test_direct_parse_preserves_fetch_error(): + with pytest.raises(ApiException, match='unavailable'): + EsploraApi().parse_balances(FetchResult(errors=['unavailable'])) diff --git a/blockapi/v2/api/__init__.py b/blockapi/v2/api/__init__.py index 2864c1b2..00cfedcb 100644 --- a/blockapi/v2/api/__init__.py +++ b/blockapi/v2/api/__init__.py @@ -9,6 +9,7 @@ ) from blockapi.v2.api.chainso import ChainSoLitecoinApi from blockapi.v2.api.debank import DebankApi, DebankApp, DebankPrediction +from blockapi.v2.api.esplora import EsploraApi, MempoolSpaceApi from blockapi.v2.api.ethplorer import EthplorerApi from blockapi.v2.api.haskoin import HaskoinApi from blockapi.v2.api.litecoinspace import LitecoinSpaceApi diff --git a/blockapi/v2/api/esplora.py b/blockapi/v2/api/esplora.py new file mode 100644 index 00000000..ff16cb5a --- /dev/null +++ b/blockapi/v2/api/esplora.py @@ -0,0 +1,92 @@ +from blockapi.v2.base import ApiException, BalanceMixin, BlockchainApi +from blockapi.v2.coins import COIN_BTC +from blockapi.v2.models import ( + ApiOptions, + AssetType, + BalanceItem, + Blockchain, + FetchResult, + ParseResult, +) + + +class EsploraApi(BlockchainApi, BalanceMixin): + """Confirmed BTC address balances from an Esplora-compatible API. + + Defaults to Blockstream. Custom base URLs must include the API path + (e.g. https://example.com/api/). Extended public keys are not supported. + Docs: https://github.com/Blockstream/esplora/blob/master/API.md + """ + + coin = COIN_BTC + api_options = ApiOptions( + blockchain=Blockchain.BITCOIN, + base_url='https://blockstream.info/api/', + rate_limit=0.2, + ) + supported_requests = {'get_balance': 'address/{address}'} + request_timeout = (5, 15) + + def __init__(self, base_url=None, api_key=None, sleep_provider=None): + super().__init__(api_key=api_key, sleep_provider=sleep_provider) + self.base_url = (base_url or self.base_url).rstrip('/') + '/' + + def _get_response(self, request_method, headers, params, req_args): + return self._session.get( + self._build_request_url(request_method, **req_args), + headers=headers, + params=params, + timeout=self.request_timeout, + ) + + def fetch_balances(self, address: str) -> FetchResult: + if address.startswith(('xpub', 'ypub', 'zpub', 'tpub', 'upub', 'vpub')): + return FetchResult(errors=['Esplora does not support extended public keys']) + try: + return self.get_data('get_balance', address=address) + except ValueError: + # The shared HTTP helper decodes JSON outside its exception handler. + return FetchResult(errors=['Invalid JSON in Esplora response']) + + def parse_balances(self, fetch_result: FetchResult) -> ParseResult: + if fetch_result.errors: + raise ApiException(fetch_result.errors[0]) + data = fetch_result.data + stats = data.get('chain_stats') if isinstance(data, dict) else None + if not isinstance(stats, dict): + raise ApiException('Invalid Esplora response: missing chain_stats') + funded = stats.get('funded_txo_sum') + spent = stats.get('spent_txo_sum') + if ( + type(funded) is not int + or type(spent) is not int + or funded < 0 + or spent < 0 + or spent > funded + ): + raise ApiException('Invalid Esplora response: invalid confirmed totals') + + # Exclude mempool deltas to preserve Haskoin's confirmed-only semantics. + balance_raw = funded - spent + if balance_raw == 0: + return ParseResult() + return ParseResult( + data=[ + BalanceItem.from_api( + balance_raw=balance_raw, + coin=self.coin, + asset_type=AssetType.AVAILABLE, + raw=data, + ) + ] + ) + + +class MempoolSpaceApi(EsploraApi): + """Confirmed BTC address balances using mempool.space's Esplora API.""" + + api_options = ApiOptions( + blockchain=Blockchain.BITCOIN, + base_url='https://mempool.space/api/', + rate_limit=0.2, + )