def test_interactive_withdraw_get_no_content_tx_complete( mock_content_for_transaction, mock_form_for_transaction, client ): usd = Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, distribution_seed=Keypair.random().secret, ) withdraw = Transaction.objects.create( asset=usd, kind=Transaction.KIND.withdrawal, status=Transaction.STATUS.completed ) mock_form_for_transaction.return_value = None mock_content_for_transaction.return_value = None payload = interactive_jwt_payload(withdraw, "withdraw") token = jwt.encode(payload, settings.SERVER_JWT_KEY, algorithm="HS256").decode( "ascii" ) response = client.get( f"{WEBAPP_PATH}" f"?token={token}" f"&transaction_id={withdraw.id}" f"&asset_code={withdraw.asset.code}" ) assert response.status_code == 422 assert client.session["authenticated"] is True assert ( "The anchor did not provide content, is the interactive flow already complete?" in str(response.content) )
def test_interactive_withdraw_bad_post_data(client): usd = Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, distribution_seed=Keypair.random().secret, withdrawal_max_amount=10000, ) withdraw = Transaction.objects.create( asset=usd, kind=Transaction.KIND.withdrawal, protocol=Transaction.PROTOCOL.sep24, ) payload = interactive_jwt_payload(withdraw, "withdraw") token = jwt.encode(payload, settings.SERVER_JWT_KEY, algorithm="HS256").decode("ascii") response = client.get(f"{WEBAPP_PATH}" f"?token={token}" f"&transaction_id={withdraw.id}" f"&asset_code={withdraw.asset.code}") assert response.status_code == 200 assert client.session["authenticated"] is True response = client.post( f"{WEBAPP_PATH}/submit" f"?transaction_id={withdraw.id}" f"&asset_code={withdraw.asset.code}", {"amount": 20000}, ) assert response.status_code == 400
def test_withdraw_invalid_operation(client): """`GET /withdraw` fails with an invalid asset argument.""" eth = Asset.objects.create( code="ETH", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=False, distribution_seed=Keypair.random().secret, ) response = client.post(WITHDRAW_PATH, {"asset_code": eth.code}, follow=True) content = response.json() assert response.status_code == 400 assert content == {"error": "invalid operation for asset ETH"}
def test_withdraw_invalid_amount(client): usd = Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, distribution_seed=Keypair.random().secret, withdrawal_max_amount=1000, ) response = client.post( WITHDRAW_PATH, {"asset_code": usd.code, "amount": 10000}, follow=True ) assert response.status_code == 400 assert response.json()["error"] == "invalid 'amount'"
def test_withdraw_interactive_no_asset(client): """ `GET /transactions/withdraw/webapp` fails with no asset_code. """ Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, distribution_seed=Keypair.random().secret, ) response = client.get(f"{WEBAPP_PATH}?transaction_id=2", follow=True) assert response.status_code == 400 assert "asset_code" in response.content.decode()
def test_interactive_withdraw_pending_anchor(mock_after_form_validation, client): usd = Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, distribution_seed=Keypair.random().secret, ) withdraw = Transaction.objects.create(asset=usd, kind=Transaction.KIND.withdrawal, protocol=Transaction.PROTOCOL.sep24) payload = interactive_jwt_payload(withdraw, "withdraw") token = jwt.encode(payload, settings.SERVER_JWT_KEY, algorithm="HS256").decode("ascii") response = client.get(f"{WEBAPP_PATH}" f"?token={token}" f"&transaction_id={withdraw.id}" f"&asset_code={withdraw.asset.code}") assert response.status_code == 200 assert client.session["authenticated"] is True response = client.get(f"{WEBAPP_PATH}" f"?token={token}" f"&transaction_id={withdraw.id}" f"&asset_code={withdraw.asset.code}") assert response.status_code == 403 assert "Unexpected one-time auth token" in str(response.content) def mark_as_pending_anchor(_, transaction): transaction.status = Transaction.STATUS.pending_anchor transaction.save() mock_after_form_validation.side_effect = mark_as_pending_anchor response = client.post( f"{WEBAPP_PATH}/submit" f"?transaction_id={withdraw.id}" f"&asset_code={withdraw.asset.code}", {"amount": 200.0}, ) assert response.status_code == 302 assert client.session["authenticated"] is False withdraw.refresh_from_db() assert withdraw.status == Transaction.STATUS.pending_anchor
def test_process_response_strict_send_success(client): """ Tests successful processing of the SUCCESS_PAYMENT_TRANSACTION_JSON """ asset = Asset.objects.create( code="TEST", issuer=TEST_ASSET_ISSUER_PUBLIC_KEY, distribution_seed=TEST_ASSET_DISTRIBUTION_SEED, ) transaction = Transaction.objects.create( asset=asset, stellar_account=Keypair.random().public_key, amount_in=1001, kind=Transaction.KIND.send, status=Transaction.STATUS.pending_sender, memo=SUCCESS_STRICT_SEND_PAYMENT["memo"], protocol=Transaction.PROTOCOL.sep31, receiving_anchor_account=TEST_ASSET_DISTRIBUTION_PUBLIC_KEY, ) json = deepcopy(SUCCESS_STRICT_SEND_PAYMENT) Command.process_response(json, TEST_ASSET_DISTRIBUTION_PUBLIC_KEY) transaction.refresh_from_db() assert transaction.from_address assert transaction.stellar_transaction_id assert transaction.paging_token assert transaction.status == Transaction.STATUS.pending_receiver assert transaction.amount_in == 1001
def test_interactive_withdraw_bad_issuer(client): usd = Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, distribution_seed=Keypair.random().secret, ) withdraw = Transaction.objects.create(asset=usd) payload = interactive_jwt_payload(withdraw, "withdraw") payload["iss"] = "bad iss" token = jwt.encode(payload, settings.SERVER_JWT_KEY, algorithm="HS256").decode() response = client.get(f"{WEBAPP_PATH}?token={token}") assert "Invalid token issuer" in str(response.content) assert response.status_code == 403
def create_channel_account(self, transaction: Transaction): kp = Keypair.random() settings.HORIZON_SERVER._client.get( f"https://friendbot.stellar.org/?addr={kp.public_key}" ) transaction.channel_seed = kp.secret transaction.save()
def main(): kp = Keypair.random() print("Secret: {}".format(kp.secret)) print("Public Key: {}".format(kp.public_key)) print("") pass
def test_withdraw_client_domain_saved(client): kp = Keypair.random() usd = Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, distribution_seed=Keypair.random().secret, ) response = client.post( WITHDRAW_PATH, {"asset_code": usd.code, "account": kp.public_key}, ) content = response.json() assert response.status_code == 200, json.dumps(content, indent=2) assert Transaction.objects.count() == 1 transaction = Transaction.objects.first() assert transaction.client_domain == "test.com"
def users_info(users): data = [] for user in users: pair = Keypair.random() data.append({ 'name': user, 'secret': pair.secret, 'publicKey': pair.public_key }) return data
def test_interactive_withdraw_no_transaction(client): usd = Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, distribution_seed=Keypair.random().secret, ) withdraw = Transaction.objects.create(asset=usd, kind=Transaction.KIND.withdrawal) payload = interactive_jwt_payload(withdraw, "withdraw") withdraw.delete() # remove from database token = jwt.encode(payload, settings.SERVER_JWT_KEY, algorithm="HS256").decode( "ascii" ) response = client.get(f"{WEBAPP_PATH}?token={token}") assert "Transaction for account not found" in str(response.content) assert response.status_code == 403
def test_withdraw_no_distribution_account(client): usd = Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, ) response = client.post( WITHDRAW_PATH, {"asset_code": usd.code, "amount": 10000}, follow=True ) assert response.status_code == 400 assert response.json()["error"] == f"invalid operation for asset {usd.code}"
def test_withdraw_interactive_complete(mock_interactive_url, client): usd = Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, distribution_seed=Keypair.random().secret, ) withdraw = Transaction.objects.create( asset=usd, status=Transaction.STATUS.incomplete, kind=Transaction.KIND.withdrawal, ) payload = interactive_jwt_payload(withdraw, "withdraw") token = jwt.encode(payload, settings.SERVER_JWT_KEY, algorithm="HS256").decode( "ascii" ) mock_interactive_url.return_value = "https://test.com/customFlow" response = client.get( f"{WEBAPP_PATH}" f"?token={token}" f"&transaction_id={withdraw.id}" f"&asset_code={withdraw.asset.code}" ) assert response.status_code == 302 mock_interactive_url.assert_called_once() assert client.session["authenticated"] is True response = client.get( WITHDRAW_PATH + "/complete", {"transaction_id": withdraw.id, "callback": "test.com/callback"}, ) assert response.status_code == 302 redirect_to_url = response.get("Location") assert "more_info" in redirect_to_url assert "callback=test.com%2Fcallback" in redirect_to_url withdraw.refresh_from_db() assert withdraw.status == Transaction.STATUS.pending_user_transfer_start
def test_amount_too_large(client, usd_asset_factory): asset = usd_asset_factory(protocols=[Transaction.PROTOCOL.sep6]) response = client.get( WITHDRAW_PATH, { "asset_code": asset.code, "account": Keypair.random().public_key, "type": "good type", "dest": "test bank account number", "amount": asset.deposit_max_amount + 1, }, ) assert response.status_code == 400 assert "amount" in json.loads(response.content)["error"]
def test_withdraw_success(client): """`GET /withdraw` succeeds with no optional arguments.""" usd = Asset.objects.create( code="USD", issuer=Keypair.random().public_key, sep24_enabled=True, withdrawal_enabled=True, distribution_seed=Keypair.random().secret, ) response = client.post(WITHDRAW_PATH, {"asset_code": usd.code}, follow=True) content = response.json() assert content["type"] == "interactive_customer_info_needed" assert content.get("id") t = Transaction.objects.filter(id=content.get("id")).first() assert t assert t.stellar_account == "test source address" assert t.asset.code == usd.code assert t.protocol == Transaction.PROTOCOL.sep24 assert t.kind == Transaction.KIND.withdrawal assert t.status == Transaction.STATUS.incomplete assert t.receiving_anchor_account == usd.distribution_account assert t.memo_type == Transaction.MEMO_TYPES.hash
def test_good_amount(mock_deposit, client, usd_asset_factory): asset = usd_asset_factory(protocols=[Transaction.PROTOCOL.sep6]) mock_deposit.process_sep6_request = Mock(return_value={"how": "test"}) response = client.get( WITHDRAW_PATH, { "asset_code": asset.code, "account": Keypair.random().public_key, "type": "good type", "dest": "test bank account number", "amount": asset.deposit_max_amount - 1, }, ) assert response.status_code == 200 args, _ = mock_deposit.process_sep6_request.call_args[0] assert args.get("amount") == asset.deposit_max_amount - 1
def create_wallet(): print('creating keys...') kp = Keypair.random() if CONF['network'] == 'PUBLIC': print_formatted_text( HTML( '<ansiyellow>WARNING YOU NEED TO FUND AND BACKUP YOUR PRIVATE KEY!</ansiyellow>' )) else: print('.. on testnet... hit f after this to fund') print( 'Public key this is where people send funds to. You need to fund with some lumens to get started\n' ) print_formatted_text(HTML('<ansired>' + kp.public_key + '</ansired>')) print('\nPrivate key please ensure you store securely\n') print_formatted_text(HTML('<ansiyellow>' + kp.secret + '</ansiyellow>')) sm = StellarMnemonic(CONF['language'].lower()) secret_phrase = sm.generate() print( '\n if you loose your key you can recreate it with this special passphrase:\n' ) print(secret_phrase) print('') print('> if you want to store this hit y') text = session.prompt(u'> y') if text.lower() == 'n': return # todoo update config if CONF['public_key'] != '': print('only one public key is currently supported') return CONF['public_key'] = kp.public_key CONF['private_key'] = kp.secret with open(PTC, 'w') as fp: fp.write(toml.dumps(CONF)) if CONF['network'] != 'TESTNET': print( 'configuration saved - please remember to fund by sending a couple of lumens' )
def test_bad_auth_delete(client): response = client.delete("/".join([endpoint, Keypair.random().public_key])) assert response.status_code == 404
def test_create_random(self): kp = Keypair.random() public_key = kp.public_key secret = kp.secret assert StrKey.is_valid_ed25519_public_key(public_key) assert StrKey.is_valid_ed25519_secret_seed(secret)
def test_not_isinstance_equal(self): assert Keypair.random() != "bad type"
from stellar_sdk.keypair import Keypair # create a random keypair print("create a random keypair") kp = Keypair.random() print("Secret: {}".format(kp.secret)) print("Public Key: {}".format(kp.public_key)) print("") # create a keypair from secret print("create a keypair from secret") secret = "SBRR6ZPBHHTDXYSFRZR2QZCGDZURNE5ON4M4F3HQA42G3Z62SFCR7EEJ" kp = Keypair.from_secret(secret) print("Secret: {}".format(kp.secret)) print("Public Key: {}".format(kp.public_key)) print("") # create a keypair from public key print("create a keypair from public key") public_key = "GDCZ6JDZMWYORTIHEO2E4ZXKBQ2TLXNRQJPJH5RCFN7Q7I24G4RGLXP6" kp = Keypair.from_public_key(public_key) print("Public Key: {}".format(kp.public_key))
from stellar_sdk.keypair import Keypair import requests from stellar_sdk.server import Server import json server = Server("https://horizon-testnet.stellar.org") accounts = {} for i in range(3): # Create a Keypair pair = Keypair.random() print(f"Secret: {pair.secret}") print(f"Public Key: {pair.public_key}") # Create Account public_key = pair.public_key response = requests.get(f"https://friendbot.stellar.org?addr={public_key}") if response.status_code == 200: print(f"SUCCESS! You have a new account :)\n{response.text}") # Get Account details account = server.accounts().account_id(public_key).call() for balance in account['balances']: print( f"Type: {balance['asset_type']}, Balance: {balance['balance']}" ) # Save Account Keys accounts[i] = {"sk": pair.secret, "pk": pair.public_key} else:
""" import json import pytest import datetime from typing import Optional, List from unittest.mock import Mock from polaris.models import Asset, Transaction from stellar_sdk.keypair import Keypair STELLAR_ACCOUNT_1 = "GAIRMDK7VDAXKXCX54UQ7WQUXZVITPBBYH33ADXQIADMDTDVJMQGBQ6V" STELLAR_ACCOUNT_1_SEED = "SBB57BRFU7OFBVGUNJH4PMTQR72VCGKKFXBRQJJX7CHRSTZATAB5645L" STELLAR_ACCOUNT_2 = "GAWGLF7Y6WFNPMFLIZ7AZU7TCHRRMTVKSB64XUSLJUGMXS3KFCOZXJWC" STELLAR_ACCOUNT_2_SEED = "SAANDCFGMTWUQX27URREU47QL2HSJRCTB6YXZIOBHZJCAUBBEFJTGASY" USD_DISTRIBUTION_SEED = Keypair.random().secret USD_ISSUER_ACCOUNT = Keypair.random().public_key ETH_DISTRIBUTION_SEED = Keypair.random().secret ETH_ISSUER_ACCOUNT = Keypair.random().public_key @pytest.fixture(scope="session", name="usd_asset_factory") def fixture_usd_asset_factory(): """Factory method fixture to populate the test database with a USD asset.""" def create_usd_asset(protocols: Optional[List[str]] = None): """ Creates a test USD asset that composes the example /info response, according to https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0024.md#response-2 """ signer = { "key": Keypair.from_secret(USD_DISTRIBUTION_SEED).public_key,