Ejemplo n.º 1
0
    def SetUp(self):
        """
		Запускается в начале каждого теста,
		создает пользователя для тестирования
		"""
        self.name, self.total_money = 'test Wallet', 1000000
        self.wallet = Wallet(self.name, self.total_money)
Ejemplo n.º 2
0
class TestWalletCase(object):
    def SetUp(self):
        """
		Запускается в начале каждого теста,
		создает пользователя для тестирования
		"""
        self.name, self.total_money = 'test Wallet', 1000000
        self.wallet = Wallet(self.name, self.total_money)
        print self.wallet.name

    def test_add_money(self):
        """
		Проверяет функцию перемещения денег
		"""
        self.wallet.add_money(666)
        print self.wallet.total_money

    def test_move_money(self):
        """
		Проверяет функцию пополнения баланса
		"""
        #<----->

    def run_all_test(self):
        """
		Запускает все тесты
		"""
        self.SetUp()
        self.test_add_money()
Ejemplo n.º 3
0
def wallet_transfer(source_wallet_id, target_wallet_id):
    source_wallet_query = Wallet.objects(wallet_id=source_wallet_id)
    if source_wallet_query.count() != 1:
        return make_response(("Database consistency error", 500))

    target_wallet_query = Wallet.objects(wallet_id=target_wallet_id)
    if target_wallet_query.count() != 1:
        return make_response(("Database consistency error", 500))

    source_wallet = source_wallet_query.first()
    target_wallet = target_wallet_query.first()
    transfer_amount = request.json['amount']

    OperationLogEntry.log_transfer(source_wallet, target_wallet,
                                   transfer_amount, OperationStatus.NEW)
    OperationLogEntry.log_transfer(target_wallet, source_wallet, 0,
                                   OperationStatus.NEW)

    if source_wallet.balance < transfer_amount:
        return make_response(('Low balance', 400))

    initial_balance = source_wallet.balance

    source_currency = source_wallet.currency
    target_currency = target_wallet.currency

    exchange_rate = get_exchange_rates(source_currency, target_currency)

    converted_transfer_amount = transfer_amount * exchange_rate
    source_wallet.balance -= transfer_amount

    try:
        source_wallet.save(save_condition={'balance': initial_balance})
    except SaveConditionError as e:
        source_wallet.reload()
        OperationLogEntry.log_transfer(source_wallet, target_wallet,
                                       transfer_amount, OperationStatus.FAILED)
        OperationLogEntry.log_transfer(target_wallet, source_wallet,
                                       -converted_transfer_amount,
                                       OperationStatus.FAILED)
    else:
        try:
            target_wallet.update(inc__balance=converted_transfer_amount)
        except Exception as e:
            target_wallet.reload()
            OperationLogEntry.log_transfer(
                source_wallet, target_wallet, transfer_amount, OperationStatus.
                CRITICAL)  # Should raise an alarm and be investigated ASAP
        else:
            OperationLogEntry.log_transfer(source_wallet, target_wallet,
                                           transfer_amount,
                                           OperationStatus.SUCCESS)
            OperationLogEntry.log_transfer(target_wallet, source_wallet,
                                           -converted_transfer_amount,
                                           OperationStatus.SUCCESS)
    return make_response(
        (app.json_encoder().encode(source_wallet.get_sanitized_object()),
         "200"))
Ejemplo n.º 4
0
def register():
    print(request.json)
    wallet_data = request.json
    password_hashed = HMAC(b"somesecret",
                           str.encode(wallet_data['password'])).digest()
    wallet_data['password'] = password_hashed
    wallet = Wallet(**wallet_data)
    wallet.save()
    return make_response(
        (app.json_encoder().encode(wallet.get_sanitized_object()), "201"))
Ejemplo n.º 5
0
def wallet_info(wallet_id):
    wallet_query = Wallet.objects(wallet_id=wallet_id)
    if wallet_query.count() != 1:
        return make_response(("Databse consistency error", 500))
    wallet = wallet_query.first()
    return make_response(
        (app.json_encoder().encode(wallet.get_sanitized_object()), "201"))
Ejemplo n.º 6
0
 def __init__(self, token: str, init_cash_amount: float):
     self.wallet = Wallet(token, init_cash_amount)
     self.start_amount = init_cash_amount
     # this should be set once strategy has run
     self.end_amount = 0
     # rate of return will be calculated once strategy is executed
     self.ror = 0
Ejemplo n.º 7
0
    def test_move_money_from_wal_to_wal(self):
        """
		Проверяет функцию пополнения баланса
		"""
        self.SetUp()
        test_wallet = Wallet("wallet 2", 400)
        self.wallet.move_money(300000, test_wallet)
        assert self.wallet.balance == 700000
        assert test_wallet.balance == 300400
Ejemplo n.º 8
0
    def mine_block(self):
        """
        take all open_transactions and add to a new block, add to blockchain
        """
        if self.public_key is None:
            return None
        last_block = self.__chain[-1]
        hashed_block = hash_block(last_block)

        # proof of work before adding reward transaction
        proof = self.proof_of_work()

        # miner get reward, reward will be sent to the node which did mining
        # we never verify signature here
        reward_transaction = Transaction(sender='MINING',
                                         recipient=self.public_key,
                                         signature='',
                                         amount=MINING_REWARD)

        # now we ensure that is not managed globally but locally
        # could safely do that without risking that open transaction would be affected
        copied_transactions = self.__open_transactions[:]

        # loop check all transactions(not include reward transactions) which will be added in next block
        for tx in copied_transactions:
            if not Wallet.verify_transaction(tx):
                return None
        copied_transactions.append(
            reward_transaction)  # just add into open transaction

        block = Block(index=len(self.__chain),
                      previous_hash=hashed_block,
                      transactions=copied_transactions,
                      proof=proof)

        self.__chain.append(block)  # add new block into blockchain
        self.__open_transactions = []
        self.save_data()
        for node in self.__peer_nodes:
            url = 'http://{}/broadcast-block'.format(node)
            converted_block = block.__dict__.copy()
            converted_block['transactions'] = [
                tx.__dict__ for tx in converted_block['transactions']
            ]
            try:
                response = requests.post(url, json={'block': converted_block})
                if response.status_code == 400 or response.status_code == 500:
                    print('Broadcast block declined, needs resolving')
                if response.status_code == 409:  # 409 means conflict
                    self.resolve_conflicts = True
            except requests.exceptions.ConnectionError:
                continue
        return block
Ejemplo n.º 9
0
    def CreateWallet(self,  name):
        log.info('CreateWallet(' + name + ')...')
            
        try:
            Wallet.objects.get(name=name)
            log.info('Name %s already exists. Aborting creation ', name)
            return tools.HttpHelper.BuildBadRequest('The wallet %s already exists.' % (name))

        except DoesNotExist:
            # Not found
            pass
            
        #except Exception as e:
         #   log.error('Exception: ' + str(e))
          #  return tools.HttpHelper.BuildBadRequest('Exception: ' + str(e))
            
            
        # create wallet
        wallet = Wallet(name=name,  balance=0)
        wallet.save()
                
        return tools.HttpHelper.BuildGoodRequest('CreateWallet created') 
Ejemplo n.º 10
0
 def post(self):
     username = request.json['username']
     email = request.json['email']
     password = request.json['password']
     # email regexp validation
     if not re.match(r'^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$',
                     email):
         abort(400, message='Email not valid.')
     # verify password weakness
     if len(password) < 6:
         abort(400, message='Password too weak.')
     else:
         try:
             user = User(username=username,
                         email=email,
                         password=generate_password_hash(password),
                         active=False)
             user.save()
         # verify if email/username already exist
         except NotUniqueError:
             abort(400,
                   message='Username or email already used by another user')
     # encode jwt
     exp = datetime.datetime.utcnow() + datetime.timedelta(
         days=ACTIVATION_EXPIRE_DAYS)
     encoded = jwt.encode({
         'email': email,
         'exp': exp
     },
                          SECRET_KEY,
                          algorithm='HS256')
     activation_code = encoded.decode('utf-8')
     # Send activation email
     activation_str = "Your activation code is: " + activation_code
     send_email(email, "Activation code", activation_str)
     # create new wallet
     wallet = Wallet(username=username)
     wallet.save()
     return {'success': "Account created"}
Ejemplo n.º 11
0
def wallet_report(wallet_id, mode):
    allowed_modes = {'json', 'xml', 'csv'}
    if mode not in allowed_modes:
        return make_response(('Wrong report type requested!', 400))
    wallet_query = Wallet.objects(wallet_id=wallet_id)
    if wallet_query.count() != 1:
        return make_response(("Databse consistency error", 500))
    report_list = OperationLogEntry.objects(wallet_id=wallet_id).all()
    if mode == 'csv':
        return make_response((create_csv_report(report_list), 200))
    if mode == 'xml':
        return make_response(("XML not supported", 417))

    return make_response(
        (app.json_encoder().encode([i.to_mongo() for i in report_list]), 200))
Ejemplo n.º 12
0
def create_courier(db: Session, courier: courier_schema.CourierRegister):
    try:
        name = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', courier.mobile)
        db_courier = Couriers(mobile=courier.mobile,
                              last_name=name,
                              first_name=name)
        db.add(db_courier)
        db.flush()
        # 给用户创建一个钱包
        new_wallet = Wallet(courier_id=db_courier.id)
        db.add(new_wallet)
        db.commit()
        db.refresh(db_courier)
        return db_courier
    except Exception as e:
        log.logger.error(e)
        raise HTTPException(500, detail=e)
    finally:
        db.close()
Ejemplo n.º 13
0
def wallet_topup(wallet_id):
    wallet_query = Wallet.objects(wallet_id=wallet_id)
    if wallet_query.count() != 1:
        return make_response(("Databse consistency error", 500))
    wallet = wallet_query.first()
    old_balance = wallet.balance
    OperationLogEntry.log_topup(wallet, request.json['amount'],
                                OperationStatus.NEW)
    wallet.balance += request.json['amount']
    try:
        wallet.save(save_condition={'balance': old_balance})
    except SaveConditionError as e:
        wallet.reload()
        OperationLogEntry.log_topup(wallet, request.json['amount'],
                                    OperationStatus.FAILED)
        return make_response(
            (app.json_encoder().encode(wallet.get_sanitized_object()), 409))
    else:
        OperationLogEntry.log_topup(wallet, request.json['amount'],
                                    OperationStatus.SUCCESS)
        return make_response(
            (app.json_encoder().encode(wallet.get_sanitized_object()), 200))
Ejemplo n.º 14
0
class TestWalletCase(object):
    def SetUp(self):
        """
		Запускается в начале каждого теста,
		создает пользователя для тестирования
		"""
        self.name, self.total_money = 'test Wallet', 1000000
        self.wallet = Wallet(self.name, self.total_money)

    def test_add_money(self):
        """
		Проверяет функцию перемещения денег
		"""
        self.SetUp()
        self.wallet.add_money(666)
        assert self.wallet.balance == 1000666

    def test_move_money_from_wal_to_wal(self):
        """
		Проверяет функцию пополнения баланса
		"""
        self.SetUp()
        test_wallet = Wallet("wallet 2", 400)
        self.wallet.move_money(300000, test_wallet)
        assert self.wallet.balance == 700000
        assert test_wallet.balance == 300400

    def test_move_money_from_wal_to_cat(self):
        """
		Проверяет функцию пополнения баланса
		"""
        self.SetUp()
        test_cat = Category("category", 400)
        self.wallet.move_money(300000, test_cat)
        assert self.wallet.balance == 700000
        assert test_cat.balance == 300400

    def run_all_test(self):
        """
		Запускает все тесты
		"""
        self.test_add_money()
        self.test_move_money_from_wal_to_wal()
        self.test_move_money_from_wal_to_cat()
Ejemplo n.º 15
0
            ) and peer_blockchain.size() > best_blockchain.size():
                best_blockchain = peer_blockchain


################################################
# This is the main function that starts the application

if __name__ == '__main__':
    if len(sys.argv) >= 4:
        ip_address = sys.argv[1]
        port = sys.argv[2]
        id = sys.argv[3]
    else:
        print("Illegal argument, cant start the models")
        sys.exit(0)

    # Creates its wallet
    wallet = Wallet(blockchain)

    # Node collects all the neighbors in the P2P network
    collect_neighbors()

    # Node registers itself in the P2P network
    self_register()

    # Node mines genesis if it is a first node in the network
    blockchain.mine_genesis()

    get_updated()
    app.run(host=ip_address, port=port)
Ejemplo n.º 16
0
    blockchain.remove_peer_node(node_url)
    response = {
        'message': 'Node removed',
        'all_node': blockchain.get_peer_nodes()
    }
    return jsonify(response), 200


@app.route('/nodes', methods=['GET'])
def get_node():
    nodes = blockchain.get_peer_nodes()
    response = {
        'all_nodes': nodes
    }
    return jsonify(response), 200


if __name__ == '__main__':
    '''User can pass the port args in order to run app on different server'''
    from argparse import ArgumentParser
    parser = ArgumentParser()
    parser.add_argument('-p', '--port', type=int, default=5003)
    args = parser.parse_args()
    port = args.port

    wallet = Wallet(port)
    blockchain = Blockchain(wallet.public_key, port)

    # run() take 2 args, IP and port
    app.run(host='0.0.0.0', port=port, debug=True)
Ejemplo n.º 17
0
        return response, status_codes["CLIENT_ERROR"]
    node = node_details["node"]
    blockchain.add_peer_node(node)
    response = {
        "Message": "Node added successfully.",
        "Nodes": list(blockchain.get_peer_nodes()),
    }
    return jsonify(response), status_codes["CREATED"]


@server.route("/node/<node_url>", methods=["DELETE"])
def remove_node(node_url):
    if node_url == "" or node_url == None:
        response = {"Message": "Invalid node url"}
        return jsonify(response), status_codes["CLIENT_ERROR"]
    blockchain.remove_peer_node(node_url)
    response = {
        "Message": "Node removed successfully",
        "Nodes": list(blockchain.get_peer_nodes()),
    }
    return jsonify(response), status_codes["SUCCESS"]


if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("-p", "--port", type=int, default=8000)
    args = parser.parse_args()
    port = args.port
    wallet = Wallet(node=port)
    blockchain = Blockchain(wallet.public_key + '-' + str(port))
    server.run(host=host, port=port)
Ejemplo n.º 18
0
 def test_move_money_from_cat_to_wallet(self):
     self.SetUp()
     test_wallet = Wallet("test Wallet", 500)
     self.category.move_money(300000, test_wallet)
     assert self.category.balance == 700000
     assert test_wallet.balance == 300500
Ejemplo n.º 19
0
 def get_wallet(self, symbol, decrypted_seed=None) -> Wallet:
     xpub = self.xpubs[symbol]
     data = None
     if symbol in self.data:
         data = self.data[symbol]
     return Wallet(decrypted_seed, xpub, data)