def initialize_standard_bank(self, bank, environment): from src.transaction import Transaction bank.identifier = "standard_bank_id" # deposits - we get the first household from the list of households # if there are no households it will be a blank which is fine for testing amount = 250.0 transaction = Transaction() transaction.this_transaction("deposits", "", environment.households[0].identifier, bank.identifier, amount, bank.interest_rate_deposits, 0, -1) # environment.households[0] is only for testing purposes DO NOT USE IN PRODUCTION transaction.add_transaction(environment) # money - cash and equivalents amount = 100.0 transaction = Transaction() transaction.this_transaction("cash", "", bank.identifier, bank.identifier, amount, 0, 0, -1) transaction.add_transaction(environment) # loans - we get the first firm from the list of firms # if there are no firms it will be a blank which is fine for testing amount = 150.0 transaction = Transaction() transaction.this_transaction("loans", "", bank.identifier, environment.firms[0].identifier, amount, bank.interest_rate_loans, 0, -1) # environment.firms[0] is only for testing purposes DO NOT USE IN PRODUCTION transaction.add_transaction(environment)
def initialize_standard_household(self, household, environment): from src.transaction import Transaction household.identifier = "standard_household_id" # identifier household.parameters["labour"] = 24.00 # labour to sell per step household.parameters["propensity_to_save"] = 0.40 # propensity to save # percentage of income household wants to save as deposits # deposits - we get the first bank from the list of banks # if there are no banks it will be a blank which is fine for testing amount = 200.0 transaction = Transaction() transaction.this_transaction( "deposits", "", household.identifier, environment.banks[0:1][0], amount, environment.banks[0:1][0].interest_rate_deposits, 0, -1) # environment.banks[0:1][0] is only for testing purposes DO NOT USE IN PRODUCTION # what it does is is takes the first bank in environment, but if there are no # banks (which happens in testing) it doesn't break down household.accounts.append(transaction) # money - cash and equivalents amount = 50.0 transaction = Transaction() transaction.this_transaction("cash", "", household.identifier, household.identifier, amount, 0, 0, -1) household.accounts.append(transaction) # manhours - labour to sell amount = 250.0 transaction = Transaction() transaction.this_transaction("manhours", "", household.identifier, household.identifier, amount, 0, 0, -1) household.accounts.append(transaction)
def initialize_standard_firm(self, firm, environment): from src.transaction import Transaction firm.identifier = "standard_firm_id" # identifier firm.parameters[ "productivity"] = 1.20 # how much goods do we get from 1 unit of labour # loans - we get the first bank from the list of banks # if there are no banks it will be a blank which is fine for testing amount = 250.0 transaction = Transaction() transaction.this_transaction( "loans", "", environment.banks[0:1][0], firm.identifier, amount, environment.banks[0:1][0].interest_rate_loans, 0, -1) # environment.banks[0:1][0] is only for testing purposes DO NOT USE IN PRODUCTION # what it does is is takes the first bank in environment, but if there are no # banks (which happens in testing) it doesn't break down firm.accounts.append(transaction) # money - cash and equivalents amount = 200.0 transaction = Transaction() transaction.this_transaction("cash", "", firm.identifier, firm.identifier, amount, 0, 0, -1) firm.accounts.append(transaction) # goods - unique production amount = 50.0 transaction = Transaction() transaction.this_transaction("goods", "", firm.identifier, firm.identifier, amount, 0, 0, -1) firm.accounts.append(transaction)
def init_repo(self): self.__repo.add_item(Transaction(2, 1909, 'in', 'freelancing')) self.__repo.add_item(Transaction(24, 178, 'out', 'food')) self.__repo.add_item(Transaction(1, 1200, 'out', 'rent')) self.__repo.add_item(Transaction(14, 54, 'out', 'food')) self.__repo.add_item(Transaction(14, 55023, 'in', 'salary')) self.__repo.add_item(Transaction(16, 550, 'in', 'freelancing')) self.__repo.add_item(Transaction(23, 1200, 'out', 'project')) self.__repo.add_item(Transaction(2, 230, 'out', 'food')) self.__repo.add_item(Transaction(16, 176, 'out', 'food')) self.__repo.add_item(Transaction(5, 188, 'out', 'food'))
def test_get_max(): repo = Repository() repo.add_item(Transaction(2, 1909, 'in', 'freelancing')) repo.add_item(Transaction(2, 178, 'out', 'food')) repo.add_item(Transaction(1, 1200, 'out', 'rent')) repo.add_item(Transaction(14, 54, 'out', 'food')) repo.add_item(Transaction(14, 55023, 'in', 'salary')) repo.add_item(Transaction(14, 550, 'in', 'freelancing')) repo.add_item(Transaction(23, 1200, 'out', 'project')) repo.add_item(Transaction(2, 230, 'out', 'food')) repo.add_item(Transaction(16, 176, 'out', 'food')) repo.add_item(Transaction(5, 188, 'out', 'food')) assert get_max(repo, 'in', 14).get_money_amount() == 55023 assert get_max(repo, 'out', 2).get_money_amount() == 230
def execute_transaction(self, username: str, shopping_cart, payment_method: str, payment_details, address: DeliveryAddress, account_number: int): if not self.check_availability_of_products(shopping_cart): return MessageResponse( False, 1, "Not all the products are available in this amount") TransactionManagement.transaction_counter += 1 transaction = Transaction(self.transaction_counter, shopping_cart['products'], username, payment_method, payment_details, address, account_number, shopping_cart['store_number']) cart = ShoppingCart(shopping_cart["store_number"], shopping_cart['products']) # until here yet transaction.total_price = cart.calculate_price() if self.payment_system.charge(username, payment_details[0], payment_details[1], payment_details[2], payment_details[3], payment_details[4]) == 'declined': return MessageResponse(False, 1, "payment problem") transaction.update_payment_status() if self.delivery_system.delivery(transaction.products, address) == 'undelivered': return MessageResponse(False, 1, 'delivery problem, payment were cancelled') transaction.update_delivery_status() self.transactions.append(transaction) self.remove_products_from_store(shopping_cart) return MessageResponse( transaction, 1, 'succeed transaction' + str(transaction.transaction_id))
def test_get_balance(): repo = Repository() repo.add_item(Transaction(2, 1909, 'in', 'freelancing')) repo.add_item(Transaction(24, 178, 'out', 'food')) repo.add_item(Transaction(1, 1200, 'out', 'rent')) repo.add_item(Transaction(14, 54, 'out', 'food')) repo.add_item(Transaction(14, 55023, 'in', 'salary')) repo.add_item(Transaction(16, 550, 'in', 'freelancing')) repo.add_item(Transaction(23, 1200, 'out', 'project')) repo.add_item(Transaction(2, 230, 'out', 'food')) repo.add_item(Transaction(16, 176, 'out', 'food')) repo.add_item(Transaction(5, 188, 'out', 'food')) assert get_balance(repo, 2) == 479 assert get_balance(repo, 5) == 291
def main(): path = os.getcwd() print(path) try: print('trying to read') os.chdir(path + '/blk') with open('blkchain.pkl', 'rb') as fp: chain = pickle.load(fp) fp.close() except: check = int(input("Are you miner or wallet :")) if check: print('Miner/Wallet started') else: print('Creating genesis') number_of_candidates = int(input("Enter number of candidates :")) trs = [] for i in range(number_of_candidates): Name = input("Enter name :") age = input("Enter Age :") #usr = User(name=Name, age=age, publickey=sha256(Name.encode() + str(age).encode()).hexdigest(), privatekey=sha256(Name.encode() + str(age).encode()).hexdigest(), candidate=True) ts = Transaction(sha256(Name.encode() + str(age).encode()).hexdigest(), sha256(Name.encode() + str(age).encode()).hexdigest(), 0, name=Name) trs.append(ts) chain = Blockchain() chain.initialize_genesis(trs) os.mkdir('blk') os.chdir(path + '/blk') with open('blkchain.pkl', 'wb') as fp: pickle.dump(chain, fp) fp.close()
def sell(self, symbol, amount): stock_price = self.get_stock_current_price(symbol) if stock_price * self.holdings.get(symbol, 0) < amount: raise Exception('Not enough holding of {}!'.format(symbol)) self.holdings[symbol] = self.holdings[symbol] - amount / stock_price self.cash += amount self.transactions.append(Transaction("SELL", symbol, amount))
def replace_transaction(self, args): """ Replace the amount of a transaction with a given value. replace <day> <type> <description> with <value> """ if len(args) != 5: raise clisys.InvalidArgumentCount if args[3] != 'with': raise clisys.InvalidArgument(args[3]) try: day = int(args[0]) except ValueError: raise clisys.InvalidArgument(args[0]) type = args[1] description = args[2] try: value = int(args[4]) except ValueError: raise clisys.InvalidArgument(args[4]) self.__repo.replace_item( lambda t: t.get_day() == day and t.get_type() == type and t. get_description() == description, Transaction(day, value, type, description))
def add_transaction(self, type_, asset, from_id, to_id, amount, interest, maturity, time_of_default, environment): from src.transaction import Transaction transaction = Transaction() transaction.this_transaction(type_, asset, from_id, to_id, amount, interest, maturity, time_of_default) transaction.add_transaction(environment)
def endow_labour(self, environment, time): # We make sure household get their labour endowment per step for household in environment.households: # First, we set a control variable that makes sure we have exactly # one transaction with "manhours", though this should in general # be the case, this should always run through the second if check = 0 for tranx in household.accounts: if tranx.type_ == "manhours": check = check + 1 # We check how many transactions with manhours are there for the household # If there are no "manhours" transactions then we create one and add it to the household's accounts if check == 0: # The amount is equal to the parameter read from the config of the household amount = household.labour # We create the transaction transaction = Transaction() # We add the appropriate values to the transaction transaction.this_transaction("manhours", "", household.identifier, household.identifier, amount, 0, 0, -1) # It's important to add the transaction using the method # from Transaction class and not manually transaction.add_transaction(environment) else: # If we have more than one "mahhours" transaction we raise an error raise LookupError( "Labour transactions for a household haven't been properly removed." ) logging.info(" labour endowed on step: %s", time)
def new_transaction(self, type_, asset, from_, to, amount, interest, maturity, time_of_default): from src.transaction import Transaction transaction = Transaction() transaction.this_transaction(type_, asset, from_, to, amount, interest, maturity, time_of_default) transaction.add_transaction(self)
def transfer_required_deposits(self): transaction = Transaction() value = round(float(self.r * self.get_account("D")), 4) transaction.this_transaction("rD", self.identifier, -3, value, self.rb, 0, -1) self.accounts.append(transaction) return -1.0 * value
def add_transaction(self, type_, asset, from_id, to_id, amount, interest, maturity, time_of_default): from src.transaction import Transaction transaction = Transaction() transaction.this_transaction(type_, asset, from_id, to_id, amount, interest, maturity, time_of_default) self.accounts.append(transaction) del transaction # append() above does make a copy so we may delete for garbage collection
def buy(self, symbol, amount): stock_price = self.get_stock_current_price(symbol) if self.cash < amount: raise Exception('Not enough money!') self.holdings[symbol] = self.holdings.get(symbol, 0) + amount / stock_price self.cash -= amount self.transactions.append(Transaction("BUY", symbol, amount))
def test_proto(): reward_key = Key.generate_private_key() proto1 = Protocol([], GENESIS_BLOCK, 1337) proto2 = Protocol([("127.0.0.1", 1337)], GENESIS_BLOCK, 1338) miner1 = Miner(proto1, reward_key) miner2 = Miner(proto2, reward_key) miner2.start_mining() miner1.start_mining() try: sleep(5) target_key = Key.generate_private_key() chain = miner1.chainbuilder.primary_block_chain reward_trans = chain.blocks[20].transactions[0] trans_in = TransactionInput(reward_trans.get_hash(), 0) trans_targ = TransactionTarget(target_key, reward_trans.targets[0].amount) trans = Transaction([trans_in], [trans_targ], datetime.utcnow()) trans.sign([reward_key]) assert trans.verify(chain, set()), "transaction should be valid" proto1.received('transaction', trans.to_json_compatible(), None) print("============Transaction=============") sleep(10) chain_len1 = len(miner1.chainbuilder.primary_block_chain.blocks) chain_len2 = len(miner2.chainbuilder.primary_block_chain.blocks) print("Length of chain of miner 1: {}".format(chain_len1)) print("Length of chain of miner 2: {}".format(chain_len2)) finally: miner1.shutdown() miner2.shutdown() assert max(chain_len1, chain_len2) * 90 // 100 < min( chain_len1, chain_len2), "chain lengths are VERY different" chain1 = miner1.chainbuilder.primary_block_chain hashes1 = [b.hash for b in chain1.blocks[:chain_len1 * 90 // 100]] hashes2 = [ b.hash for b in miner2.chainbuilder.primary_block_chain.blocks[:chain_len1 * 90 // 100] ] assert hashes1 == hashes2, "first 90% of chains should be identical" assert not trans.verify( miner1.chainbuilder.primary_block_chain, set()), "inserted transaction should be spent and therefore invalid" assert TransactionInput( trans.get_hash(), 0) in chain1.unspent_coins, "someone spent our coins?"
def test_transaction_constructor(): test_transaction = Transaction("fromAddress", "toAddress", 5, 123, "id", "signature") assert (test_transaction.to_address == "toAddress" and test_transaction.from_address == "fromAddress" and test_transaction.amount == 5 and test_transaction.timestamp == 123 and test_transaction.id == "id" and test_transaction.signature == "signature")
def _read_transactions_from_csv_file(self, path_to_csv_file): transactions = [] with open(path_to_csv_file) as fin: csv_reader = csv.DictReader(fin) for row in csv_reader: transactions.append( Transaction(date=row[self.KEY_TRANSACTION_DATE], description=row[self.KEY_DESCRIPTION], amount=float(row[self.KEY_AMOUNT]))) return transactions
def transfer_excess_reserves(self): availableVolume = self.Q plannedVolume = self.gamma * (1.0 - self.lamb) * self.V transactionVolume = round(min(plannedVolume, availableVolume), 4) self.Q = round(self.Q - transactionVolume, 4) if self.Q < 0.0: logging.info("ERROR: Q negative in transfer_excess_reserves") transaction = Transaction() transaction.this_transaction("E", self.identifier, -3, transactionVolume, self.rb, 0, -1) self.accounts.append(transaction) del transaction
def get_data_pairs(self, file_path): transaction = Transaction( self.data_reader.get_stock_info(stock_file_path=file_path)) turnover = transaction.get_return(self.time_frame_size_y) avg_delta_in_bid_and_ask = transaction.get_average_delta_bid_ask_size( 'all', self.time_frame_size_x) volume_init_by_buy_and_sell = transaction.get_volume_init_by_buy_and_sell( 'all', self.time_frame_size_x) result = [turnover ] + avg_delta_in_bid_and_ask + volume_init_by_buy_and_sell return pd.concat(result, axis=1).iloc[:min(map(len, result))]
def get_last_transaction(self): if not len(self): raise EmptyTransactionLogException() def parse_timestamp(x): return datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f') sorted_transaction_log = sorted( self, key=lambda x: parse_timestamp(x['timestamp']), reverse=True) last_transaction = sorted_transaction_log[0]['transactionJson'] return Transaction(last_transaction)
def initialize_standard_bank(self, bank, environment): from src.transaction import Transaction bank.identifier = "standard_bank_id" # deposits - we get the first household from the list of households # if there are no households it will be a blank which is fine for testing amount = 250.0 transaction = Transaction() transaction.this_transaction("deposits", "", environment.households[0:1][0], bank.identifier, amount, bank.interest_rate_deposits, 0, -1) # environment.households[0:1][0] is only for testing purposes DO NOT USE IN PRODUCTION # what it does is is takes the first household in environment, but if there are no # households (which happens in testing) it doesn't break down bank.accounts.append(transaction) # money - cash and equivalents amount = 100.0 transaction = Transaction() transaction.this_transaction("cash", "", bank.identifier, bank.identifier, amount, 0, 0, -1) bank.accounts.append(transaction) # loans - we get the first firm from the list of firms # if there are no firms it will be a blank which is fine for testing amount = 150.0 transaction = Transaction() transaction.this_transaction("loans", "", bank.identifier, environment.firms[0:1][0], amount, bank.interest_rate_loans, 0, -1) # environment.firms[0:1][0] is only for testing purposes DO NOT USE IN PRODUCTION # what it does is is takes the first firm in environment, but if there are no # firms (which happens in testing) it doesn't break down bank.accounts.append(transaction)
def buildRelationTx(self, options): tx = Transaction(self) if not options: tx.tx_json.obj = Exception('invalid options type') return tx if not ~Transaction.RelationTypes.index(options.type): tx.tx_json.type = Exception('invalid relation type') return tx if options.type == 'trust': return self.__buildTrustSet(options, tx) elif options.type == 'authorize' or \ options.type == 'freeze' or options.type == 'unfreeze': return self.__buildRelationSet(options, tx) tx.tx_json.msg = Exception('build relation set should not go here') return tx
def add_transaction(self, args): """ Add a transaction to the list. add <value> <type> <description> """ try: value = int(args[0]) except ValueError: raise clisys.InvalidArgument(args[0]) type = args[1] description = args[2] transaction = Transaction(int(datetime.today().strftime('%d')), value, type, description) self.__repo.add_item(transaction)
def create_genesis_transaction(private_key, public_key): # TODO: I don't think the genesis transaction needs inputs. It's the genesis, where is it getting its money from? """ Create the genesis transaction. :param private_key: :param public_key: :return: """ hashed_address = SHA256.new(public_key.encode('utf-8')).hexdigest() transaction = { "input_count": 1, "inputs": [{ "transaction_id": '', "output_index": -1, "unlock": { "public_key": public_key, "signature": '', } }], "output_count": 1, "outputs": [{ "address": hashed_address, "amount": 7000 }] } # fill the unlock signature transaction_message = SHA256.new(( # compose transaction message str(transaction['inputs'][0]['transaction_id']) + # input id str(transaction['inputs'][0]['output_index']) + # output index str(hashed_address) + # hashed public key as address str(transaction['outputs']) # new outputs ).encode()) signer = DSS.new(private_key, 'fips-186-3') signature = signer.sign(transaction_message) # sign the message encoded = base64.b64encode(signature).decode() transaction['inputs'][0]['unlock']['signature'] = encoded transaction_id = SHA256.new(str(transaction).encode('utf-8')).hexdigest() transaction['transaction_id'] = transaction_id return Transaction(payload=transaction)
def create_transaction(recipient, amount): """ creates a new transaction and add it to verified_transactions.json :param recipient: public address of the recipient :param amount: the amount of abc to be sent :return: None """ # TODO: Send a success message to client conf = Configuration() try: tx = Transaction() tx.add_output(recipient, amount) tx.unlock_inputs(get_private_key(), get_public_key("string")) save_verified_transaction(tx.get_transaction_id(), tx.get_data()) conf.subtract_balance(tx.sum_of_outputs()) except ValueError as e: # Will raise if insufficient utxos are found raise ValueError("INSUFFICIENT FUNDS")
def do_update(self, environment, time): # As a first step, we accrue all interest over the transactions # Thus, important to notice to keep 0 as interest by default # Unless transaction should carry interest self.accrue_interests(environment, time) # The households sell labour to firms self.sell_labour(environment, time) # The firms sell goods to households self.consume_rationed(environment, time) # We net deposits and loans self.net_loans_deposits(environment, time) # We remove the perishable transactions self.remove_perishable(environment, time) # And add capital to balance the books self.capitalise(environment, time) # Investing of the banks self.invest(environment, time) # Purging accounts at every step just in case transaction = Transaction() transaction.purge_accounts(environment)
def do_update(self, environment, time): # As a first step, we accrue all interest over the transactions # Thus, important to notice to keep 0 as interest by default # Unless transaction should carry interest # DON'T DO INTERESTS SO FAR, DO ONCE THE REST WORKS self.accrue_interests(environment, time) # Then agents get their labour endowment for the step (e.g. work hours to spend) # For now we don't need to keep track of labour left as there is no queue # self.endow_labour(environment, time) # The households sell labour to firms self.sell_labour(environment, time) # The firms sell goods to households self.consume_rationed(environment, time) # We net deposits and loans self.net_loans_deposits(environment, time) # We remove goods and labour (perishable) and are left with capital self.net_labour_goods(environment, time) # Purging accounts at every step just in case transaction = Transaction() transaction.purge_accounts(environment)
def network__get_transactions(self, args): import os from src.bank import Bank from src.household import Household from src.firm import Firm from src.environment import Environment from src.transaction import Transaction from src.network import Network text = "This test checks network.get_transactions \n" self.print_info(text) # # INITIALIZATION # environment_directory = str(args[0]) identifier = str(args[1]) log_directory = str(args[2]) # Configure logging parameters so we get output while the program runs logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S', filename=log_directory + identifier + ".log", level=logging.INFO) logging.info( 'START logging for test network__get_transactions in run: %s', environment_directory + identifier + ".xml") # Construct household filename environment = Environment(environment_directory, identifier) # # TESTING # print(nx.info(environment.network.get_transactions())) print("Adding a transaction") transaction = Transaction() transaction.add_transaction("type", "asset", "bank_test_config_id", "bank_test_config_id_two", 1, 2, 3, 4, environment) print(nx.info(environment.network.get_transactions()))