Пример #1
0
    def test_use_pool(self):
        bc = BlockChain()
        w = Wallet()
        w.create_keys()

        # make some cash
        tx0 = Transaction("0", w.get_address(), 1)
        b = bc.new_block(tx0)
        mine(b)
        self.assertTrue(bc.discard_block(b))

        self.assertEqual(bc.get_wallet_balance(w.get_address()), 1)
        tx_count = 10
        for i in range(tx_count):
            t = Transaction(w.get_address(), 1, 1 / 100)
            w.sign_transaction(t)
            self.assertTrue(bc.add_transaction(t))
        self.assertEqual(len(bc.transaction_pool), tx_count)
        b = bc.new_block(self.tx)

        max_txs_in_block = 2**Tree.MAX_DEPTH
        self.assertEqual(len(list(b.get_transactions())),
                         min(max_txs_in_block, tx_count + 1))

        # Transactions in new block are removed from tx pool when new block is successfully discarded to chain
        b = bc.new_block(self.tx)  # coinbase tx
        mine(b)
        bc.discard_block(b)

        expected_txs_in_tx_pool = max(0, tx_count - (max_txs_in_block - 1))
        self.assertEqual(len(bc.transaction_pool), expected_txs_in_tx_pool)

        leftover_count = min(max_txs_in_block - 1, expected_txs_in_tx_pool)
        self.assertEqual(len(list(bc.new_block(self.tx).get_transactions())),
                         1 + leftover_count)
Пример #2
0
    def post(self):
        key = self.request.GET['key']
        try:
            category = self.request.get("category", "none")
            quantity = float(self.request.get("quantity", 0))
            type = self.request.get("type", "none")
            description = self.request.get("description", "none")
            date = self.request.get("date", "none")
            date_format = datetime.datetime.strptime(date, "%Y-%m-%d")
        except ValueError:
            url = "/viewAccount?key=" + str(
                key) + ";msg_error=Formato de campo incorrecto"
            self.redirect(url)
            return

        account_key = ndb.Key(urlsafe=key)

        #Store the answer

        new_transaction = Transaction(category=category,
                                      quantity=quantity,
                                      type=type,
                                      description=description,
                                      date=date_format,
                                      account=account_key)
        new_transaction.put()
        time.sleep(1)

        url = "/viewAccount?key=" + str(key)
        self.redirect(url)
Пример #3
0
    def test_block_serialize(self):
        a = Block(0, 1, datetime.datetime.utcnow().timestamp())
        t1 = Transaction(0, 1, 2)
        a.add_transaction(t1)
        t2 = Transaction(0, 1, 2)
        a.add_transaction(t2)

        b = Block.from_json(a.to_json())
        self.assertEqual(a.get_hash(), b.get_hash())
Пример #4
0
 def test_walk_transactions(self):
     b = Block(0, 0, 0)
     t = Transaction(0, 1, 2)
     b.add_transaction(t)
     self.assertEqual(len(list(b.get_transactions())), 1)
     t = Transaction(0, 1, 2)
     b.add_transaction(t)
     self.assertEqual(len(list(b.get_transactions())), 2)
     for x in b.get_transactions():
         self.assertIsInstance(x, Transaction)
Пример #5
0
 def deposit(self, depositAmount):
     '''
     Deposit money into the account
     Takes a double as a parameter
     '''
     # Update the account's balance
     self.balance += depositAmount
     self.save()
     # Create a transaction log for the deposit
     Transaction.create_deposit_log(self.owner, depositAmount, self)
Пример #6
0
 def deposit(self, depositAmount):
     '''
     Deposit money into the account
     Takes a double as a parameter
     '''
     # Update the account's balance
     self.balance += depositAmount
     self.save()
     # Create a transaction log for the deposit
     Transaction.create_deposit_log(self.owner, depositAmount, self)
Пример #7
0
 def receive_trasfer(self, transferAmount, sourceAccount):
     '''
     The account receives a transfer from another account.
     Add the money and record the transaction
     Takes a double and another account object as parameters
     '''
     # Update account's balance
     self.balance += transferAmount
     self.save()
     # Create the transaction log for receiving the transfer
     Transaction.create_transfer_received_log(self.owner, transferAmount, sourceAccount, self)
Пример #8
0
 def receive_trasfer(self, transferAmount, sourceAccount):
     '''
     The account receives a transfer from another account.
     Add the money and record the transaction
     Takes a double and another account object as parameters
     '''
     # Update account's balance
     self.balance += transferAmount
     self.save()
     # Create the transaction log for receiving the transfer
     Transaction.create_transfer_received_log(self.owner, transferAmount,
                                              sourceAccount, self)
Пример #9
0
 def save_transaction(self, account, detail):
     trading_date = self.convert_trading_date(detail[0].text)
     if trading_date is None:
         return 0
     description = detail[1].text
     account_id = account.get_account_id()
     balance = float(detail[2].text.replace(',', ''))
     reference_number = self.convert_reference_number(description)
     transaction = Transaction(account_id, reference_number, trading_date,
                               balance, description)
     if transaction.save() == 1:
         self.total_transactions = self.total_transactions + 1
         self.email_transport.send_transaction_email(account, transaction)
Пример #10
0
    def test_locate_transaction(self):
        t = Tree()
        trans1 = Transaction(0, 1, 2)
        self.assertTrue(t.add_transaction(trans1))

        trans2 = Transaction(1, 2, 3)
        self.assertTrue(t.add_transaction(trans2))
        self.assertEqual(t.depth, 1)

        self.assertTrue(t.is_present(trans1))

        trans3 = Transaction(0, 1, 2)
        self.assertFalse(t.is_present(trans3))
Пример #11
0
 def save_transaction(self, account, detail):
     trading_date = self.convert_trading_date(
         detail[0].find_element_by_xpath("div[contains(@class,'list-info-txt-sub')]").text)
     description = detail[0].find_element_by_xpath("div[contains(@class,'list-info-txt-main')]").text
     account_id = account.get_account_id()
     reference_number = detail[1].find_element_by_xpath("div[contains(@class,'list-info-txt-sub')]").text.replace(
         'Số tham chiếu: ', '')
     balance = float(
         detail[1].find_element_by_xpath("div[contains(@class,'list-info-txt-main')]").text.replace(',', '').replace(
             ' ', ''))
     transaction = Transaction(account_id, reference_number, trading_date, balance, description)
     print(reference_number)
     if transaction.save() == 1:
         self.total_transactions = self.total_transactions + 1
         self.email_transport.send_transaction_email(account, transaction)
Пример #12
0
    def withdraw(self, withdrawAmount):
        '''
        Withdraw money from the account
        Takes a double as a parameter
        '''
        # Make sure the account has enough money
        if withdrawAmount <= self.balance:
            # Update the account's balance
            self.balance -= withdrawAmount
            self.save()
            # Create the transaction log for the withdraw
            Transaction.create_withdraw_log(self.owner, withdrawAmount, self)

        else:
            raise Exception("Insufficient Funds.")
Пример #13
0
    def test_sign_transaction(self):
        w = Wallet()
        w.create_keys()

        t = Transaction(w.get_address(), 1, 1)
        th = t.get_hash()

        self.assertIsNone(t.signature)

        self.assertTrue(w.sign_transaction(t))

        self.assertIsNotNone(t.signature)
        self.assertEqual(t.get_hash(), th)

        self.assertTrue(w.verify_transaction(t))
    def save_transaction(self, account, detail):
        trading_date = self.convert_trading_date(detail[0].text)
        reference_number = detail[1].text
        description = detail[3].text
        account_id = account.get_account_id()

        if detail[4].text is not '':
            balance = float(detail[4].text.replace(',', '').replace(' ', ''))
        else:
            balance = float(detail[5].text.replace(',', '').replace(' ', ''))
        transaction = Transaction(account_id, reference_number, trading_date,
                                  balance, description)
        if transaction.save() == 1:
            self.total_transactions = self.total_transactions + 1
            self.email_transport.send_transaction_email(account, transaction)
Пример #15
0
    def withdraw(self, withdrawAmount):
        '''
        Withdraw money from the account
        Takes a double as a parameter
        '''
        # Make sure the account has enough money
        if withdrawAmount <= self.balance:
            # Update the account's balance
            self.balance -= withdrawAmount
            self.save()
            # Create the transaction log for the withdraw
            Transaction.create_withdraw_log(self.owner, withdrawAmount, self)

        else:
            raise Exception("Insufficient Funds.")
Пример #16
0
    def get(self):
        user = users.get_current_user()
        user.nickname()
        try:
            msg_error = self.request.GET['msg_error']
        except:
            msg_error = None

        key = self.request.GET['key']

        account_key = ndb.Key(urlsafe=key)

        transactions = Transaction.query(
            Transaction.account == account_key).order(-Transaction.date)

        template_values = {
            'title': "Transactions",
            'account_key': account_key,
            'transactions': transactions,
            'user_nickname': user.nickname(),
            'user_logout': users.create_logout_url("/"),
            'user_id': user.user_id(),
            'msg_error': msg_error
        }

        template = JINJA_ENVIRONMENT.get_template("invoices.html")
        self.response.write(template.render(template_values))
Пример #17
0
    def generate_wallet_and_coinbase():
        w = Wallet()
        w.create_keys()
        tx = Transaction("0", w.get_address(), 1)  # coinbase
        w.sign_transaction(tx)

        return w, tx
Пример #18
0
def create_transaction():
    """Add and broadcast the given transaction.
    Returns HTTP 400 if the transaction is considered invalid."""
    try:
        # retrieve transaction from request body
        jso = request.get_data(as_text=True)
        tx = Transaction.from_json(jso)

        # add transaction to local blockchain
        success = app.p2p.bc.add_transaction(tx)
        if success:
            # broadcast transaction to p2p network
            app.p2p.broadcast_tx(tx)

            return Response(tx.to_json(), status=HTTP_CREATED)
        else:
            logger.debug("failed to add tx")
            raise BadRequest()
    except BadRequest:
        raise
    except BaseException as e:
        logger.debug(e)
        logger.debug(traceback.format_exc())
        logger.debug(sys.exc_info())
        raise BadRequest()
Пример #19
0
    def test_post_new_block(self):
        self.prepare_app()

        # prepare a valid transaction
        w = Wallet()
        w.create_keys()
        tx = Transaction(0, w.get_address(), 1)
        w.sign_transaction(tx)

        client = app.test_client()

        response = client.post("/block/new", data=tx.to_json())
        self.assertEqual(response.status_code, 201)

        b = Block.from_json(response.get_data())
        self.assertTrue(type(b) == Block)
Пример #20
0
    def test_transaction(self):
        """One tree node can contain only one transaction"""
        n = TreeNode()
        t = Transaction(0, 1, 1)
        self.assertTrue(n.add_child(t))

        n1 = TreeNode()
        self.assertFalse(n.add_child(n1))
Пример #21
0
 def deposit(self, date, description, amount):
     tx = Transaction(date=date,
                      description=description,
                      amount=amount,
                      tx_type='D',
                      account_number=self.number)
     self.transactions.append(tx)
     return tx
Пример #22
0
 def withdrawal(self, date, description, amount):
     tx = Transaction(date=date,
                      description=description,
                      amount=amount * -1,
                      tx_type='W',
                      account_number=self.number)
     self.transactions.append(tx)
     return tx
Пример #23
0
    def test_tree_serialize(self):
        t = Tree()
        u = Tree.from_json(t.to_json())

        self.assertEqual(t.root.get_hash(), u.root.get_hash())

        trans1 = Transaction(0, 1, 2)
        self.assertTrue(t.add_transaction(trans1))
        trans2 = Transaction(1, 2, 3)
        self.assertTrue(t.add_transaction(trans2))
        trans3 = Transaction(2, 3, 4)
        self.assertTrue(t.add_transaction(trans3))

        u = Tree.from_json(t.to_json())
        self.assertEqual(t.root._child_1.get_hash(),
                         u.root._child_1.get_hash())
        self.assertEqual(t.root.get_hash(), u.root.get_hash())
Пример #24
0
 def make_transaction(self, data: dict) -> Transaction:
     """
     Método disparado quando efetuado a chamada de um .load(object).data onde efetua o retorno
     de uma instancia de um dataclass de uma transação
     :param data: payload que irá ser transformado
     :return: Instancia dataclass de umma transação.
     """
     return Transaction(**data)
Пример #25
0
    def test_post_transaction(self):
        self.prepare_app()

        # prepare a valid transaction
        w = Wallet()
        w.create_keys()
        tx = Transaction("0", w.get_address(), 1)
        w.sign_transaction(tx)

        client = app.test_client()

        response = client.post("/block/new", data=tx.to_json())
        self.assertEqual(response.status_code, 201)

        b = Block.from_json(response.get_data())
        mine(b)
        response = client.post("/block", data=b.to_json())
        self.assertEqual(response.status_code, 201)

        tx = Transaction(w.get_address(), 1, 0.5)

        # test without signature
        response = client.post("/transaction", data=tx.to_json())
        self.assertEqual(response.status_code, 400)

        # test with signature
        w.sign_transaction(tx)
        response = client.post("/transaction", data=tx.to_json())
        self.assertEqual(response.status_code, 201)
Пример #26
0
 def save_transaction(self, account, history):
     trading_date = self.convert_trading_date(history['transferDate'])
     trading_time = history['transferTime']
     description = history['remark']
     if description is None:
         description = 'None'
     account_id = account.get_account_id()
     balance = float(history['amount'])
     if history['dcSign'] == 'D':
         balance = -balance
     reference_number = self.code.generate_code(description +
                                                history['transferDate'])
     created_at = trading_date + ' ' + trading_time
     transaction = Transaction(account_id, reference_number, trading_date,
                               balance, description, created_at)
     if transaction.save() == 1:
         self.total_transactions = self.total_transactions + 1
         self.email_transport.send_transaction_email(account, transaction)
Пример #27
0
    def test_inf_nan_balance(self):
        bc = BlockChain()

        tx = Transaction("src", "dst", math.inf)

        is_found = False
        balance, is_found = bc.update_balance("src", math.inf, tx, is_found)
        self.assertEqual(is_found, True)
        self.assertEqual(balance, math.inf)
Пример #28
0
 def save_transaction(self, account, detail):
     now = datetime.now()
     year = str(now.year)
     if detail[0] == 'PEND':
         detail[0] = str(now.day) + '/' + str(now.month)
     trading_date = self.convert_trading_date(detail[0] + '/' + year)
     description = detail[1]
     account_id = account.get_account_id()
     if detail[4] == 'DB':
         balance = float('-' + detail[3].replace(',', ''))
     else:
         balance = float(detail[3].replace(',', ''))
     del detail[0]
     reference_number = self.code.generate_code('-'.join(detail))
     transaction = Transaction(account_id, reference_number, trading_date,
                               balance, description)
     if transaction.save() == 1:
         self.total_transactions = self.total_transactions + 1
         self.email_transport.send_transaction_email(account, transaction)
Пример #29
0
    def enrich_wallet_coinbase(cls):
        w = Wallet()
        w.create_keys()
        tx = Transaction("0", w.get_address(), 1)  # coinbase
        w.sign_transaction(tx)

        cls.w = w
        cls.tx = tx

        return w, tx
Пример #30
0
    def test_verify_foreign_transaction(self):
        w = Wallet()
        w.create_keys()
        t = Transaction(w.get_address(), 1, 1)
        w.sign_transaction(t)

        # Create different keypair
        w.create_keys()

        self.assertTrue(w.verify_transaction(t))
Пример #31
0
    def test_add_transactions(self):
        tp = TransactionPool()
        w = Wallet()
        w.create_keys()

        t = Transaction(w.get_address(), 1, 1)
        # Transaction is not signed
        self.assertFalse(tp.add_transaction(t))

        w.sign_transaction(t)
        self.assertTrue(tp.add_transaction(t))

        # Canot add the same transaciton multiple times
        self.assertFalse(tp.add_transaction(t))

        self.assertEqual(len(tp), 1)

        t2 = tp.pull_transaction()
        self.assertEqual(t.get_hash(), t2.get_hash())
Пример #32
0
 def readFile(self, fileName, bankStatement):
     file = csv.reader( open(fileName) )
     transaction = Transaction()
     for row in file:
         transaction = Transaction()
         lineCorrect = True
         for field in self.fields:
             if field[0] == u'interestDate':
                 if row[ int(field[1]) ].isdigit():
                     transaction.interestDate = row[ int(field[1]) ]
                 else:
                     lineCorrect = False
             elif field[0] == u'date':
                 if row[ int(field[1]) ].isdigit():
                     transaction.date = row[ int(field[1]) ]
                 else:
                     lineCorrect = False
             elif field[0] == u'amount':
                 transaction.amount = row[ int(field[1]) ]
             elif field[0] == u'memo':
                 for i in field[1].split():
                     transaction.memo += u' ' + row[ int(i) ]
             elif field[0] == u'type':
                 transaction.type = row[ int(field[1]) ]
             elif field[0] == u'description':
                 transaction.description = row[ int(field[1]) ].strip()
             elif field[0] == u'account':
                 account = row[ int(field[1]) ]
                 if not re.search( ur'\w{2}\d{2}\w{4}\d{7}\w{0,16}', account ):                        
                     account = account.replace(u" ",u"")
                     search = re.search(ur'\w{2}\d{2}\w{4}.*'+account,u' '.join(row))
                     
                 transaction.account = account
             elif field[0] == u'credit/debit':
                 (fieldNumber,credit,debit) = field[1].split()
                 creditDebit = row[ int(fieldNumber) ]
                 if creditDebit == credit:
                     transaction.debit = False
                 elif creditDebit == debit:
                     transaction.debit = True
             elif field[0] == u'currency' and len(bankStatement.currency) == 0:
                 bankStatement.currency = field[1]                   
Пример #33
0
    def test_secure_wallet_balance(self):
        bc = BlockChain()

        w1 = Wallet()
        w1.create_keys()
        addr1 = w1.get_address()

        tx0 = Transaction("0", addr1, 1)
        b = bc.new_block(tx0)
        mine(b)
        bc.discard_block(b)

        balance = bc.get_secure_wallet_balance(addr1)
        self.assertEqual(balance, None)

        tx1 = Transaction(addr1, "toto", 1)
        w1.sign_transaction(tx1)

        cbtx = WalletHelper.generate_coinbase_with_unused_wallet()
        b1 = bc.new_block(cbtx)
        b1.add_transaction(tx1)
        mine(b1)
        bc.discard_block(b1)

        self.assertEqual(bc.get_secure_wallet_balance("toto"), None)

        for i in range(5):
            tx0 = Transaction("0", addr1, 1)
            b = bc.new_block(tx0)
            mine(b)
            bc.discard_block(b)

        # only 5 confirmations so far, tx is not there yet for secure balance
        self.assertEqual(bc.get_secure_wallet_balance("toto"), None)

        cbtx = WalletHelper.generate_coinbase_with_unused_wallet()
        b6 = bc.new_block(cbtx)
        mine(b6)
        bc.discard_block(b6)

        # tx appears after 6 confirmations only
        self.assertEqual(bc.get_secure_wallet_balance("toto"), 1)
Пример #34
0
    def to_object(self, row):
        if len(row) > 0:
            return (Transaction(id_=int(row[0]),
                                account_number=int(row[1]),
                                date=datetime.strptime(row[2],
                                                       '%Y/%m/%d  %H:%M:%S'),
                                tx_type=row[3],
                                description=row[4],
                                amount=row[5]))

        return None
Пример #35
0
    def send_transfer(self, transferAmount, destinationAccount):
        '''
        The account sends a transfer to another account.
        Make sure there's enough money and remove it then record the transaction
        Takes a double and another account object as parameters
        '''
        if self == destinationAccount:
            raise Exception("Cannot Transfer to the Same Account")

        # Make sure the account has enough money
        if transferAmount <= self.balance:
            # Update the account's balance
            self.balance -= transferAmount
            self.save()
            # Deliver money to other account
            destinationAccount.receive_trasfer(transferAmount, self)
            # Create the transaction log for the tarnsfer
            Transaction.create_transfer_sent_log(self.owner, transferAmount, self, destinationAccount)
        else:
            raise Exception("Insufficient Funds for Transfer.")
Пример #36
0
    def __init__(self):
        self.__failedStrings = u""
        self.dateStart = 99999999
        self.dateEnd = 0
        self.currency = u""
        self.account = u""
        self.language = u"NL"
        self.transactions = []

        d = datetime.today()
        self.dateTime = d.strftime(u"%Y%m%d%H%M%S")
        
        
if __name__ == u"__main__":
    b = BankStatement()
    print b.dateTime
    b.failedStrings = u"test"
    b.failedStrings = u"test2"
    print b.failedStrings
    t = Transaction()
    t.amount = u"100.0"
    b.addTransaction( t )
    print b.transactions
    t = Transaction()
    t.amount = u"200.0"
    b.addTransaction( t )
    print b.transactions
    
    
Пример #37
0
 def get_system_log(self):
     '''
     Retrieves all of the transactions from the system
     '''
     return Transaction.select()