Skip to content

use dns resolver to get account key #12

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

Merged
merged 8 commits into from
Dec 6, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions examples/dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
from loguru import logger

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from pythclient.pythclient import PythClient, V2_PROGRAM_KEY, V2_FIRST_MAPPING_ACCOUNT_KEY # noqa
from pythclient.pythclient import PythClient # noqa
from pythclient.ratelimit import RateLimit # noqa
from pythclient.pythaccounts import PythPriceAccount # noqa
from pythclient.utils import get_key # noqa

logger.enable("pythclient")

Expand All @@ -32,9 +33,11 @@ def set_to_exit(sig: Any, frame: Any):
async def main():
global to_exit
use_program = len(sys.argv) >= 2 and sys.argv[1] == "program"
v2_first_mapping_account_key = get_key("devnet", "mapping")
v2_program_key = get_key("devnet", "program")
async with PythClient(
first_mapping_account_key=V2_FIRST_MAPPING_ACCOUNT_KEY,
program_key=V2_PROGRAM_KEY if use_program else None,
first_mapping_account_key=v2_first_mapping_account_key,
program_key=v2_program_key if use_program else None,
) as c:
await c.refresh_all_prices()
products = await c.get_products()
Expand All @@ -57,7 +60,7 @@ async def main():
await ws.connect()
if use_program:
print("Subscribing to program account")
await ws.program_subscribe(V2_PROGRAM_KEY, await c.get_all_accounts())
await ws.program_subscribe(v2_program_key, await c.get_all_accounts())
else:
print("Subscribing to all prices")
for account in all_prices:
Expand Down Expand Up @@ -88,7 +91,7 @@ async def main():

print("Unsubscribing...")
if use_program:
await ws.program_unsubscribe(V2_PROGRAM_KEY)
await ws.program_unsubscribe(v2_program_key)
else:
for account in all_prices:
await ws.unsubscribe(account)
Expand Down
6 changes: 1 addition & 5 deletions pythclient/pythclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,13 @@
from .pythaccounts import PythAccount, PythMappingAccount, PythProductAccount, PythPriceAccount
from . import exceptions, config, ratelimit

V1_FIRST_MAPPING_ACCOUNT_KEY = "ArppEFcsybCLE8CRtQJLQ9tLv2peGmQoKWFuiUWm4KBP"
V2_FIRST_MAPPING_ACCOUNT_KEY = "BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2"
V2_PROGRAM_KEY = "gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s"


class PythClient:
def __init__(self, *,
solana_client: Optional[SolanaClient] = None,
solana_endpoint: str = SOLANA_DEVNET_HTTP_ENDPOINT,
solana_ws_endpoint: str = SOLANA_DEVNET_WS_ENDPOINT,
first_mapping_account_key: str = V1_FIRST_MAPPING_ACCOUNT_KEY,
first_mapping_account_key: str,
program_key: Optional[str] = None,
aiohttp_client_session: Optional[aiohttp.ClientSession] = None) -> None:
self._first_mapping_account_key = SolanaPublicKey(first_mapping_account_key)
Expand Down
35 changes: 35 additions & 0 deletions pythclient/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import ast
import dns.resolver
from loguru import logger
from typing import Optional

DEFAULT_VERSION = "v2"


# Retrieving keys via DNS TXT records should not be considered secure and is provided as a convenience only.
# Accounts should be stored locally and verified before being used for production.
def get_key(network: str, type: str, version: str = DEFAULT_VERSION) -> Optional[str]:
"""
Get the program or mapping keys from dns TXT records.

Example dns records:

devnet-program-v2.pyth.network
mainnet-program-v2.pyth.network
testnet-mapping-v2.pyth.network
"""
url = f"{network}-{type}-{version}.pyth.network"
try:
answer = dns.resolver.resolve(url, "TXT")
except dns.resolver.NXDOMAIN:
logger.error("TXT record for {} not found", url)
return ""
if len(answer) != 1:
logger.error("Invalid number of records returned for {}!", url)
return ""
# Example of the raw_key:
# "program=FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH"
raw_key = ast.literal_eval(list(answer)[0].to_text())
# program=FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH"
_, key = raw_key.split("=", 1)
return key
Comment on lines +12 to +35
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wrote this code for pyth-observer as a quick and dirty hack and don't consider it very pretty python. Would you mind adding some tests for it? I'd be willing to help you do so if necessary.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will write tests for it 🙂

7 changes: 5 additions & 2 deletions tests/test_pyth_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
_ACCOUNT_HEADER_BYTES, _VERSION_2, PythMappingAccount, PythPriceType, PythProductAccount, PythPriceAccount
)

from pythclient.pythclient import PythClient, V2_FIRST_MAPPING_ACCOUNT_KEY, V2_PROGRAM_KEY, WatchSession
from pythclient.pythclient import PythClient, WatchSession
from pythclient.solana import (
SolanaClient,
SolanaCommitment,
Expand All @@ -16,14 +16,17 @@

from pytest_mock import MockerFixture

from mock import AsyncMock
from mock import AsyncMock, Mock


# Using constants instead of fixtures because:
# 1) these values are not expected to be mutated
# 2) these values are used in get_account_info_resp() and get_program_accounts_resp()
# and so if they are passed in as fixtures, the functions will complain for the args
# while mocking the respective functions
V2_FIRST_MAPPING_ACCOUNT_KEY = 'BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2'
V2_PROGRAM_KEY = 'gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s'
Comment on lines +27 to +28
Copy link
Contributor Author

@cctdaniel cctdaniel Dec 1, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

declared as constants for the same reason as the constants below -- doesn't seems like there's a need to mock this?


BCH_PRODUCT_ACCOUNT_KEY = '89GseEmvNkzAMMEXcW9oTYzqRPXTsJ3BmNerXmgA1osV'
BCH_PRICE_ACCOUNT_KEY = '4EQrNZYk5KR1RnjyzbaaRbHsv8VqZWzSUtvx58wLsZbj'

Expand Down