Ejemplo n.º 1
0
def check_users():
    """
    Check if accounts exist in stellar and create them if not.
    Check if users exist in our system and create them if not.
    """
    for user_seed, call_sign in zip(
            (TEST_LAUNCHER_SEED, TEST_COURIER_SEED, TEST_RECIPIENT_SEED),
            ('test_launcher', 'test_courier', 'test_recipient')):
        user_keypair = paket_stellar.stellar_base.Keypair.from_seed(user_seed)
        user_pubkey = user_keypair.address().decode()
        user_seed = user_keypair.seed().decode()
        try:
            paket_stellar.get_bul_account(user_pubkey)
        except paket_stellar.StellarAccountNotExists:
            LOGGER.info("creating account %s", user_pubkey)
            create_new_account(db.FUNDER_SEED, user_pubkey, XLM_START_BALANCE)
            LOGGER.info("adding trust to %s", user_pubkey)
            add_trust(user_pubkey, user_seed)
            paket_stellar.fund_from_issuer(user_pubkey, BUL_START_BALANCE)
        except paket_stellar.TrustError:
            LOGGER.info("adding trust to %s", user_pubkey)
            add_trust(user_pubkey, user_seed)
            paket_stellar.fund_from_issuer(user_pubkey, BUL_START_BALANCE)

        try:
            db.create_user(user_pubkey, call_sign)
        except db.UserAlreadyExists as exc:
            LOGGER.info(str(exc))
Ejemplo n.º 2
0
 def test_accept_untrusted(self):
     """Test for getting bul account that actualy may not have bul balance."""
     account = paket_stellar.get_bul_account(self.regular_account_pubkey,
                                             accept_untrusted=True)
     self.assertNotIn('bul_balance', account)
     with self.assertRaises(paket_stellar.TrustError):
         paket_stellar.get_bul_account(self.regular_account_pubkey)
Ejemplo n.º 3
0
def create_and_fund(user_pubkey):
    """Create account and fund it with starting XLM and BUL amounts"""
    try:
        paket_stellar.get_bul_account(user_pubkey, accept_untrusted=True)
    except paket_stellar.StellarAccountNotExists:
        LOGGER.info("stellar account with pubkey %s does not exists and will be created", user_pubkey)
    else:
        LOGGER.info("stellar account with pubkey %s already exists", user_pubkey)
        return

    daily_spent_euro = get_daily_spent_euro()
    if daily_spent_euro >= DAILY_FUND_LIMIT:
        raise FundLimitReached('daily fund limit reached')

    hourly_spent_euro = get_hourly_spent_euro()
    if hourly_spent_euro >= HOURLY_FUND_LIMIT:
        raise FundLimitReached('hourly fund limit reached')

    starting_balance = util.conversion.stroops_to_units(XLM_STARTING_BALANCE)
    funder_pubkey = paket_stellar.stellar_base.Keypair.from_seed(FUNDER_SEED).address().decode()
    builder = paket_stellar.gen_builder(funder_pubkey)
    builder.append_create_account_op(destination=user_pubkey, starting_balance=starting_balance)
    envelope = builder.gen_te().xdr().decode()
    paket_stellar.submit_transaction_envelope(envelope, seed=FUNDER_SEED)
    euro_cents = util.conversion.xlm_to_euro_cents(XLM_STARTING_BALANCE, prices.xlm_price())
    with SQL_CONNECTION() as sql:
        sql.execute("""
            INSERT INTO fundings (user_pubkey, currency, currency_amount, euro_cents)
            VALUES (%s, %s, %s, %s)""", (user_pubkey, 'XLM', XLM_STARTING_BALANCE, euro_cents))
Ejemplo n.º 4
0
def send_requested_xlm(purchase, euro_cents_to_fund, success_purchase_status=db.PURCHASE_FUNDED):
    """Send amount of XLM requested in purchase."""
    fund_amount = db.util.conversion.euro_cents_to_xlm_stroops(
        euro_cents_to_fund, db.prices.xlm_price())
    try:
        paket_stellar.get_bul_account(purchase['user_pubkey'], accept_untrusted=True)
        fund_account(purchase['user_pubkey'], fund_amount, 'XLM')
        LOGGER.info("%s funded with %s XLM", purchase['user_pubkey'], fund_amount)
    except paket_stellar.StellarAccountNotExists:
        LOGGER.info("account %s does not exist and will be created", purchase['user_pubkey'])
        create_new_account(purchase['user_pubkey'], fund_amount)
    db.set_purchase(
        purchase['user_pubkey'], purchase['payment_pubkey'], purchase['payment_currency'],
        euro_cents_to_fund, purchase['requested_currency'], paid=success_purchase_status)
    LOGGER.info("purchase with address %s marked as funded", purchase['payment_pubkey'])
Ejemplo n.º 5
0
def send_requested_bul(purchase, euro_cents_to_fund, success_purchase_status=db.PURCHASE_FUNDED):
    """Send amount of BUL requested in purchase."""
    fund_amount = db.util.conversion.euro_cents_to_bul_stroops(
        euro_cents_to_fund, db.prices.bul_price())
    try:
        account = paket_stellar.get_bul_account(purchase['user_pubkey'])
        if account['bul_balance'] + fund_amount <= account['bul_limit']:
            fund_account(purchase['user_pubkey'], fund_amount, 'BUL')
            LOGGER.info("%s funded with %s BUL", purchase['user_pubkey'], fund_amount)
            db.set_purchase(
                purchase['user_pubkey'], purchase['payment_pubkey'], purchase['payment_currency'],
                euro_cents_to_fund, purchase['requested_currency'], paid=success_purchase_status)
            LOGGER.info("purchase for account %s marked as funded", purchase['user_pubkey'])
        else:
            LOGGER.error("account %s need to set higher limit for BUL."
                         " balance: %s limit: %s amount to fund: %s", purchase['user_pubkey'],
                         account['bul_balance'], account['bul_limit'], fund_amount)
            db.set_purchase(
                purchase['user_pubkey'], purchase['payment_pubkey'], purchase['payment_currency'],
                euro_cents_to_fund, purchase['requested_currency'], paid=db.PURCHASE_FAILED)
            LOGGER.error("purchase with address %s marked as unsuccessful", purchase['payment_pubkey'])
    except (paket_stellar.TrustError, paket_stellar.StellarAccountNotExists) as exc:
        LOGGER.error(str(exc))
        db.set_purchase(
            purchase['user_pubkey'], purchase['payment_pubkey'], purchase['payment_currency'],
            euro_cents_to_fund, purchase['requested_currency'], paid=db.PURCHASE_FAILED)
        LOGGER.error("purchase with address %s marked as unsuccessful", purchase['payment_pubkey'])
Ejemplo n.º 6
0
def bul_account_handler(queried_pubkey):
    """
    Get the details of a Stellar BUL account.
    ---
    :param queried_pubkey:
    :return:
    """
    account = paket_stellar.get_bul_account(queried_pubkey)
    return dict(status=200, account=account)
Ejemplo n.º 7
0
def enrich_package(package, user_role=None, user_pubkey=None, check_solvency=False, check_escrow=False):
    """Add some periferal data to the package object."""
    package['short_package_id'] = get_short_package_id(package['escrow_pubkey'], package['to_location'])
    package['blockchain_url'] = "https://testnet.steexp.com/account/{}#signing".format(package['escrow_pubkey'])
    package['paket_url'] = "https://paket.global/paket/{}".format(package['escrow_pubkey'])
    package['events'] = get_package_events(package['escrow_pubkey'])
    event_types = {event['event_type'] for event in package['events']}
    if package['events']:
        package['custodian_pubkey'] = package['events'][-1]['user_pubkey']
        launch_event = next((event for event in package['events'] if event['event_type'] == events.LAUNCHED), None)
        package['launch_date'] = launch_event['timestamp'] if launch_event is not None else None
    else:
        package['custodian_pubkey'] = None
        package['launch_date'] = None
        LOGGER.warning("eventless package: %s", package)

    extract_xdrs(package)
    set_package_status(package, event_types)
    set_user_role(package, user_role, user_pubkey)

    if check_solvency:
        try:
            launcher_account = paket_stellar.get_bul_account(package['launcher_pubkey'])
        except (paket_stellar.TrustError, paket_stellar.StellarAccountNotExists):
            package['launcher_solvency'] = False
        else:
            package['launcher_solvency'] = launcher_account['bul_balance'] >= package['payment']

    if check_escrow:
        try:
            escrow_account = paket_stellar.get_bul_account(package['escrow_pubkey'])
        except (paket_stellar.TrustError, paket_stellar.StellarAccountNotExists):
            package['payment_deposited'] = package['collateral_deposited'] = package['correctly_deposited'] = False
        else:
            package['payment_deposited'] = escrow_account['bul_balance'] >= package['payment']
            package['collateral_deposited'] = (
                escrow_account['bul_balance'] >= package['payment'] + package['collateral'])
            package['correctly_deposited'] = (
                escrow_account['bul_balance'] == package['payment'] + package['collateral'])

    return package
Ejemplo n.º 8
0
def setup_account(seed, new_account=False, add_trust=False):
    """Generate new keypair, and optionally create account and set trust."""
    keypair = paket_stellar.get_keypair(seed=seed)
    pubkey = keypair.address().decode()
    seed = keypair.seed().decode()

    if new_account:
        try:
            account = paket_stellar.get_bul_account(pubkey,
                                                    accept_untrusted=True)
        except paket_stellar.StellarAccountNotExists:
            LOGGER.info("%s not exist and will be created", pubkey)
            create_account_transaction = paket_stellar.prepare_create_account(
                paket_stellar.ISSUER, pubkey, START_ACCOUNT_BALANCE)
            paket_stellar.submit_transaction_envelope(
                create_account_transaction, paket_stellar.ISSUER_SEED)
        else:
            LOGGER.info("%s already exist", pubkey)
            if account['xlm_balance'] < MINIMUM_ACCOUNT_BALANCE:
                LOGGER.info("%s has %s XLM on balance and need to be funded",
                            pubkey, account['xlm_balance'])
                send_xlm_transaction = paket_stellar.prepare_send_lumens(
                    paket_stellar.ISSUER, pubkey, START_ACCOUNT_BALANCE)
                paket_stellar.submit_transaction_envelope(
                    send_xlm_transaction, paket_stellar.ISSUER_SEED)
            else:
                LOGGER.info("%s has %s XLM on balance", pubkey,
                            account['xlm_balance'])

    if new_account and add_trust:
        try:
            paket_stellar.get_bul_account(pubkey)
        except paket_stellar.TrustError:
            LOGGER.info("BUL trustline will be added to %s", pubkey)
            trust_transaction = paket_stellar.prepare_trust(pubkey)
            paket_stellar.submit_transaction_envelope(trust_transaction, seed)
        else:
            LOGGER.info("%s already trust BUL", pubkey)

    return pubkey, seed
Ejemplo n.º 9
0
    def test_ent_to_end(self):
        """End-to-end test."""
        # prepare escrow properties
        payment = 10000000
        collateral = 20000000
        relay_payment = 5000000
        relay_collateral = 10000000
        deadline = int(time.time()) + 60 * 60 * 24 * 10

        # prepare participants accounts
        # launcher_account, first_courier_account, second_courier_account, recipient_account = (
        #     self.create_and_setup_new_account() for _ in range(4))
        # escrow_account = self.create_and_setup_new_account(buls_amount=payment)
        launcher_account = (
            'GBI27N2K5CA46RVPPO2UFQABNQIOFVJGJPXJWNROS2KR6J5BP2H7TX4M',
            'SAAR6N7SLB3OECH7OBEGNPXADX35GV7R7EVC6P67EEXXWKIZYC346BWV')
        first_courier_account = (
            'GDCFBUSFW5GDHO6TQW65ACW3JRDFTBK2I5YTWJRRJHIFIPO5FIQWLOLA',
            'SDBE3HXYKW2WMQWKZOCNRD4EICC4VMBOTM7BCSROQAA7TGVWZZGCO7LV')
        second_courier_account = (
            'GB7VMXUABOSAG7TXDPVR2MMHEBKEXBNWA2EHP5SUHG5HU66PDW2F77W6',
            'SAEYMJX77WYIHT2TSONGMTUTTSR7CR2GOMPZQKNRJA5Z6JZ63REZ5KU2')
        recipient_account = (
            'GBR4SCRHZUPYYFIC7HBJKMEIESSZRGSTYMZSLNSG2IH2B6Z766QDTXJC',
            'SB7R6P6NMJS3S6PA6WKFWQMD3BU4H2N7ZT4OORVQC5PSHLBBEG2OU7TZ')

        # prepare courier's additional account
        keypair = paket_stellar.stellar_base.Keypair.random()
        fcourier_additional_account = keypair.address().decode(), keypair.seed(
        ).decode()
        prepare_account = paket_stellar.prepare_create_account(
            first_courier_account[0], fcourier_additional_account[0])
        paket_stellar.submit_transaction_envelope(
            prepare_account, seed=first_courier_account[1])
        prepare_trust = paket_stellar.prepare_trust(
            fcourier_additional_account[0])
        paket_stellar.submit_transaction_envelope(
            prepare_trust, seed=fcourier_additional_account[1])
        LOGGER.info('additional account prepared')

        # get initial balances
        launcher_initial_balance = paket_stellar.get_bul_account(
            launcher_account[0])['bul_balance']
        LOGGER.info("launcher initial balance: %s BUL stroops",
                    launcher_initial_balance)
        first_courier_initial_balance = paket_stellar.get_bul_account(
            first_courier_account[0])['bul_balance']
        LOGGER.info("first courier initial balance: %s BUL stroops",
                    first_courier_initial_balance)
        fcourier_additional_initial_balance = paket_stellar.get_bul_account(
            fcourier_additional_account[0])['bul_balance']
        LOGGER.info(
            "first courier additional account initial balance: %s BUL stroops",
            fcourier_additional_initial_balance)
        second_courier_initial_balance = paket_stellar.get_bul_account(
            second_courier_account[0])['bul_balance']
        LOGGER.info("second courier initial balance: %s BUL stroops",
                    second_courier_initial_balance)

        # prepare escrow account
        # escrow_account = self.create_and_setup_new_account(buls_amount=payment+collateral)
        escrow_keypair = paket_stellar.stellar_base.Keypair.random()
        escrow_account = escrow_keypair.address().decode(
        ), escrow_keypair.seed().decode()
        prepare_escrow_account = paket_stellar.prepare_create_account(
            launcher_account[0], escrow_account[0])
        paket_stellar.submit_transaction_envelope(prepare_escrow_account,
                                                  seed=launcher_account[1])
        prepare_trust = paket_stellar.prepare_trust(escrow_account[0])
        paket_stellar.submit_transaction_envelope(prepare_trust,
                                                  seed=escrow_account[1])
        LOGGER.info('escrow account prepared')

        # prepare escrow transactions
        escrow_transactions = paket_stellar.prepare_escrow(
            escrow_account[0], launcher_account[0],
            fcourier_additional_account[0], recipient_account[0], payment,
            collateral, deadline)
        LOGGER.info('escrow transactions prepared')
        paket_stellar.submit_transaction_envelope(
            escrow_transactions['set_options_transaction'],
            seed=escrow_account[1])
        LOGGER.info('escrow set_options transaction sent')

        # send payment and collateral to escrow
        prepare_send_buls = paket_stellar.prepare_send_buls(
            launcher_account[0], escrow_account[0], payment)
        paket_stellar.submit_transaction_envelope(prepare_send_buls,
                                                  seed=launcher_account[1])
        LOGGER.info('payment sent to escrow account')
        prepare_send_buls = paket_stellar.prepare_send_buls(
            first_courier_account[0], escrow_account[0], collateral)
        paket_stellar.submit_transaction_envelope(
            prepare_send_buls, seed=first_courier_account[1])
        LOGGER.info('collateral sent to escrow account')

        # prepare relay transactions
        relay_transactions = paket_stellar.prepare_relay(
            fcourier_additional_account[0], first_courier_account[0],
            second_courier_account[0],
            payment + collateral - relay_payment - relay_collateral,
            relay_payment + relay_collateral, deadline)
        LOGGER.info('relay transactions prepared')
        paket_stellar.submit_transaction_envelope(
            relay_transactions['set_options_transaction'],
            seed=fcourier_additional_account[1])

        # second courier send collateral directly to first courier account
        prepare_send = paket_stellar.prepare_send_buls(
            second_courier_account[0], first_courier_account[0],
            relay_collateral)
        paket_stellar.submit_transaction_envelope(
            prepare_send, seed=second_courier_account[1])

        # accept package by recipient
        paket_stellar.submit_transaction_envelope(
            escrow_transactions['payment_transaction'],
            seed=recipient_account[1])
        LOGGER.info('package accepted by courier')
        paket_stellar.submit_transaction_envelope(
            escrow_transactions['merge_transaction'])
        LOGGER.info('escrow merge transaction sent')

        # submit relay transactions
        paket_stellar.submit_transaction_envelope(
            relay_transactions['relay_transaction'])
        paket_stellar.submit_transaction_envelope(
            relay_transactions['sequence_merge_transaction'])

        # get result balances
        launcher_result_balance = paket_stellar.get_bul_account(
            launcher_account[0])['bul_balance']
        first_courier_result_balance = paket_stellar.get_bul_account(
            first_courier_account[0])['bul_balance']
        second_courier_result_balance = paket_stellar.get_bul_account(
            second_courier_account[0])['bul_balance']

        # check account balances
        self.assertEqual(
            launcher_result_balance, launcher_initial_balance - payment,
            "expected {} BUL stroops for launcher, {} got instead".format(
                launcher_initial_balance - payment, launcher_result_balance))
        self.assertEqual(
            first_courier_result_balance,
            first_courier_initial_balance + payment - relay_payment,
            "expected {} BUL stroops for first courier, {} got instead".format(
                first_courier_initial_balance + payment - relay_payment,
                first_courier_result_balance))
        self.assertEqual(
            second_courier_result_balance,
            second_courier_initial_balance + relay_payment,
            "expected {} BUL stroops for second courier, {} got instead".
            format(second_courier_initial_balance + relay_payment,
                   second_courier_result_balance))
Ejemplo n.º 10
0
 def test_get_bul_account(self):
     """Test for getting bul account."""
     account = paket_stellar.get_bul_account(pubkey=self.bul_account_pubkey)
     self.assertIn('bul_balance', account)