def deposit(self, deposit_amount): ''' Deposing money on the account, writes to a json file for specific user. Checks for type validations. :param deposit_amount: Amount to deposit :return:None ''' try: deposit_amount = float(deposit_amount) if deposit_amount < 0: transaction_description = "Deposit failed - Amount incorrect." transaction = Transaction(self, datetime.datetime.now(), "deposit", self.balance, self.balance, "failed", transaction_description) self.transaction_list.append(transaction._to_dict()) return False except ValueError: return False balance_before = self.balance self.balance += deposit_amount transaction_description = "Deposit succeeded." transaction = Transaction(self, datetime.datetime.now(), "deposit", balance_before, self.balance, "succeeded", transaction_description) self.transaction_list.append(transaction._to_dict()) return True
def setUp(self): self.company_1 = Company("RailScot") self.tag_1 = Tag("travel") self.company_2 = Company("Pilot Beer") self.tag_2 = Tag("food") self.transaction_1 = Transaction(10.00, self.company_1, self.tag_1) self.transaction_2 = Transaction(6.50, self.company_2, self.tag_2)
def withdraw(self, withdraw_amount): try: withdraw_amount = float(withdraw_amount) if withdraw_amount < 0: transaction_description = "Withdrawal failed - Amount incorrect." transaction = Transaction(self, datetime.datetime.now(), "withdrawal", self.balance, self.balance, "failed", transaction_description) self.transaction_list.append(transaction._to_dict()) return False except ValueError: return False if self.balance - withdraw_amount - self.fees._get_fee( "withdraw_fee") > 0: balance_before = self.balance self.balance -= withdraw_amount transaction_description = "Withdrawal succeeded." transaction = Transaction(self, datetime.datetime.now(), "withdrawal", balance_before, self.balance, "succeeded", transaction_description) self.transaction_list.append(transaction._to_dict()) self.fees._charge_fee("withdraw_fee") return True elif self.balance - withdraw_amount - self.fees._get_fee("overdraft_fee") < 0 and self.balance - withdraw_amount - self.fees._get_fee("overdraft_fee") > self.__overdraft\ or self.balance - withdraw_amount - self.fees._get_fee("withdraw_fee") and self.balance - withdraw_amount - self.fees._get_fee("withdraw_fee") > self.__overdraft < 0: balance_before = self.balance self.balance -= withdraw_amount transaction_description = "Withdrawal succeeded." transaction = Transaction(self, datetime.datetime.now(), "withdrawal", balance_before, self.balance, "success", transaction_description) self.transaction_list.append(transaction._to_dict()) self.fees._charge_fee("overdraft_fee") return True else: transaction_description = "Withdrawal failed - Balance not enough." transaction = Transaction(self, datetime.datetime.now(), "withdrawal", self.balance, self.balance, "failed", transaction_description) self.transaction_list.append(transaction._to_dict()) return False
def create_transaction(): tag = tag_repository.select(request.form["tag_id"]) merchant = merchant_repository.select(request.form["merchant_id"]) amount = request.form["amount"] new_transaction = Transaction(tag, merchant, amount) transaction_repository.save(new_transaction) return redirect("/transactions")
def create(image_id): data = request.form image = Image.get_by_id(image_id) result = create_transaction(data.get("amount"), data.get("payment_method_nonce")) print(type(result)) if type(result) == SuccessfulResult: new_transaction = Transaction(amount=data.get("amount"), image=image, user_id=current_user.id) if new_transaction.save(): # If want to use mailgun api # from app import app # requests.post( # "https://api.mailgun.net/v3/<YOUR_DOMAIN_NAME>/messages", # auth=("api", app.config.get("MAILGUN_API") ), # data={"from": "Mailgun Sandbox <YOUR_DOMAIN_NAME>", # "to": "Your Name <DOMAIN_EMAIL>", # "subject": "Hello", # "text": "Successfully donated"}) flash("Transactions successfull", "success") return redirect(url_for("users.show", username=image.user.username )) else: flash("Could not save transaction", "danger") return redirect(url_for("users.show", username=image.user.username )) else: flash("Could not create braintree transaction", "danger") return redirect(url_for("users.show", username=image.user.username ))
def mine_block(self): proof_of_work = self.get_proof_of_work() mining_reward_transaction = Transaction(MINING_SENDER, self.__node_pub_key, MINING_REWARD, None) self.__outstanding_transactions.append(mining_reward_transaction) new_block = Block( hash_block(self.get_last_block()), int(self.get_last_block().index) + 1, self.__outstanding_transactions, proof_of_work, ) self.__chain.append(new_block) # Check to see if any outstanding transactions have been tampered with after being saved for txn in self.__outstanding_transactions: if not Verification.verify_transaction(txn, self.get_balance): return False if Verification.verify_blockchain(self.__chain): global participants self.__outstanding_transactions = [] participants[self.__node_pub_key] = True self.save_data() return True self.__chain.pop() self.__outstanding_transactions.pop() return False
def generate_json_file_structure(cls, customer) -> Dict: """ :param customer: Take customer object :return: dictionary of Transaction Export model """ transaction = Transaction(customer) return TransactionExport(transaction).to_export()
def make_purchase(symbol, quantity, buyerId): '''make purchase or sale of stocks. If quantity is negative this function becomes a sale instead of purchase. RETURNS String: contains errors. empty if no errors occur.''' print("quantity") print(quantity) symbol = symbol.upper() quote = get_stock(symbol) quantity = int(quantity) if quote.error: return quote.error if quantity > 0: error = buy_stocks(quantity, buyerId, quote.latestPrice) else: error = sell_stocks(quantity, buyerId, quote.latestPrice, symbol) if error: return error new_purchase = Transaction() new_purchase.symbol = symbol new_purchase.quantity = quantity new_purchase.transactionPrice = quote.latestPrice new_purchase.buyerId = buyerId db.session.add(new_purchase) db.session.commit() return ""
def main(): engine = create_engine(connection_url) Session = sessionmaker() Session.configure(bind=engine) session = Session() try: client = YnabClient(token) budget_id = get_budget_id(client) transactions = client.getTransactions(budget_id) for t in transactions: # TODO: Handle subtransactions # TODO: Add more date-related columns. Separate year, month, week of month, day of week etc. to allow for cool window functions amount = t['amount'] / 100 transaction = Transaction(id=t['id'], date=t['date'], amount=amount, category=t['category_name'], payee=t['payee_name'], description=t['memo']) session.add(transaction) session.commit() except: session.rollback() raise finally: session.close()
def add_block(self, block): # block is dict here # transactions is a list of transaction object transactions = [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions'] ] proof_is_valid = Verification.valid_proof(transactions[:-1], block['previous_hash'], block['proof']) hashes_match = hash_block(self.chain[-1]) == block['previous_hash'] if not proof_is_valid or not hashes_match: return False converted_block = Block(block['index'], block['previous_hash'], transactions, block['proof'], block['timestamp']) self.__chain.append(converted_block) """ update open transaction on peer node, when broadcast block to peer node the some open transactions on peer node should be removed because it will be store in new block """ stored_transactions = self.__open_transactions[:] for itx in block['transactions']: # itx is incoming tx for opentx in stored_transactions: # opentx is open transaction of node # for every incoming transaction, check if it is part of my open transaction if opentx.sender == itx['sender'] and opentx.recipient == itx[ 'recipient'] and opentx.amount == itx[ 'amount'] and opentx.signature == itx['signature']: # if same, try removing it from peer node to prevent encountering second time try: self.__open_transactions.remove(opentx) except ValueError: print('Item was already removed') self.save_data() return True
def resolve(self): winner_chain = self.chain replace = False # whether our current chain is getting replaced, initially is False for node in self.__peer_nodes: url = 'http://{}/chain'.format(node) try: response = requests.get(url) node_chain = response.json() # list of block dict # create list of block object with a list of dict transaction node_chain = [ Block(block['index'], block['previous_hash'], [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions'] ], block['proof'], block['timestamp']) for block in node_chain ] node_chain_length = len(node_chain) local_chain_length = len(winner_chain) if node_chain_length > local_chain_length and Verification.verify_chain( node_chain): winner_chain = node_chain replace = True # if replace is True, we can assume our transactions are incorrect except requests.exceptions.ConnectionError: continue self.resolve_conflicts = False self.chain = winner_chain if replace: self.__open_transactions = [ ] # if chain is replaced, set local open tx to [] self.save_data() return replace
def create(image_id): data = request.form image = Image.get_by_id(image_id) result = create_transaction(data.get("amount"), data.get("payment_method_nonce")) if type(result) == SuccessfulResult: new_transaction = Transaction(amount=data.get("amount"), image=image, user_id=current_user.id) if new_transaction.save(): requests.post( "https://api.mailgun.net/v3/sandboxf2ff5a19c3874580ac009024f05edf38.mailgun.org/messages", auth=("api", "17b5f5ca8aa9f463dab52b23c72c4c9d-53c13666-50ef3ea2"), data={ "from": "Mailgun Sandbox <*****@*****.**>", "to": "[email protected] <*****@*****.**>", "subject": "Hello [email protected]", "text": "Succesfully receive a donation" }) return redirect(url_for("users.show", username=image.user.username)) else: return "Could not save transaction" else: return "Could not create braintree transaction" return redirect(url_for("users.show", username=image.user.username))
def test_transaction_doubled_transaction(capsys): account_args = { 'account': { 'activeCard': True, 'availableLimit': 1000 }, 'violations': [''] } transaction_args = { "transaction": { "merchant": "Burger King", "amount": 20, "time": "2019-02-13T10:00:30.000Z" } } transaction1_args = { "transaction": { "merchant": "Burger King", "amount": 20, "time": "2019-02-13T10:00:00.000Z" } } account = Account(**account_args) transaction1 = Transaction(**transaction1_args) transactions = {0: transaction1} TransactionAuthorizer(account, transactions, transaction_args) assert capsys.readouterr().out == \ "{'account': {'activeCard': True, 'availableLimit': 1000}, 'violations': ['doubled-transaction']}\n"
def create_checkout(subscription_id): subscription = Subscription.get_or_none(Subscription.id == subscription_id) user = User.get_by_id(current_user.id) nonce_from_the_client = request.form["payment_method_nonce"] result = gateway.customer.create({ "first_name": current_user.name, "email": current_user.email, "payment_method_nonce": nonce_from_the_client }) if result.is_success : result_subscription = gateway.subscription.create({ "id" : current_user.id, "payment_method_token": result.customer.payment_methods[0].token, "plan_id": subscription.id }) if type(result_subscription) == SuccessfulResult: new_transaction = Transaction(amount = subscription.price, subscription = subscription.id , user = current_user.id) if new_transaction.save(): user.is_valid = True user.save() flash ("Transaction Successful", "success") send_message_first_payment.delay(email = current_user.email, name = current_user.name) return redirect(url_for('home')) else : flash ("Transaction Failed, check your card details and try again", "danger") return redirect(url_for('home'))
def new_transaction(user_id): ''' Add new transaction. ''' # First check that the user is valid dc = DynamoClient() user = dc.get_user_by_id(user_id) if user is None: return Response(json.dumps( {'403 BAD': 'Unauthorized access to webhook'}), status=403, mimetype='application/json') # If user is valid, make sure that actor or target is the user. req_data = request.get_json() if req_data['data']['target'][req_data['data']['target']['type']][ 'username'] == user.username or req_data['data']['actor'][ 'username'] == user.username: # Then, check the transaction try: t = Transaction(req_data) except: return Response(json.dumps( {'400 BAD': 'Invalid params for transaction payload'}), status=400, mimetype='application/json') # If all is good, index the transaction. es = EsClient() es.add_transaction(t) return Response(json.dumps({'200 OK': 'The request has succeeded'}), status=200, mimetype='application/json') return Response(json.dumps({'403 BAD': 'Unauthorized access to webhook'}), status=403, mimetype='application/json')
def post(): try: data = request.get_json() new_transaction = Transaction(**data).save() except Exception as e: return jsonify({'error_msg':str(e)}), 405 return jsonify({'result': new_transaction}), 201
def load_data(self): try: target_path = "../target/blockchain" + self.__node_port + ".txt" with open(target_path, mode="r") as file: print("------Loading existing blockchain------") file_content = file.readlines() blockchain = json.loads(file_content[0][:-1]) outstanding_transactions = json.loads(file_content[1][:-1]) updated_blockchain = [] updated_outstanding_transactions = [] for block in blockchain: updated_block = Block( block["prev_hash"], block["index"], [ Transaction( tx["sender"], tx["recepient"], tx["amount"], tx["signature"], tx["timestamp"], ) for tx in block["transactions"] ], block["proof_of_work"], block["timestamp"], ) updated_blockchain.append(updated_block) self.__chain = updated_blockchain for txn in outstanding_transactions: updated_txn = Transaction( txn["sender"], txn["recepient"], txn["amount"], txn["signature"], txn["timestamp"], ) updated_outstanding_transactions.append(updated_txn) self.__outstanding_transactions = updated_outstanding_transactions global participants participants = json.loads(file_content[2][:-1]) peer_nodes = json.loads(file_content[3][:-1]) self.__peer_nodes = set(peer_nodes) self.__node_port = json.loads(file_content[4]) except (IOError, IndexError): print("------Initializing new blockchain with genesis block------")
def select(id): sql = "SELECT * FROM transactions WHERE id=%s" values = [id] result = run_sql(sql, values)[0] company = company_repository.select(result["company_id"]) tag = tag_repository.select(result["tag_id"]) transaction = Transaction(result["amount"], company, tag, result["id"]) return transaction
def select(id): sql = "SELECT * FROM transactions WHERE id = %s" values = [id] result = run_sql(sql, values)[0] merchant = merchant_repository.select(result["merchant_id"]) tag = tag_repository.select(result["tag_id"]) transaction = Transaction(merchant, result["date"], result["amount"], tag, result["id"]) return transaction
def add(): """Input transaction.""" t = Transaction( datetime.strptime(request.values['day'], '%Y-%m-%d').date(), request.values['supplier'], float(request.values['amount']), request.values['category']) Session.add(t) Session.commit() return get_latest()
def create_transaction(): merchant_id = request.form['merchant_id'] tag_id = request.form['tag_id'] amount = request.form['amount'] merchant = merchant_repository.select(merchant_id) tag = tag_repository.select(tag_id) transaction = Transaction(merchant, tag, amount) transaction_repository.save(transaction) return redirect('/transactions')
def create_transaction(): amount = request.form["amount"] company_id = request.form["company_id"] tag_id = request.form["tag_id"] company = company_repository.select(company_id) tag = tag_repository.select(tag_id) new_transaction = Transaction(amount, company, tag) transaction_repository.save(new_transaction) return redirect("/")
def update_transaction(id): amount = request.form['amount'] category = category_repository.select(request.form['category_id']) date = request.form['date'] merchant = merchant_repository.select(request.form['merchant_id']) user = user_repository.select(request.form['user_id']) transaction = Transaction(amount, category, date, merchant, user, id) transaction_repository.update(transaction) return redirect("/transactions")
def select(id): sql = "SELECT * FROM transactions WHERE id = %s" values = [id] result = run_sql(sql, values)[0] tag = tag_repository.select(result['tag_id']) merchant = merchant_repository.select(result['merchant_id']) user = user_repository.select(result['user_id']) transaction = Transaction(tag, merchant, user, result['amount'], result['date'], result['id']) return transaction
def create_transaction(): amount = request.form["amount"] merchant_id = request.form["merchant_id"] tag_id = request.form["tag_id"] merchant = merchant_repository.select(merchant_id) tag = tag_repository.select(tag_id) new_transaction = Transaction(amount, merchant, tag) transaction_repository.save(new_transaction) return redirect("/transactions")
def test_transaction_minimum_interval(capsys): account_args = { 'account': { 'activeCard': True, 'availableLimit': 1000 }, 'violations': [''] } transaction_args = { "transaction": { "merchant": "Burger King", "amount": 20, "time": "2019-02-13T10:01:30.000Z" } } transaction1_args = { "transaction": { "merchant": "Burger King", "amount": 30, "time": "2019-02-13T10:00:00.000Z" } } transaction2_args = { "transaction": { "merchant": "7 Eleven", "amount": 20, "time": "2019-02-13T10:00:30.000Z" } } transaction3_args = { "transaction": { "merchant": "Pizza Hut", "amount": 10, "time": "2019-02-13T10:01:00.000Z" } } account = Account(**account_args) transaction1 = Transaction(**transaction1_args) transaction2 = Transaction(**transaction2_args) transaction3 = Transaction(**transaction3_args) transactions = {0: transaction1, 1: transaction2, 2: transaction3} TransactionAuthorizer(account, transactions, transaction_args) assert capsys.readouterr().out == \ "{'account': {'activeCard': True, 'availableLimit': 1000}, 'violations': ['high-frequency-small-intervall']}\n"
def load_data(self): try: # mode should be 'rb' if using pickle, and txt should be p with open('blockchain-{}.txt'.format(self.node_id), mode='r') as f: # file_content = pickle.loads(f.read()) # blockchain = file_content['chain'] # open_transactions = file_content['ot'] file_content = f.readlines() # from string to python object blockchain = json.loads(file_content[0][:-1]) # without '\n' # at this time, blockchain is a list of dict # [{..}, {..}...] updated_blockchain = [] for block in blockchain: converted_tx = [ Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions'] ] # a list of transaction object # block = {...} for now updated_block = Block(block['index'], block['previous_hash'], converted_tx, block['proof'], block['timestamp']) updated_blockchain.append(updated_block) self.chain = updated_blockchain # a list of block object will be loaded by setter open_transactions = json.loads(file_content[1][:-1]) updated_transactions = [] for tx in open_transactions: updated_transaction = Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) updated_transactions.append(updated_transaction) self.__open_transactions = updated_transactions peer_nodes = json.loads(file_content[2]) self.__peer_nodes = set(peer_nodes) # IOError is file not found error except (IOError, IndexError): pass finally: print('Cleanup!')
def select_one_transaction(id): sql = "SELECT * FROM transactions WHERE id = %s" values = [id] result = run_sql(sql, values)[0] account = account_repository.select_one_account(result["account_id"]) merchant = merchant_repository.select_one_merchant(result["merchant_id"]) tag = tag_repository.select_one_tag(result["tag_id"]) transaction = Transaction(account, merchant, result['amount'], result['date'], tag, result['id']) return transaction
def select_all(): transactions = [] sql = "SELECT * FROM transactions" results = run_sql(sql) for result in results: company = company_repository.select(result["company_id"]) tag = tag_repository.select(result["tag_id"]) transaction = Transaction(result["amount"], company, tag, result["id"]) transactions.append(transaction) return transactions
def create_transaction(): merchant_id = request.form["merchant_id"] merchant = merchant_repository.select(merchant_id) date = request.form["date"] amount = float(request.form["amount"]) tag_id = request.form["tag_id"] tag = tag_repository.select(tag_id) new_transaction = Transaction(merchant, date, amount, tag) transaction_repository.save(new_transaction) return redirect("/transactions")