예제 #1
0
def forms(form_name):
    session = Session()
    wac = WAC(session, request.args)
    '''
        account = session.query(Account).filter_by(address=wac.address).first()
    if account is None:
#        account = Account(address=wac['address'], public_key=wac['public_key'], deposit_address=get_new_deposit_account())
        import random
        account = Account(address=wac.address, public_key=wac.public_key, deposit_address=str(random.random()))
        session.add(account)
        session.commit()
        logging.debug("Registering new account: " + str(account))
    '''

    if wac.asset_id not in currencies:
        logger.error("Unknown currency: %s" % wac.asset_id)
        return "Unknown currency: %s" % wac.asset_id

    plugin_name = currencies[wac.asset_id]

    plugin_forms = importlib.import_module("plugins.%s.forms" % plugin_name)
    if form_name in plugin_forms.forms:
        result = plugin_forms.forms[form_name](session, wac)
        session.commit()
        return result

    return "Form does not exist", 404
예제 #2
0
 def setUp(self):
     self.engine = create_engine('sqlite:///:memory:')
     Session = sessionmaker(autocommit=False,
                            autoflush=False,
                            bind=self.engine)
     self.session = Session()
     Base.metadata.create_all(self.engine)
예제 #3
0
 def __init__(self, session: Session, request_args):
     if 'Session-Id' in request_args:
         # TODO: Respect session's timeout
         user_session = session.query(UserSession).filter_by(
             session_id=request_args['Session-Id']).first()
         self.account = session.query(Account).filter_by(
             address=user_session.address).first()
         self.public_key = self.account.public_key
         self.address = self.account.address
         self.asset_id = user_session.currency
     else:
         self.asset_id = request_args['Asset-Id']
         self.auth_hash = b58decode(request_args['AuthHash'])
         self.auth_nonce = b58decode(request_args['AuthNonce'])
         self.public_key = bytes(request_args['Public-Key'], 'latin-1')
         self.address = request_args['Address']
         if self.address != public_key_to_account(
                 request_args['Public-Key']):
             raise PermissionError("Public key is and address differ")
         self.account = Account.get_or_create(session, self.address,
                                              self.public_key)
         if not self._is_auth_hash_valid(self.public_key, self.auth_hash,
                                         self.auth_nonce, self.asset_id):
             raise PermissionError("WAC header is invalid")
         user_session = UserSession(self.address, self.asset_id)
         session.add(user_session)
     self.session_id = user_session.session_id
예제 #4
0
 def _scan_block(self, session: Session, block_number: int):
     transactions = get_transactions_for_block(block_number)
     for tx in transactions:
         try:
             if tx["type"] == 4:  # Asset transfer transaction
                 account = session.query(Account).filter_by(
                     deposit_address=tx["recipient"]).first()
                 if account and session.query(BlockchainTransaction).get(
                         tx["id"]) is None:
                     attachment = ''.join(
                         chr(x) for x in b58decode(tx["attachment"]))
                     logging.info(
                         "\t❤❤❤❤ A new withdrawal transaction received. - %s"
                         % tx["id"])
                     logging.info("\tFrom %s" % account.address)
                     logging.info("\tTo %s" % tx["recipient"])
                     logging.info("\tAsset %s" % tx["assetId"])
                     logging.info("\tAmount %d" % tx["amount"])
                     logging.info("\tAttachment %s" % attachment)
                     # TODO: Check if currency is defined
                     blockchain_transaction = BlockchainTransaction(
                         tx["id"], account.address, tx["type"],
                         tx["timestamp"], attachment, tx["assetId"],
                         tx["amount"])
                     session.add(blockchain_transaction)
         except KeyError:
             pass  # Unknown transaction type
 def send_money(self, session: Session, account: str, amount: int):
     acc = session.query(BankSimBalances).filter_by(
         bank_account=account).first()
     if acc is None:
         acc = BankSimBalances(account, amount)
         session.add(acc)
     else:
         acc.balance += amount
예제 #6
0
 def _scan_blockchain(self):
     session = Session()
     # TODO: Handle forks properly.
     while self.current_block <= get_current_height(
     ) - required_confirmations:
         logging.info("Scanning block %d" % self.current_block)
         self._scan_block(session, self.current_block)
         self.current_block += 1
     session.commit()
예제 #7
0
class WACTest(TestCase):
    def setUp(self):
        self.engine = create_engine('sqlite:///:memory:')
        Session = sessionmaker(autocommit=False,
                               autoflush=False,
                               bind=self.engine)
        self.session = Session()
        Base.metadata.create_all(self.engine)

    def tearDown(self):
        Base.metadata.drop_all(self.engine)

    def test_wac_incorrect_1(self):
        args = dict()
        args['Public-Key'] = "GKjxK8Q2a88Qes5WDmfmgA5fYXjVfFnyGTfXCzrGsmPP"
        args['Asset-Id'] = "3A2FXAmdSKVGxikERJvC13FG7ADf2sqb8kmzYokUzxm9"
        args['Address'] = "3N4sSM2mDoQ86qLD8LHR49hX2VF8SfWrUae"
        args['AuthHash'] = "ERKzMvUJGx36GKXapihPgJeZTPwrYkU2DpeoHF1Sdxwd"
        args['AuthNonce'] = "dRTyHTrvhH8ue89J6SD2gRuE6uPM9nxJDvyahhoZSGQ"
        global gateway_private_key
        gateway_private_key = b'\x88rz\x037{\xfb\xa1\xb3e\\^\xcb\x97\x8d\xa1q\xe0$\xaa\xd7"\xeeI\xff\xf9!Jt~pb'
        with self.assertRaises(PermissionError):
            WAC(self.session, args)

    def test_wac_incorrect_2(self):
        args = dict()
        args['Public-Key'] = "GKjxK8Q2a88Qes5WDmfmgA5fYXjVfFnyGTfXCzrGsmPP"
        args['Asset-Id'] = "3A2FXAmdSKVGxikERJvC13FG7ADf2sqb8kmzYokUzxm9"
        args['Address'] = "3N4sSM2mDoQ86qLD8LHR49hX2VF8SfWrUaf"
        args['AuthHash'] = "ERKzMvUJGx36GKXapihPgJeZTPwrYkU2DpeoHF1Sdxwd"
        args['AuthNonce'] = "dRTyHTrvhH8ue89J6SD2gRuE6uPM9nxJDvyahhoZSGQ"
        global gateway_private_key
        gateway_private_key = b'\x88rz\x037{\xfb\xa1\xb3e\\^\xcb\x97\x8d\xa1q\xe0$\xaa\xd7"\xeeI\xff\xf9!Jt~pa'
        with self.assertRaises(PermissionError):
            WAC(self.session, args)

    def test_wac_correct(self):
        args = dict()
        args['Public-Key'] = "GKjxK8Q2a88Qes5WDmfmgA5fYXjVfFnyGTfXCzrGsmPP"
        args['Asset-Id'] = "3A2FXAmdSKVGxikERJvC13FG7ADf2sqb8kmzYokUzxm9"
        args['Address'] = "3N4sSM2mDoQ86qLD8LHR49hX2VF8SfWrUae"
        args['AuthHash'] = "ERKzMvUJGx36GKXapihPgJeZTPwrYkU2DpeoHF1Sdxwd"
        args['AuthNonce'] = "dRTyHTrvhH8ue89J6SD2gRuE6uPM9nxJDvyahhoZSGQ"
        global gateway_private_key
        gateway_private_key = b'\x88rz\x037{\xfb\xa1\xb3e\\^\xcb\x97\x8d\xa1q\xe0$\xaa\xd7"\xeeI\xff\xf9!Jt~pa'
        wac = WAC(self.session, args)
        self.assertEqual(wac.asset_id, args['Asset-Id'])
        self.assertEqual(wac.address, args['Address'])
        print(wac.session_id)
        self.session.commit()

        args2 = dict()
        args2['Session-Id'] = wac.session_id
        wac2 = WAC(self.session, args2)
def index():
    session = Session()
    if "account" in request.form and "amount" in request.form:
        deposit_iban = request.form["account"]
        amount = int(
            float(request.form["amount"]) *
            (10**list(currencies.values())[0].decimals))

        account = session.query(Account).filter_by(
            deposit_iban=deposit_iban).first()
        if account is None:
            return "There is no account with IBAN %s" % (deposit_iban)

        deposit = Deposit(account.address, list(currencies.keys())[0], amount)
        # We are accepting banking transactions immediately.
        # We are waiting for confirmations only on blockchain transactions.
        deposit.accepted = True
        session.add(deposit)
        session.commit()
        return """Your deposit to %s for %d.%.2d USD was made""" % (
            deposit_iban, amount /
            (10.**list(currencies.values())[0].decimals), amount %
            (10.**list(currencies.values())[0].decimals))
    session.commit()
    msg = """Welcome to the Bank simulator!<br/>Make a deposit:
    <form method='POST' action='/'>
    Account [IBAN]:<input name='account'/><br/>
    Amount [USD]:<input name='amount'/><br/>
    <input type='submit'/></form><br/>
    <b>Account balances:</b><br/>"""

    for balance in session.query(BankSimBalances).all():
        msg += "%s - %d.%.2d<br/>" % (balance.bank_account, balance.balance /
                                      100, balance.balance % 100)

    return msg
예제 #9
0
 def change_job_status(job_id, status):
     """
     改变任务状态
     :param job_id:
     :param status:
     :return:
     """
     all_status = [
         Job.Status.DELETED, Job.Status.STOPPED, Job.Status.RUNNING,
         Job.Status.SUSPENDED
     ]
     if status not in all_status:
         raise ServiceException(ErrorCode.PARAM_ERROR, 'status参数错误')
     session = Session()
     job = JobService.get_job(job_id)
     job.status = status.value
     session.add(job)
     session.commit()
     return job.job_id
예제 #10
0
    def _handle_withdrawals(self):
        session = Session()

        plugin_name = __name__.split('.')[1]
        my_currency_ids = [
            c for c, p in currencies.items() if p == plugin_name
        ]

        pending_withdrawals = session.query(Withdrawal).filter_by(
            currency=my_currency_ids[0],
            accepted=True,
            executed=False,
            rejected=False)
        for withdrawal in pending_withdrawals:
            account = session.query(Account).filter_by(
                address=withdrawal.address).first()
            logger.info("New withdrawal: %s %s" % (account, withdrawal))
            withdrawal.executed = True
            session.commit()
            session.flush()
            real_amount = withdrawal.amount - dogecoin_withdrawal_fee * (
                10**self.DOGECOIN_DECIMAL_PLACES)
            withdrawal.dogecoin_txid = send_dogecoin(
                withdrawal.dogecoin_address, real_amount)
            session.commit()
            session.flush()

        session.commit()
예제 #11
0
    def _handle_deposits(self):
        session = Session()

        plugin_name = __name__.split('.')[1]
        my_currency_ids = [
            c for c, p in currencies.items() if p == plugin_name
        ]

        # TODO: List unconfirmed deposits
        for transaction in get_last_transactions():
            if transaction['category'] == 'receive' and transaction[
                    'confirmations'] >= dogecoin_confirmations:
                account = session.query(Account).filter_by(
                    dogecoin_deposit_address=transaction['address']).first()
                if account is not None:
                    deposit = session.query(Deposit).filter_by(
                        dogecoin_txid=transaction['txid']).first()
                    if deposit is None:
                        real_amount = transaction['amount']
                        if real_amount <= 0:
                            amount = 0
                        amount = int(real_amount *
                                     (10**self.DOGECOIN_DECIMAL_PLACES))
                        deposit = Deposit(account.address, my_currency_ids[0],
                                          amount)
                        deposit.dogecoin_txid = transaction['txid']
                        deposit.accepted = True
                        logger.info("New deposit: %s %s" % (account, deposit))
                        session.add(deposit)
                        session.commit()
                        session.flush()

        session.commit()
예제 #12
0
def fetch_airline_companies():
    session = Session()
    # crete airlines
    gol_airline = Airline('GLO', 'Gol Transportes Aéreos', 'Brazil')
    avianca_airline = Airline('ONE', 'Avianca Brazil', 'Brazil')
    tam_airline = Airline('TAM', 'TAM', 'Brazil')
    azul_airline = Airline('AZU', 'Azul Linhas Aéreas Brasileiras', 'Brazil')
    # persist data
    session.add(gol_airline)
    session.add(avianca_airline)
    session.add(tam_airline)
    session.add(azul_airline)
    # commit and close session
    session.commit()
    session.close()
예제 #13
0
    def _handle_withdrawals(self):
        session = Session()

        # TODO: API for this
        plugin_name = __name__.split('.')[1]
        my_currency_ids = [c for c, p in currencies.items() if p == plugin_name]

        # TODO: Create a cutesy API for plugin creators
        print("asdfasdfasdfadsf")
        withdrawals = session.query(Withdrawal).filter_by(accepted=True, executed=False, rejected=False).filter(
            Withdrawal.currency.in_(my_currency_ids))
        for withdrawal in withdrawals:
            logger.info("Executing withdrawal %s" % withdrawal)
            withdrawal.executed = True
            session.commit()
            self.bank_sim.send_money(session, withdrawal.bank_account, withdrawal.amount)
            session.commit()
            session.flush()

        session.commit()
예제 #14
0
    def _handle_withdrawals(self):
        session = Session()

        # TODO: Optimize this query to use relations
        pending_withdrawals = session.query(Withdrawal).filter_by(
            accepted=False, executed=False, rejected=False)
        for withdrawal in pending_withdrawals:
            transaction = session.query(BlockchainTransaction).filter_by(
                attachment=withdrawal.attachment).first()
            if transaction is not None:
                withdrawal.accept(transaction)
                session.commit()
                session.flush()
        session.commit()
        session.flush()
예제 #15
0
    def _handle_deposits(self):
        session = Session()

        pending_deposits = session.query(Deposit).filter_by(accepted=True,
                                                            executed=False,
                                                            rejected=False)
        for deposit in pending_deposits:
            logger.info("Handling deposit %s" % deposit)
            # TODO: Double verify deposits [check for amount of confirmations] ???
            # TODO: Use two phased transactions here to protect against two WavesManagers running at once

            deposit.executed = True
            session.commit()
            deposit.waves_transaction_id = send_currency(
                deposit.currency, deposit.address, deposit.amount)
            session.commit()
            session.flush()
            # Send 0.1 Waves for transaction fees if the client has less than 0.01
            if get_waves_balance(deposit.address) < 1000000:
                send_currency(None, deposit.address, 10000000)

        session.commit()
        session.flush()