-
Notifications
You must be signed in to change notification settings - Fork 36
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
Implemented a native auth client and faucet functionality #418
Changes from 5 commits
0fbb872
4bfd7b7
41e1a56
e0023e9
50c81f3
046adc2
63627d0
b311fce
030cf55
25c1f32
6c0450a
6d45b8a
cb32a68
990fa97
01c19a3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
FROM ubuntu:22.04 | ||
|
||
ARG USERNAME=developer | ||
ARG USER_UID=1000 | ||
ARG USER_GID=$USER_UID | ||
|
||
# Create the user | ||
RUN groupadd --gid $USER_GID $USERNAME \ | ||
&& useradd --uid $USER_UID --gid $USER_GID -m $USERNAME \ | ||
# | ||
# [Optional] Add sudo support. Omit if you don't need to install software after connecting. | ||
&& apt-get update \ | ||
&& apt-get install -y sudo \ | ||
&& echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \ | ||
&& chmod 0440 /etc/sudoers.d/$USERNAME | ||
|
||
# Install some dependencies as root | ||
RUN apt-get update && apt-get install -y \ | ||
wget \ | ||
python3.10 python3-pip python3.10-venv \ | ||
git \ | ||
pkg-config \ | ||
libssl-dev && \ | ||
rm -rf /var/lib/apt/lists/* | ||
|
||
# Switch to regular user | ||
USER $USERNAME | ||
WORKDIR /home/${USERNAME} | ||
|
||
RUN sudo apt-get update | ||
RUN sudo apt-get install git | ||
|
||
# RUN sudo apt install pipx -y 8 | ||
|
||
# RUN pipx ensurepath | ||
|
||
# RUN pipx install git+https://github.com/multiversx/mx-sdk-py-cli@fix-deps-all |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
import logging | ||
import webbrowser | ||
from enum import Enum | ||
from typing import Any, List, Tuple | ||
|
||
from multiversx_sdk_core import Message, MessageComputer | ||
|
||
from multiversx_sdk_cli import cli_shared | ||
from multiversx_sdk_cli.errors import BadUserInput | ||
from multiversx_sdk_cli.native_auth_client import (NativeAuthClient, | ||
NativeAuthClientConfig) | ||
|
||
logger = logging.getLogger("cli.faucet") | ||
|
||
|
||
class WebWalletUrls(Enum): | ||
DEVNET = "https://devnet-wallet.multiversx.com" | ||
TESTNET = "https://testnet-wallet.multiversx.com" | ||
|
||
|
||
class ApiUrls(Enum): | ||
DEVNET = "https://devnet-api.multiversx.com" | ||
TESTNET = "https://testnet-api.multiversx.com" | ||
|
||
|
||
def setup_parser(args: List[str], subparsers: Any) -> Any: | ||
parser = cli_shared.add_group_subparser(subparsers, "faucet", "Get xEGLD on Devnet or Testnet") | ||
subparsers = parser.add_subparsers() | ||
|
||
sub = cli_shared.add_command_subparser(subparsers, "faucet", "request", "Request xEGLD.") | ||
cli_shared.add_wallet_args(args, sub) | ||
sub.add_argument("--chain", required=True, help="the chain identifier") | ||
Comment on lines
+29
to
+30
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. here it lists There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. one of |
||
sub.set_defaults(func=faucet) | ||
|
||
parser.epilog = cli_shared.build_group_epilog(subparsers) | ||
return subparsers | ||
|
||
|
||
def faucet(args: Any): | ||
account = cli_shared.prepare_account(args) | ||
wallet, api = get_wallet_and_api_urls(args) | ||
|
||
config = NativeAuthClientConfig(origin=wallet, api_url=api) | ||
client = NativeAuthClient(config) | ||
|
||
init_token = client.initialize() | ||
message = Message(f"{account.address.to_bech32()}{init_token}".encode()) | ||
|
||
message_computer = MessageComputer() | ||
signature = account.sign_message(message_computer.compute_bytes_for_signing(message)) | ||
|
||
access_token = client.get_token( | ||
address=account.address.to_bech32(), | ||
token=init_token, | ||
signature=signature | ||
) | ||
|
||
logger.info(f"Requesting funds for address: {account.address.to_bech32()}") | ||
call_web_Wallet_faucet(wallet_url=wallet, access_token=access_token) | ||
|
||
|
||
def call_web_Wallet_faucet(wallet_url: str, access_token: str): | ||
faucet_url = f"{wallet_url}/faucet?accessToken={access_token}" | ||
webbrowser.open_new_tab(faucet_url) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. i'm thinking of the main benefits of having this command from cli, since we still have to check in the browser There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we've had people asking about it and i think it's a little bit easier to use the cli instead of doing it manually even though you have to pass the recaptcha and then press the request button. This is just an initial implementation/poc. We were thinking about doing it another way, so the user does not have to do anything else but type the command but we have not yet found a non-exploitable way to do it and we'll also need some help from the colleagues working on the api. |
||
|
||
|
||
def get_wallet_and_api_urls(args: Any) -> Tuple[str, str]: | ||
chain: str = args.chain | ||
|
||
if chain.upper() == "D": | ||
return WebWalletUrls.DEVNET.value, ApiUrls.DEVNET.value | ||
|
||
if chain.upper() == "T": | ||
return WebWalletUrls.TESTNET.value, ApiUrls.TESTNET.value | ||
|
||
raise BadUserInput("Invalid chain id. Choose between 'D' for devnet and 'T' for testnet.") |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
import base64 | ||
import json | ||
from typing import Any, Dict, Optional | ||
|
||
import requests | ||
|
||
from multiversx_sdk_cli.errors import NativeAuthClientError | ||
|
||
|
||
class NativeAuthClientConfig: | ||
def __init__( | ||
self, | ||
origin: str = '', | ||
api_url: str = "https://api.multiversx.com", | ||
expiry_seconds: int = 60 * 60 * 24, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. maybe set constants for these default values? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. made some constants for that values There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. here I was referring for these 2 variables: default api url and expiry time in seconds; i think it can be only one var for expiry_seconds There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. indeed, makes sense. done! |
||
block_hash_shard: Optional[int] = None, | ||
gateway_url: Optional[str] = None, | ||
extra_request_headers: Optional[Dict[str, str]] = None | ||
) -> None: | ||
self.origin = origin | ||
self.api_url = api_url | ||
self.expiry_seconds = expiry_seconds | ||
self.block_hash_shard = block_hash_shard | ||
self.gateway_url = gateway_url | ||
self.extra_request_headers = extra_request_headers | ||
|
||
|
||
class NativeAuthClient: | ||
def __init__(self, config: NativeAuthClientConfig = NativeAuthClientConfig()) -> None: | ||
self.config = config | ||
|
||
def get_token(self, address: str, token: str, signature: str) -> str: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Functions can be re-ordered to match the usual flow. E.g. first "initialize", then ... |
||
encoded_address = self.encode_value(address) | ||
encoded_token = self.encode_value(token) | ||
|
||
return f"{encoded_address}.{encoded_token}.{signature}" | ||
|
||
def initialize(self, extra_info: Dict[Any, Any] = {}) -> str: | ||
block_hash = self.get_current_block_hash() | ||
encoded_extra_info = self.encode_value(json.dumps(extra_info)) | ||
encoded_origin = self.encode_value(self.config.origin) | ||
|
||
return f"{encoded_origin}.{block_hash}.{self.config.expiry_seconds}.{encoded_extra_info}" | ||
|
||
def get_current_block_hash(self) -> str: | ||
if self.config.gateway_url: | ||
return self._get_current_block_hash_using_gateway() | ||
return self._get_current_block_hash_using_api() | ||
|
||
def _get_current_block_hash_using_gateway(self) -> str: | ||
round = self._get_current_round() | ||
url = f"{self.config.gateway_url}/blocks/by-round/{round}" | ||
response = self._execute_request(url) | ||
blocks = response["data"]["blocks"] | ||
block = [b for b in blocks if b["shard"] == self.config.block_hash_shard][0] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A bit fragile - it's possible to have a round where not all shards propose a block (missed block). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. However, in the context of mxpy, we don't provide the shard. |
||
return block["hash"] | ||
Check failure on line 56 in multiversx_sdk_cli/native_auth_client.py GitHub Actions / runner / mypy
|
||
|
||
def _get_current_round(self) -> int: | ||
if self.config.gateway_url is None: | ||
raise NativeAuthClientError("Gateway URL not set") | ||
|
||
if self.config.block_hash_shard is None: | ||
raise NativeAuthClientError("Blockhash shard not set") | ||
|
||
url = f"{self.config.gateway_url}/network/status/{self.config.block_hash_shard}" | ||
response = self._execute_request(url) | ||
status = response["data"]["status"] | ||
|
||
return status["erd_current_round"] | ||
Check failure on line 69 in multiversx_sdk_cli/native_auth_client.py GitHub Actions / runner / mypy
|
||
|
||
def _get_current_block_hash_using_api(self) -> str: | ||
try: | ||
url = f"{self.config.api_url}/blocks/latest?ttl={self.config.expiry_seconds}&fields=hash" | ||
response = self._execute_request(url) | ||
if response["hash"]: | ||
return response["hash"] | ||
except Exception: | ||
pass | ||
|
||
return self._get_current_block_hash_using_api_fallback() | ||
|
||
def _get_current_block_hash_using_api_fallback(self) -> str: | ||
url = f"{self.config.api_url}/blocks?size=1&fields=hash" | ||
|
||
if self.config.block_hash_shard: | ||
url += f"&shard={self.config.block_hash_shard}" | ||
|
||
response = self._execute_request(url) | ||
return response[0]["hash"] | ||
|
||
def encode_value(self, string: str) -> str: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does this help? https://docs.python.org/3/library/base64.html#base64.urlsafe_b64encode
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Might help, but indeed |
||
encoded = base64.b64encode(string.encode('utf-8')).decode('utf-8') | ||
return self.escape(encoded) | ||
|
||
def escape(self, string: str) -> str: | ||
return string.replace("+", "-").replace("/", "_").replace("=", "") | ||
|
||
def _execute_request(self, url: str) -> Any: | ||
response = requests.get(url=url, headers=self.config.extra_request_headers) | ||
response.raise_for_status() | ||
return response.json() |
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.
what is the usage of this docker image?
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.
it was committed by accident. removed!