Repository navigation
draft: feat: add Esplora BTC balance providers #288
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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='<html>unavailable</html>' | ||
| ) | ||
| 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'])) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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, | ||
| ) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd remove this, not useful imo