def calcClope(self, filename, repulsion): with open(filename, "r") as ins: for idx, line in enumerate(ins): # if (idx > 0 and idx % 50 == 0): # print idx # print '.', transaction = Transaction(line) newCluster = Cluster(transaction.getTransaction()) self.clusters.append(newCluster) profitFromNewCluster = self.getProfit(self.clusters, repulsion); profitMax = profitFromNewCluster; self.clusters.remove(newCluster); moved = False for cluster in self.clusters: cluster.addTransaction(transaction.getTransaction()) profit = self.getProfit(self.clusters, repulsion) if (profitMax <= profit): profitMax = profit else: cluster.removeTransaction(transaction.getTransaction()); if (profitMax == profitFromNewCluster): self.clusters.append(newCluster) moved = True if not moved: break #print return self
def adjust_balance(self, diff): self.edited = 1 transaction = Transaction() transaction.payee = "Balance Adjustment" transaction.amount = diff transaction.cleared = 1 transaction.memo = "Adjustment" self.cur_transaction.append(transaction) self.redraw_all(-1) # only redraw [-1]? return
def serveForever(self): """The only function any user of this class needs to run! Receives, acts on, and responds to UDP control packets as the Mini-T (or similar hardware) would. Packets are received by the main thread and queued for action and response by a second thread. """ chipsLog.info("Dummy Hardware UDP Server starting") # This starts the packet "act and respond" handler thread self.start() while not self.stopServing: try: data, addr = self._socket.recvfrom(DummyHardware.SOCKET_BUFFER_SIZE) except KeyboardInterrupt: chipsLog.warning("\nKeyboard interrupt (ctrl-c) received whilst waiting for incoming UDP packet") self._stopServingAndJoinThreads() return except: chipsLog.warning("\nException caught whilst waiting for incoming UDP packet") self._stopServingAndJoinThreads() return if not data: chipsLog.warning("Socket received an empty packet from " + repr(addr) + \ ". Assuming socket now closed.\nTerminating dummy hardware server...") self._stopServingAndJoinThreads() return else: chipsLog.debug("\nReceived packet from " + repr(addr)) transaction = Transaction.constructHostTransaction(data, addr) self._transaction_queue.put(transaction)
def execute(self, sid, command, oid, *args): #@startTime = time.time() log.debug('execute', sid, oid, command, args) # check client id session = self.clientMngr.getSession(sid) if not session.cid: raise ige.SecurityException('No player object selected.') if not self.validateClient(session): raise ige.GameException('Wrong version of client.') # check game status (admin is allowed anytime) if self.status != Const.GS_RUNNING and session.cid != Const.OID_ADMIN: raise ige.ServerStatusException(self.status) # check existence of the commander if not self.db.has_key(session.cid): raise ige.GameException('This player does not exist. He/she could lose.') # update client's liveness session.touch() # find correct object type try: obj = self.db[oid] except KeyError: raise ige.NoSuchObjectException('Object %d does not exist.' % oid) cmdObj = getattr(self.cmdPool[obj.type], command) if not hasattr(cmdObj, 'public') or not cmdObj.public: raise ige.SecurityException('Access denied - method is not public.') # get acces level of the commander accLevel = Const.AL_NONE if obj.owner == session.cid: accLevel = Const.AL_OWNER if session.cid == Const.OID_ADMIN: accLevel = Const.AL_ADMIN #@log.debug('access rights', accLevel, cmdObj.accLevel) if cmdObj.accLevel > accLevel: raise ige.SecurityException('Access denied - low access level.') # create transaction (TODO - cache it!) tran = Transaction(self, session.cid, session) # invoke command on it result = cmdObj(*(tran, obj) + args) # commit transaction tran.commit() #@log.debug('result', result) # session messages #@log.debug('Messages:', session.messages.items()) messages = session.messages.items() session.messages.clear() #@log.debug("Execution time", time.time() - startTime) return result, messages
def parseTransactionsXML(transXML): root = ET.XML(transXML) transList = [] for transElem in root.iter(bt + "transaction"): transaction = Transaction(transElem.find(bt + "auth-seq").text) amtString = transElem.find(bt + "amount").text transaction.amount = float(amtString) invoice = transElem.find(bt + "invoice") if invoice is not None: transaction.invoice = invoice.text job = transElem.find(bt + "job-code") if job is not None: transaction.job = job.text oldInvoice = transElem.find(bt + "original-invoice") if oldInvoice is not None: transaction.oldInvoice = oldInvoice.text custElem = transElem.find(bt + "customer") transaction.cust = parseCustomerElement(custElem) transList.append(transaction) return transList
def serveForever(self): """The only function any user of this class needs to run! Receives, acts on, and responds to TCP control packets as the Mini-T (or similar hardware) would. Packets are received by the main thread and queued for action and response by a second thread. """ chipsLog.info("Dummy Hardware TCP Server starting") # This starts the packet "act and respond" handler thread self.start() try: chipsLog.debug("Awaiting connection...") self._connectedSocket, addr = self._socket.accept() # TCP chipsLog.debug("Client connection accepted.") except KeyboardInterrupt: chipsLog.warning("\nKeyboard interrupt (ctrl-c) received whilst waiting for a TCP connection") self._stopServingAndJoinThreads() return while not self.stopServing: try: data = self._connectedSocket.recv(DummyHardware.SOCKET_BUFFER_SIZE) # TCP except KeyboardInterrupt: chipsLog.warning("\nKeyboard interrupt (ctrl-c) received whilst waiting for incoming TCP packet") self._stopServingAndJoinThreads() return except: chipsLog.warning("\nException caught whilst waiting for incoming TCP packet") self._stopServingAndJoinThreads() return if not data: chipsLog.debug("TCP socket received an empty packet from " + repr(addr) + ": assuming connection closed.") try: chipsLog.debug("Awaiting new connection...") self._connectedSocket, addr = self._socket.accept() # TCP chipsLog.debug("Client connection accepted.") continue except KeyboardInterrupt: chipsLog.warning("\nKeyboard interrupt (ctrl-c) received whilst waiting for a TCP connection") self._stopServingAndJoinThreads() return chipsLog.debug("\nReceived TCP packet from " + repr(addr)) transaction = Transaction.constructHostTransaction(data, addr) self._transaction_queue.put(transaction) chipsLog.info("Dummy Hardware TCP Server stopping.")
def dispatchRawRequest(self, requestDict, strmOut): """Dispatch a raw request. Dispatch a request as passed from the web server via WSGI. This method creates the request, response, and transaction objects, then runs (via `runTransaction`) the transaction. It also catches any exceptions, which are then passed on to `handleExceptionInTransaction`. """ request = self.createRequestForDict(requestDict) if request: trans = Transaction(application=self, request=request) if trans: request.setTransaction(trans) response = request.responseClass()(trans, strmOut) if response: trans.setResponse(response) self.runTransaction(trans) try: trans.response().deliver() except ConnectionAbortedError as err: trans.setError(err) response.clearTransaction() # release possible servlets on the stack while True: servlet = request.pop() if not servlet: break self.returnServlet(servlet) # get current servlet (this may have changed) servlet = trans.servlet() if servlet: # return the current servlet to its pool self.returnServlet(servlet) if self.setting('LogActivity'): self.writeActivityLog(trans) request.clearTransaction() return trans
def makeConflictingTree(root, pubK, priK, depth): ret = [] if depth > 0: prevOut = root.getOutput(0) prevVal = prevOut.value for i in range(2): tx = Transaction() tx.addInput(root.getHash(), 0) tx.addOutput(prevVal * 0.3 * (i + 1), pubK) signInput(tx, priK, 0) tx.finalize() ret.append(tx) for tx2 in makeConflictingTree(tx, pubK, priK, depth - 1): ret.append(tx2) return ret
def CreateTransaction(receiverAddr, howMuch, owner, wallet): senderAddr = rsa.PublicKey(int(wallet.privateKeyN), int(wallet.privateKeyE)) sender = rsa.PrivateKey(int(wallet.privateKeyN), int(wallet.privateKeyE), int(wallet.privateKeyD), int(wallet.privateKeyP), int(wallet.privateKeyQ)) #privateKeyN = privkey.n #privateKeyP = privkey.p #privateKeyE = privkey.e #privateKeyD = privkey.d #privateKeyQ = privkey.q ammount = 0 #if turn == False: # senderAddr = USER1.pubKey # sender = USER1 #elif turn == True and not USER1 == None: # senderAddr = USER2.pubKey # sender = USER2 #else: # senderAddr = str(recieverentry.get()) Naslovi = [] Naslovi.append(Address(str(receiverAddr), float(howMuch))) ammount = ammount + float(howMuch) a = Transaction( str(senderAddr.n), Naslovi, ammount, hexlify( rsa.sign((f"{str(senderAddr)}{str(Naslovi)}{str(ammount)}{time}" ).encode("utf-8"), sender, "SHA-256")).decode("utf-8")) Speak("API_ADDRESS_NEW", a, client2) client2.close() ret = Transak(data=json.dumps(a, default=lambda o: o.__dict__, sort_keys=False), humanId=owner) ret.save() return
def importDE(file): rows = [] with open(file, mode="r", encoding="utf8") as csv_file: csv_reader = csv.reader(csv_file, delimiter=";") for row in csv_reader: rows.append(row) transacts_list = rows[14:-3] transacts = [] for row in transacts_list: amount_str = ('-') * (row[12] == 'S') + row[11].replace(',', '.') amount = float(amount_str) transact = Transaction(datetime.datetime.strptime(row[0], '%d.%m.%Y'), row[2], row[3], row[8].replace("\n", ""), amount, row[10], '', GK_DE) readExpense(transact) transacts.append(transact) transacts = list(reversed(transacts)) return transacts
def mine_block(self): if self.hosting_node is None: return None last_block = self.__chain[-1] hashed_block = hash_block(last_block) reward_transaction = Transaction('MINING', self.hosting_node, '', MINING_REWARD) copied_transaction = self.__open_transactions[:] for tx in copied_transaction: if not Wallet.verify_transaction(tx): return False copied_transaction.append(reward_transaction) proof = self.proof_of_work() block = Block(len(self.chain), hashed_block, copied_transaction, proof) self.__chain.append(block) self.__open_transactions = [] self.save_data() return block
def read_csv(filename): # function that opens and reads a csv file with open(filename, "r") as file: if file.mode == "r": # checks that file is open in read mode content = read_open_file(filename, file) rows = re.findall( r"(\d{2}\/\d{2}\/\d{4}),([^,]+),([^,]+),([^,]+),([^,]+)\n\b", content) # regex search # that groups data from each column transactions = [] for csv_row in rows: transactions.append( Transaction.from_csv(csv_row) ) # formats data into standard internal transaction # class format logging.info(filename + " has been read and closed.") return transactions
def add_purchase(self, payer, amount, label): self.transactions.append(Transaction(amount, payer, label)) amount_each = amount / self.number_of_members() amount_to_payer = amount - amount_each # Update each member's balance. for member in self.members: if payer == self.members[member]: payer.add(amount_to_payer) continue self.members[member].sub(amount_each) # Find total debt. # TODO Look into better way of updating this value. self.total_debt = 0 for member in self.members: if self.members[member].in_debt(): self.total_debt += self.members[member].balance
def getOrderFromFile(): buyPackage = [] buys = constant.readAll() for order in buys: if order != '' and order != '\n': params = order.split(',') price = params[0] amount = params[1] orderId = params[2] index = params[3] isSpecial = params[4] transaction = Transaction(price, index, amount, orderId, isSpecial) buyPackage.append(transaction) return buyPackage
def GenerateRandomTransactions(self, numberOfTransactions): ''' Generates random transactions Input: numberOfTransactions: Number of transactions to generate ''' for i in range(0, numberOfTransactions): coins = random.randrange(0,50) + random.random() fromUser = random.randrange(0, self.numberOfUsers) toUser = random.randrange(0, self.numberOfUsers) # Ensures the sender is not the receiver if toUser == fromUser: while toUser == fromUser: toUser = random.randrange(0, self.numberOfUsers) newTransaction = Transaction(coins, fromUser, toUser) self.Transactions.append(newTransaction)
def process_accountTransaction(bankNo, monthNow, yearNow): transactions = [] try: bankTransFile = open("file/" + bankNo, "r") for bankTrans in bankTransFile: list = bankTrans.split(',') s = Transaction(list[0], list[1], list[2], list[3], list[4], list[5]) if list[6] == monthNow and list[7] == (yearNow + "\n"): transactions.append(s) bankTransFile.close() return transactions except IOError: print("File not found") return transactions except: print("Unknown error") return transactions
def handle_incoming_message(self, msg: dict): """ Handles incoming messages from the Messenger class in dictionary format. Four types of messages exist: Transactions, Blocks, Sync, and Key messages. :param msg: dict. Message attributes represented as string key value pairs. :return: None """ if msg['type'] == 'Transaction': # if transaction append to tx queue contents = msg['contents'] self.transaction_queue.append(Transaction(contents)) elif msg['type'] == 'Block' and self.genesis_time != 'not set': # if block process and reset mine function if valid msg_dict = json.loads(msg['contents']) incoming_block = Block(msg_dict['block']) leader_id = msg_dict['leader_id'] block_term = int(msg_dict['term']) block_history = json.loads(msg_dict['history']) # print("\nIncoming Block received: \n", incoming_block, block_term, leader_id, '\n incoming term : ', block_term) self.process_incoming_block(block=incoming_block, term=block_term, leader_id=leader_id, block_history=block_history) elif msg['type'] == 'sync': msg_dict = json.loads(msg['contents']) start_time = date_parser.parse(msg_dict['start_time']) self.nodes_online.append(start_time) if len(self.nodes_online) > 3: # print("synched!") self.genesis_time = max(self.nodes_online) print('genesis time = ', self.genesis_time) elif msg['type'] == 'key': msg_dict = json.loads(msg['contents']) sender = msg_dict['sender'] sig = msg_dict['signature'] key_string = msg_dict['key'].encode("utf-8") incoming_public_key = serialization.load_pem_public_key( key_string, backend=default_backend() ) self.all_public_keys[sender] = incoming_public_key self.peer_signatures[sig] = sender
def create_genesis_block(self, node_pool=None): assert len( node_pool ) > 0, "The system cannot have 0 nodes initially during the creation of genesis block" genesis_txn = Transaction(version=0, lock_time=0, coin=100, address=node_pool[0].get_address()) for node in node_pool[1:]: pubkey = node.get_address() genesis_txn.add_output(pubkey, 100) genesis_txn.finalize() return genesis_txn
def make_transaction(self, supplier_key, receiver_key, item_id): # Selection functions for the keys and the item ID selection = input('\nSelect type of key (M/O) for supplier: ') if selection == 'M': index = int(input('There are a total of ' + str(len(self.manufacturers_list)) + ' users. Enter your selection: ')) - 1 supplier_key = self.manufacturers_list[index] elif selection == 'O': index = int(input('There are a total of ' + str(len(self.other_users_list)) + ' users. Enter your selection: ')) - 1 supplier_key = self.other_users_list[index] selection = input('\nSelect type of key (M/O) for receiver: ') if selection == 'M': index = int(input('There are a total of ' + str(len(self.manufacturers_list)) + ' users. Enter your selection: ')) - 1 receiver_key = self.manufacturers_list[index] elif selection == 'O': index = int(input('There are a total of ' + str(len(self.other_users_list)) + ' users. Enter your selection: ')) - 1 receiver_key = self.other_users_list[index] receiver_puk = receiver_key.publickey().exportKey("PEM").decode('utf-8') item_id = input('Enter the ID of the tracked item: ') # Acquiring the details for the transactions supplier_puk = supplier_key.publickey() timestamp = date.datetime.now() # Generating the message text and the signature message = str(supplier_puk.exportKey("PEM").decode('utf-8')) + \ str(receiver_puk) + item_id + str(timestamp) hash_message = SHA256.new(message.encode('utf-8')) supplier_prk = RSA.import_key(supplier_key.exportKey("DER")) signature = pkcs1_15.new(supplier_prk).sign(hash_message) # Creating a new transaction new_transaction = Transaction( supplier_puk, receiver_puk, item_id, timestamp, signature) self.utxo_array.append(new_transaction)
def processTurnInternal(self): log.message("--- TURN PROCESSING STARTED ---") # commit player's changes #if ige.igeRuntimeMode: # self.db.checkpoint() # get turn phases turn, turnspec, data = self.getTurnData() log.debug('Processing turn %d' % turn) tran = Transaction(self, OID_ADMIN, Session(0)) counter = 0 # phases for objIDs, phases in turnspec: # process all objects for objID in objIDs: # process all phases for phase in phases: todo = [objID] t0 = time.time() cnt0 = self.db.statCount log.debug('Processing turn %d phase %d.%s' % (turn, objID, phase)) while todo: tmpID = todo.pop(0) #@log.debug('Processing obj', tmpID) try: counter += 1 obj = self.db[tmpID] method = getattr( self.cmdPool[obj.type], 'process%sPhase' % phase, ) result = method(tran, obj, data) if result: todo.extend(result) obj = None except: log.warning('Cannot execute %s on %d' % (phase, tmpID)) log.debug('STATS -- time: %.3f sec, db accesses: %d' % (time.time() - t0, tran.db.statCount - cnt0)) log.message('Processed commands:', counter) # turn processing has finished self.turnFinished() log.message("--- TURN PROCESSING FINISHED ---")
def processTurn(self, sid, turns = 1): session = self.clientMngr.getSession(sid) if session.login != Const.ADMIN_LOGIN: raise ige.SecurityException('You cannot issue this command.') for turn in xrange(turns): log.message("--- TURN PROCESSING STARTED ---") # commit player's changes #if ige.igeRuntimeMode: # self.db.checkpoint() # get turn phases turn, turnspec, data = self.getTurnData(sid)[0] log.debug('Processing turn %d' % turn) tran = Transaction(self, session.cid, session) counter = 0 # phases for objIDs, phases in turnspec: # process all objects for objID in objIDs: # process all phases for phase in phases: todo = [objID] t0 = time.time() cnt0 = self.db.statCount log.debug('Processing turn %d phase %d.%s' % (turn, objID, phase)) while todo: tmpID = todo.pop(0) #@log.debug('Processing obj', tmpID) try: counter += 1 obj = self.db[tmpID] method = getattr(self.cmdPool[obj.type], 'process%sPhase' % phase,) result = method(tran, obj, data) if result: todo.extend(result) obj = None except: log.warning('Cannot execute %s on %d' % (phase, tmpID)) log.debug('STATS -- time: %.3f sec, db accesses: %d' % (time.time() - t0, tran.db.statCount - cnt0)) log.message('Processed commands:', counter) # turn processing has finished self.turnFinished(sid) log.message("--- TURN PROCESSING FINISHED ---") return 1, None
def _makeAndRunTransaction(self, requestsList): """Constructs, runs and then returns a completed transaction from the given requestsList requestsList: a list of TransactionElements (i.e. requests from client to the hardware). Notes: _makeAndRunTransaction will automatically prepend one byte-order transaction. """ # Construct the transaction and serialise it - we prepend four byte-order transactions in # order to ensure we meet minimum Ethernet payload requirements, else funny stuff happens. transaction = Transaction.constructClientTransaction(requestsList, self._hostAddr) transaction.serialiseRequests() chipsLog.debug("Sending packet now."); try: # Send the transaction self._socketSend(transaction) except socket.error, socketError: raise ChipsException("A socket error occurred whilst sending the IPbus transaction request packet:\n\t" + str(socketError))
def upgrade(self): oldStatus = self.status self.status = GS_MAINT tran = Transaction(self, OID_ADMIN) # used objects objIDs = {} for objID in self.db.keys(): objIDs[objID] = None del objIDs[1] del objIDs[OID_ADMIN] del objIDs[OID_I_LOGIN2OID] del objIDs[OID_I_NAME2OID] # stats types = {} typesMin = {} typesMax = {} typesSum = {} # upgrade all objects in database # and collect all not referenced objects for id in self.db.keys(): try: obj = self.db[id] except: log.warning("Cannot upgrade object", id, "no such id in db") if not isinstance(obj, IDataHolder): #@log.debug('Upgrade - skiping', id) continue #@log.debug('Upgrade - upgrading', id, obj.type) types[obj.type] = types.get(obj.type, 0) + 1 size = self.db.getItemLength(id) typesMin[obj.type] = min(typesMin.get(obj.type, 1000000), size) typesMax[obj.type] = max(typesMax.get(obj.type, 0), size) typesSum[obj.type] = typesSum.get(obj.type, 0) + size if self.cmdPool.has_key(obj.type): try: self.cmdPool[obj.type].upgrade(tran, obj) except Exception, e: log.warning("Cannot upgrade object", id) references = self.cmdPool[obj.type].getReferences(tran, obj) if references: for tmpID in references: if tmpID in objIDs: del objIDs[tmpID]
def isValidTx(tx, utxoPool, pks): verifyTransaction = Transaction() #* Returns true if #* (1) all outputs claimed by tx are in the current UTXO pool, #* (4) all of tx’s output values are non-negative, and txOutSum = 0 for txInputInd in range(0, tx.getOutputLen()): txOut = tx.getOutput(txInputInd) txOutValue = txOut.value if txOutValue is None and not utxoPool.contains( txOutValue) and txOutValue < 0: return False else: txOutSum += txOutValue verifyTransaction.addOutput(txOut.value, txOut.address) #* (3) no UTXO is claimed multiple times by tx, meaning that an input cannot occur twice inputTracker = set() #* (2) the signatures on each input of tx are valid, #* (5) the sum of tx’s input values is greater than or equal to the sum of its output values; and false otherwise. txInSum = 0 for txInputInd in range(0, tx.getInputLen()): txIn = tx.getInput(txInputInd) prevTxOut = utxoPool.search(txIn.prevTxHash, txIn.outputIndex) if prevTxOut is None: return False if (txIn.prevTxHash, txIn.signature) in inputTracker: return False else: inputTracker.add((txIn.prevTxHash, txIn.signature)) verifyTransaction.addInput(txIn.prevTxHash, txIn.outputIndex) m = hashlib.sha256() m.update(str.encode( verifyTransaction.getRawDataToSign(txInputInd))) hm = int(m.hexdigest(), 16) #HM is same, pk is correct as it is passed in so signatures should match if not verify(pks[txInputInd], txIn.signature, hm): return False if prevTxOut.value is None or prevTxOut.value < 0: return False else: txInSum += prevTxOut.value return (txInSum >= txOutSum)
def parse_file(self, fname=""): if not fname: print("Empty filename!") return print("Parsing file: {}".format(fname)) f = open(fname) fout = open(fname.replace(".csv", "_parsed.csv"), "w+") lines = f.readlines() saved_line = "" for l in lines: match = re.search("^[0-9+]", l) if match: if saved_line: tr = Transaction(text=saved_line) self.transactions.append(tr) fout.write(str(tr) + "\n") if tr.to_iban in self.ibans or\ tr.from_iban in self.ibans: self.f_iac.write(str(tr) + "\n") else: self.f_agg.write(str(tr) + "\n") clean_line = "" ok_to_stripp = 0 for c in l.strip(): oc = c if c == "\"": ok_to_stripp += 1 continue if ok_to_stripp % 2 == 1: if c == ".": continue if c == ",": oc = "." clean_line += oc saved_line = clean_line.replace(",,,", ",*,*,") elif l.startswith(",,,"): saved_line += l.strip() else: continue f.close() fout.close()
def Parse(self, transaction, sno): withdrawal = 0.00 deposit = 0.00 closingBalance = 0.00 if (transaction[4].strip().replace('-', '').replace(',', '').replace( 'Cr', '') != ''): withdrawal = float(transaction[4].replace('-', '').replace( ',', '').replace('Cr', '')) if (transaction[5].strip().replace('-', '').replace(',', '').replace( 'Cr', '') != ''): deposit = float(transaction[5].replace('-', '').replace( ',', '').replace('Cr', '')) if (transaction[6].strip().replace('-', '').replace(',', '').replace( 'Cr', '') != ''): closingBalance = float(transaction[6].replace('-', '').replace( ',', '').replace('Cr', '')) return Transaction(sno, Utility.GetDate(transaction[1]), '', transaction[2], transaction[3], Utility.GetDate(transaction[7]), withdrawal, deposit, closingBalance, '', '', '1')
def transfer_money(self, account_number): #transfers money try: to_account_number = int( input("\nEnter the account number to transfer ")) cur.execute("select * from accounts where accountnumber=" + str(to_account_number)) cur.fetchone() if cur.rowcount != 0: if account_number != to_account_number: amount = float(input("Enter the amount to transfer ")) if amount > float(0): cur.execute( "select balance,accounttype from accounts where accountnumber=" + str(account_number)) row = cur.fetchone() balance = float(row[0]) account_type = row[1] if amount > balance: print( "Transfer failed. Insufficient balance. Your balance is ₹" + str(balance)) elif account_type.upper( ) == "CA" and balance - amount < float(5000): print( "Transfer failed. You should maintain a minimum balance of ₹5000 \nYour balance is ₹" + str(balance) + "\nYou can Transfer/Withdraw a maximum of ₹" + str(balance - float(5000)) + " as of now.") else: balance = Transaction().transfer( account_number, to_account_number, amount) print("Transfer success.\nYour balance: ₹" + str(balance)) else: print("Invalid amount") else: print("You cannot transfer to your own account") else: print("Invalid account number") except ValueError: print("Invalid value")
def Deposit(): global account_number account_search = False access_account = int(input("\nEnter your account number Deposit: ")) #accounts for i in new_accounts: if access_account == i.account_number: i.print_balance() old_balance = i.balance i.Deposit() i.new_balance() #Creating transaction object and Storing info in transaction list type_of_transaction = 'Deposit' new_balance = i.balance #vert important, uses the current account number rather than the global account number for transaction object account_number = access_account new_transaction = Transaction(account_number, type_of_transaction, old_balance, new_balance) Transactions.append(new_transaction) account_search = True if account_search == False: print( "\nThe number you entered did not match an account number on file. Please return to main console and try again. " ) main()
def __init__(self, transactions, parser, statementTransType, ttMapFName, atMapFName): self.transactions = [] Transaction.PopulateMap(ttMapFName, atMapFName) for i in range(len(transactions)): transaction = parser.Parse(transactions[i], i) if (transaction is None): continue transList = [] transType = type(transaction) if (type(transaction) is not list): transList.append(transaction) else: transList = transaction for t in transList: if (t.value[TTEnum.Account] == ''): t.value[TTEnum.Account] = statementTransType self.transactions.append(t) self.statementTransType = statementTransType
def readNewCSVObject(file): with open(file, mode="r") as csv_file: csv_reader = csv.reader(csv_file, delimiter=";") transacts = [] for index, row in enumerate(csv_reader): if index > 3 and ( row[2].find("PAYPAL") != -1 or row[2].find("SCHMIT LORIS CARLO, 130") != -1 or row[2].find("Loris Schmit, DE22660908000007898649") != -1 or row[2].find("RETRAIT BANCOMAT") != -1 or row[2].find("DECOMPTE VISA") != -1): comma_pos = row[2].rfind(",") sender = row[2][:comma_pos].replace(",", "") reference = row[2][comma_pos + 2:].replace(",", "") amount = row[3].replace(",", ".") date = datetime.datetime.strptime(row[0], "%d/%m/%Y") transact = Transaction(date, row[1].replace(",", ""), sender, reference, amount, row[4], '', CC_LUX) transacts.append(transact) transacts = list(reversed(transacts)) return transacts
def process_transaction_entry(self): """ Processes a transaction entry. Method called by button on window :return: None """ action_object = None stock_name = self.enter_transaction_stock_radio_value.get() price = self.enter_transaction_window_price_entry.get() stock_quanity = self.enter_transaction_window_share_entry.get() date_to_save = datetime.strptime(self.enter_transaction_window_date_entry.get(), "%m-%d-%Y") if self.action_for_transaction_stringVar_object.get() == 'buy': action_object = BuyTransaction() else: action_object = SellTransaction() transactions_to_save = Transaction(stock_name, date_to_save, action_object, price, stock_quanity) database = Database() database.save_transaction(transactions_to_save) self.enter_transaction_window_object.destroy() self.adjust_status("New Transaction Added")
def validate(self, block, previous_block): try: assert_valid(previous_block.hashed == block.previous_block_hash, "prv bloc hash") assert_valid(previous_block.block_number + 1 == block.block_number, "block num") for txn in block.txns: nTxn = Transaction(txn.sender_public_key, txn.reciever_public_key, txn.product_hash, txn.hashed) assert_valid(nTxn.authenticated, "auth") assert_valid(nTxn.validated, "valid") assert_valid( self.generate_txns_hash(block) == block.hashed, "hash") assert_valid( self.gen_hash(block.hashed, block.nonce) == block.pow, "pow") return True except Exception as e: print str(e) return False
def Parse(self, transaction, sno): #Date, empty, empty, empty, empty, empty, empty, action, empty, empty, account, empty, unit, empty, empty, price #sno if (transaction[0].strip() == ''): return date = Utility.GetDate(transaction[0]) transType = '' description = transaction[10] refNo = '' action = transaction[7] deposit = withdrawal = 0 if (action.lower() == 'buy'): deposit = float(transaction[12]) else: withdrawal = -float(transaction[12]) closingBalance = 0 account = transaction[10] price = str(self.CalPrice(transaction[15])) return Transaction(sno, date, transType, description, refNo, date, withdrawal, deposit, closingBalance, action, account, price)
def build_transactions_mastercard(transactions, year): final_transactions = [] i = 0 while i < len(transactions): line = transactions[i].split(' ') t_date = ' '.join(line[:2]) t_date = ' '.join([t_date, year]) description = ' '.join(line[4:]) amount = transactions[i + 1] amount = amount.replace('$', '') amount = invert_negatives(amount) key = get_category_key(description) sub, main = set_category(key) transaction = Transaction(t_date, description, amount, 'Mastercard', sub, main) i = i + 2 final_transactions.append(transaction) return final_transactions
def archive(self, *args): d = wx.TextEntryDialog(self, "Archive transactions before what date (mm/dd/yy)?", "Archive Date") if d.ShowModal() == wx.ID_OK: date = Date(d.GetValue()) else: date = None d.Destroy() if not date: return archive = Asset() newcb_starttransaction = Transaction() newcb_starttransaction.amount = 0 newcb_starttransaction.payee = "Starting Balance" newcb_starttransaction.memo = "Archived by PyAsset" newcb_starttransaction.cleared = 1 newcb_starttransaction.date = date newcb = Asset() newcb.filename = self.cur_transaction.filename newcb.name = self.cur_transaction.name newcb.append(newcb_starttransaction) archtot = 0 for transaction in self.cur_transaction: if transaction.date < date and transaction.cleared: archive.append(transaction) archtot += transaction.amount else: newcb.append(transaction) newcb_starttransaction.amount = archtot self.cur_transaction = newcb while 1: d = wx.FileDialog(self, "Save Archive As", "", "", "*.qif", wx.SAVE) if d.ShowModal() == wx.ID_OK: fname = d.GetFilename() dir = d.GetDirectory() d.Destroy() if fname: break archive.write_qif(os.path.join(dir, fname)) self.redraw_all(-1) self.edited = 1 return
def CreateNewAddress(howMuch, publicKey): global turn, USER1, USER2, CURRENTUSER ammount = 0 #if turn == False: # receiverAddr = USER1.pubKey # reciever = USER1 #elif turn == True and not USER1 == None: # receiverAddr = USER2.pubKey # receiver = USER2 #else: # receiverAddr = str(recieverentry.get()) Naslovi = [] Naslovi.append(Address(str(publicKey.n), float(howMuch))) ammount = ammount + float(howMuch) Speak("API_ADDRESS_NEW", Transaction("coinbase", Naslovi, ammount, str(0)), client2) client2.close() return
def Parse(self, transaction, sno): withdrawal = 0.00 deposit = 0.00 closingBalance = 0.00 if (transaction[6].strip() == 'Cr'): deposit = float(transaction[5]) elif (transaction[6].strip() == 'Dr'): withdrawal = float(transaction[5]) if (deposit < 0): withdrawal = -deposit deposite = 0.0 elif (withdrawal < 0): deposit = -withdrawal withdrawal = 0.0 closingBalance = transaction[8] #sno, date, transtype, narration, refno, valuedate, withdrawal, deposit, closingbalance, action, account, price return Transaction(sno, Utility.GetDate(transaction[1]), '', transaction[2], transaction[3], Utility.GetDate(transaction[0]), withdrawal, deposit, closingBalance, '', '', '1')
def handle_incoming_message(self, msg: dict): """ Handles incoming messages from the Messenger class in dictionary format. :param msg: dict. Message attributes represented as string key value pairs. :return: None """ if msg['type'] == 'Transaction': # if transaction append to tx queue self.transaction_queue.append(Transaction(msg['contents'])) elif msg[ 'type'] == 'Block': # if block process and reset mine function if valid incoming_block = Block(msg['contents']) print("\nIncoming Block received: \n", "Index: ", incoming_block.index, '\n', "Previous Hash: ", incoming_block.prevHash, '\n', "Hash: ", incoming_block.hash, '\n') # Nodes must always mine on the longest chain, so any mining in progress needs to be reset self.received_blocks.append(incoming_block) self.reset_mine_function = True print('reset mining true')
def dispatchRawRequest(self, requestDict, strmOut): """Dispatch a raw request. Dispatch a request as passed from the Adapter through the AppServer. This method creates the request, response, and transaction object, then runs (via `runTransaction`) the transaction. It also catches any exceptions, which are then passed on to `handleExceptionInTransaction`. """ request = self.createRequestForDict(requestDict) if request: trans = Transaction(application=self, request=request) if trans: request.setTransaction(trans) response = request.responseClass()(trans, strmOut) if response: trans.setResponse(response) self.runTransaction(trans) try: trans.response().deliver() except ConnectionAbortedError, err: trans.setError(err) response.clearTransaction() # release possible servlets on the stack while 1: servlet = request.pop() if not servlet: break self.returnServlet(servlet) servlet.resetKeyBindings() # get current servlet (this may have changed) servlet = trans.servlet() if servlet: # return the current servlet to its pool self.returnServlet(servlet) if self.setting('LogActivity'): self.writeActivityLog(trans) request.clearTransaction()
def GeneratePercentInvalidTransactions(self, percent=0.05): ''' To be used as a secondary call to GenerateValidTransactions to generate a percentage of those transactions as invalid transactions Input: percent: Percentage of valid transactions to be invalid transactions. Initially set to 5% ''' # TODO: Integrate this into the main program # Generate some number of transactions proportional to a percentage of the # current transactions numberOfTransactions = math.floor(len(self.Transactions) * percent) for i in range(0, numberOfTransactions): fromUser = random.randrange(0, self.numberOfUsers) toUser = random.randrange(0, self.numberOfUsers) # Insures that the To address is not the same as the From address if toUser == fromUser: while toUser == fromUser: toUser = random.randrange(0, self.numberOfUsers) # Insures that the account balance is not empty if self.modifiedAccountList.AccountIsEmpty(fromUser): while self.modifiedAccountList.AccountIsEmpty(fromUser): fromUser = random.randrange(0, self.numberOfUsers) accountBalance = self.modifiedAccountList.AccountBalance(fromUser) # Coins in transaction will be between the accountBalance + 1 to accountBalance + 1 + up to the account balance in 25% intervals coins = random.randrange(math.floor(accountBalance)+1, math.ceil(accountBalance + 1 + (random.randrange(1,4)/4)*accountBalance)) # Verifies that the transaction is invalid. If not, tries again while (accountBalance - coins) >= 0: coins = random.randrange(math.floor(accountBalance)+1, math.ceil(accountBalance + 1 + (random.randrange(1,4)/4)*accountBalance)) newTransaction = Transaction(coins, fromUser, toUser) # Adds invalid transaction to transaction list self.Transactions.append(newTransaction)
class Analyses: """Perform additional analyses on the Portfolios and stocks.""" pass if __name__ == "__main__": print('pf - Portfolio Version', VERSION) DATA = Database() PRICES = Prices(DATA) SECS = Securities(DATA) PRICES.secs = SECS SECS.prices = PRICES # print('PRICES') # print(PRICES) # print('SECS') print(SECS) TRANSACTION = Transaction(DATA, SECS, PRICES) PORTFOLIO = Portfolio('All', TRANSACTION, PRICES, SECS) MONEY = Money(DATA, PORTFOLIO) TRANSACTION.money = MONEY UI = UI(SECS, PORTFOLIO, PRICES, TRANSACTION, MONEY) pickle.dump(PORTFOLIO, open('portfolio.p', 'wb')) # print('PRICES') # print(PRICES) # print('SECS') # print(SECS) # print('TRANSACTIONS') print(TRANSACTION) DATA.close()
def testMethods(self): genesis = Block(b'', scroogePubKey) genesis.finalize() blockChain = BlockChain(genesis) blockHandler = BlockHandler(blockChain) # Genesis block test self.assertEqual(genesis.getHash(), blockChain.getMaxHeightBlock().getHash(), \ 'genesis should be max height block') self.assertEqual(blockChain.getMaxHeightBlock(), genesis, \ 'genesis should be max height block') self.assertEqual(len(blockChain.getMaxHeightUTXOPool().getAllUTXO()), 1, \ 'UTXOPool should have one output') self.assertEqual(len(blockChain.getTransactionPool().getTransactions()), 0, \ 'transaction pool should be empty') # Spend the genesis coinbase transaction in many outputs tx = Transaction() tx.addInput(genesis.getCoinbase().getHash(), 0) numGenOuts = int(COINBASE) for i in range(numGenOuts): tx.addOutput(1.0, scroogePubKey) signInput(tx, scroogePriKey, 0) tx.finalize() # Add one transaction test. No block has been added. blockHandler.processTx(tx) self.assertEqual(blockChain.getMaxHeightBlock(), genesis, \ 'genesis should be max height block') self.assertEqual(len(blockChain.getMaxHeightUTXOPool().getAllUTXO()), 1, \ 'UTXOPool should have one output') self.assertEqual(len(blockChain.getTransactionPool().getTransactions()), 1, \ 'transaction pool should have one entry') self.assertIsNotNone(blockChain.getTransactionPool().getTransaction(tx.getHash()), \ 'tx should be in txPool') # Build out the chain depth = 15; chainedBlocks = [] for i in range(depth): # Spend the new outputs, one tx per block tx2 = Transaction() tx2.addInput(tx.getHash(), i) tx2.addOutput(1.0, scroogePubKey) signInput(tx2, scroogePriKey, 0) tx2.finalize() blockHandler.processTx(tx2); chainedBlocks.append(blockHandler.createBlock(scroogePubKey)) # Deep chain test self.assertIsNotNone(chainedBlocks[i], 'ith block should exist') self.assertEqual(blockChain.getMaxHeightBlock(), chainedBlocks[i], \ 'ith block should be max height') self.assertEqual(len(blockChain.getMaxHeightUTXOPool().getAllUTXO()), numGenOuts + i + 1, \ 'wrong number UTXOs when i = ' + str(i)) self.assertEqual(len(blockChain.getTransactionPool().getTransactions()), 0, \ 'txPool should be empty') # Remember the current max height block maxBlockBefore = blockChain.getMaxHeightBlock() # Make another block on the deepest block that should still work sideBlock = Block(chainedBlocks[depth - CUT_OFF_AGE - 1].getHash(), scroogePubKey) sideBlock.finalize() retVal = blockChain.addBlock(sideBlock) # Add valid side chain block test self.assertTrue(retVal, 'side block should have been added') self.assertEqual(blockChain.getMaxHeightBlock(), maxBlockBefore, \ 'max height block should not have changed') # Make another block that is too deep tooDeep = Block(chainedBlocks[depth - CUT_OFF_AGE - 2].getHash(), scroogePubKey) tooDeep.finalize() retVal2 = blockChain.addBlock(tooDeep) # Too deep test self.assertFalse(retVal2, 'too deep block should not be added') # Build on the side chain prevBlock = sideBlock for i in range(CUT_OFF_AGE - 1): # Spend the previous coinbase transaction tx2 = Transaction(); tx2.addInput(prevBlock.getCoinbase().getHash(), 0) tx2.addOutput(10.0, scroogePubKey) signInput(tx2, scroogePriKey, 0) tx2.finalize(); newBlock = Block(prevBlock.getHash(), scroogePubKey) newBlock.addTransaction(tx2) newBlock.finalize() retVal3 = blockChain.addBlock(newBlock) self.assertTrue(retVal3, 'side blocks should be added') prevBlock = newBlock # The side chain should be the same length as the previous chain # and so the max height block should not have changed. self.assertEqual(blockChain.getMaxHeightBlock(), maxBlockBefore, \ 'max height block should not be changed') # Now add another to the side chain, making it the new highest # Spend the previous coinbase transaction tx3 = Transaction() tx3.addInput(prevBlock.getCoinbase().getHash(), 0) tx3.addOutput(10.0, scroogePubKey) signInput(tx3, scroogePriKey, 0) tx3.finalize() newBlock = Block(prevBlock.getHash(), scroogePubKey) newBlock.addTransaction(tx3) newBlock.finalize() retVal3 = blockChain.addBlock(newBlock) self.assertTrue(retVal3, 'block should be added') self.assertNotEqual(blockChain.getMaxHeightBlock(), maxBlockBefore, \ 'max height block should be changed') self.assertEqual(blockChain.getMaxHeightBlock(), newBlock, \ 'max height block should be the new block')
import Etos from Transaction import Transaction from TimeUtil import * from UrlUtil import xmlLoader from Dumper import * sim = Etos.Simulation(startTime=float(strdt("0:00:00"))) sim.initialize() transactionNode = xmlLoader("XML/subtrans.xml") t = Transaction(transactionNode, sim) sim.activate(t, t.run()) sim.simulate(until=int(DayTime(days=1)))
def testHandleTxsManyNonconflictingTxs(self): many = 30 baseTx = Transaction() for i in range(many): baseTx.addOutput(1.0, scroogePubK) baseTx.finalize() # Add these outputs to the pool anyway pool = UTXOPool() addTx(pool, baseTx) # Make a bunch of transactions that depend on that one. possibleTxs = [] for i in range(many): tx = Transaction() tx.addInput(baseTx.getHash(), i) tx.addOutput(0.5, alicePubK) signInput(tx, scroogePrivK, 0) tx.finalize() possibleTxs.append(tx) handler = MaxFeeTxHandler(pool) ret = handler.handleTxs(possibleTxs) self.assertEquals(len(ret), many, 'should return all transactions')
def read_qif(self, filename, readmode='normal'): if readmode == 'normal': # things not to do on 'import': self.filename = filename name = filename.replace('.qif', '') self.name = os.path.split(name)[1] mffile = open(filename, 'r') lines = mffile.readlines() mffile.close() transaction = Transaction() input_type = lines.pop(0) for line in lines: input_type, rest = line[0], line[1:].strip() if input_type == "D": transaction.setdate(rest) blank_transaction = False elif input_type == "T": transaction.setamount(rest) blank_transaction = False elif input_type == "P": transaction.setpayee(rest) blank_transaction = False elif input_type == "C": transaction.setcleared(rest) blank_transaction = False elif input_type == "N": transaction.setnumber(rest) blank_transaction = False elif input_type == "L": transaction.setcomment(rest) blank_transaction = False elif input_type == "M": transaction.setmemo(rest) blank_transaction = False elif input_type == "A": total_payee = transaction.getpayee() + " " + rest transaction.setpayee(total_payee) blank_transaction = False elif input_type == "^": if not blank_transaction: self.transactions.append(transaction) self.total = self.total + transaction.getamount() transaction = Transaction() blank_transaction = True else: print "Unparsable line: ", line[:-1] self.sort() return
def testHandleTxsMessy(self): # Make the initial pool pool = UTXOPool() # Make the base transaction and put in pool baseTx = Transaction() baseTx.addOutput(10, scroogePubK) baseTx.addOutput(10, scroogePubK) baseTx.finalize() addTx(pool, baseTx) # Transaction A txA = Transaction() txA.addInput(baseTx.getHash(), 0) # 10 in, conflicts with B and C txA.addOutput(7, scroogePubK) # 7 out, fee = 3 signInput(txA, scroogePrivK, 0) txA.finalize() # Transaction B txB = Transaction() txB.addInput(baseTx.getHash(), 0) # 10 in, conflicts with A and C txB.addOutput(9, scroogePubK) # 9 out, fee = 1 signInput(txB, scroogePrivK, 0) txB.finalize() # Transaction C txC = Transaction() txC.addInput(baseTx.getHash(), 0) # 10 in, conflicts with A and B txC.addInput(baseTx.getHash(), 1) # 10 more in, conflicts with D txC.addOutput(5, scroogePubK) txC.addOutput(14, scroogePubK) # 19 out, fee = 1 signInput(txC, scroogePrivK, 0) signInput(txC, scroogePrivK, 1) txC.finalize() # Transaction D txD = Transaction() txD.addInput(baseTx.getHash(), 1) # 10 in, conflicts with C txD.addOutput(9, scroogePubK) # 9 out, fee = 1 signInput(txD, scroogePrivK, 0) txD.finalize() # Transaction E txE = Transaction() txE.addInput(txA.getHash(), 0) # 7 in, from A txE.addOutput(6, scroogePubK) # 6 out, fee = 1 signInput(txE, scroogePrivK, 0) txE.finalize() # Transaction F txF = Transaction() txF.addInput(txC.getHash(), 0) # 5 in, from C txF.addOutput(4, scroogePubK) # 4 out, fee = 1 signInput(txF, scroogePrivK, 0) txF.finalize() # Transaction G txG = Transaction() txG.addInput(txB.getHash(), 0) # 9 in, from B txG.addInput(txC.getHash(), 1) # 14 in, from C txG.addOutput(8, scroogePubK) # 8 out, fee = 15 signInput(txG, scroogePrivK, 0) signInput(txG, scroogePrivK, 1) txG.finalize() # Transaction H txH = Transaction() txH.addInput(baseTx.getHash(), 0) # 10 in txH.addOutput(4, scroogePubK) # 4 out, fee = 6 signInput(txH, alicePrivK, 0) # But invalid, since wrong signature txH.finalize() # Transaction I txI = Transaction() txI.addInput(baseTx.getHash(), 2) # no such input, so invalid txI.addOutput(4, scroogePubK) # 4 out, fee = NA signInput(txI, scroogePrivK, 0) txI.finalize() # Transaction J txJ = Transaction() txJ.addInput(txI.getHash(), 0) # 4 in (if txI were valid) txJ.addOutput(3, scroogePubK) # 3 out, fee = 1 signInput(txJ, scroogePrivK, 0) txJ.finalize() # Make the proposed transaction list proposedTxs = [txA, txB, txC, txD, txE, txF, txG, txH, txI, txJ] handler = MaxFeeTxHandler(pool) acceptedHashes = sorted([tx.getHash() for tx in handler.handleTxs(proposedTxs)]) expectedHashes = sorted([tx.getHash() for tx in [txA, txD, txE]]) self.assertEqual(acceptedHashes, expectedHashes, 'wrong set') # Make another proposed transaction list proposedTxs = [txB, txD, txH, txC, txF, txG, txI, txA, txE, txJ] handler = MaxFeeTxHandler(pool) acceptedHashes = sorted([tx.getHash() for tx in handler.handleTxs(proposedTxs)]) self.assertEqual(acceptedHashes, expectedHashes, 'wrong set') # Make another proposed transaction list proposedTxs = [txC, txJ, txF, txD, txB, txE, txG, txH, txI, txA] handler = MaxFeeTxHandler(pool) acceptedHashes = sorted([tx.getHash() for tx in handler.handleTxs(proposedTxs)]) self.assertEqual(acceptedHashes, expectedHashes, 'wrong set')
def execute(self, sid, command, oid, *args): #@startTime = time.time() log.debug('execute', sid, oid, command, args) # check client id session = self.clientMngr.getSession(sid) if not session.cid: # check if real id exists try: cid = self.db[OID_I_LOGIN2OID].get(session.login, None) except AttributeError: raise SecurityException('Not logged in.') log.debug('Adding cid to session', cid) if not cid: # no real id #@log.debug('Raising exception NoAccountException') raise NoAccountException('No game account exists.') session.cid = cid # validate client if not self.validateClient(session): raise GameException('Wrong version of client.') # notify object, that player has logged in player = self.db[cid] self.cmdPool[player.type].loggedIn(Transaction(self), player) # check game status (admin is allowed anytime) if self.status != GS_RUNNING and session.cid != OID_ADMIN: raise ServerStatusException(self.status) # check existence of the commander if not self.db.has_key(session.cid): raise GameException('This player does not exist. He/she could lose.') # update client's liveness session.touch() # find correct object type try: obj = self.db[oid] except KeyError: raise NoSuchObjectException('Object %d does not exist.' % oid) cmdObj = getattr(self.cmdPool[obj.type], command) # TODO check access level if not hasattr(cmdObj, 'public') or not cmdObj.public: raise SecurityException('Access denied - method is not public.') # get acces level of the commander accLevel = AL_NONE if obj.owner == session.cid: accLevel = AL_OWNER if session.cid == OID_ADMIN: accLevel = AL_ADMIN # TODO delete #tmpAL = self.getAccRights(obj, session.cid) #if tmpAL > accLevel: # accLevel = tmpAL #@log.debug('access rights', accLevel, cmdObj.accLevel) if cmdObj.accLevel > accLevel: raise SecurityException('Access denied - low access level.') # create transaction (TODO - cache it!) tran = Transaction(self, session.cid, session) # invoke command on it result = apply(cmdObj, (tran, obj) + args) # commit transaction tran.commit() #@log.debug('result', result) # session messages #@log.debug('Messages:', session.messages.items()) messages = session.messages.items() session.messages.clear() #@log.debug("Execution time", time.time() - startTime) return result, messages
#!/usr/bin/env python3 import Etos from Transaction import Transaction, EntityFactory from TimeUtil import * from UrlUtil import xmlLoader import Model EntityFactory.registerModule(Model) sim = Etos.Simulation(startTime=float(strdt("0:00:00"))) sim.initialize() transactionNode = xmlLoader("XML/gastrans.xml#transaction[@id='starter']") t = Transaction(transactionNode, sim) sim.activate(t, t.run(), at = 0) sim.simulate(until=int(DayTime(days=1))) #for transaction in sim.tanking.keys(): # print("{0}:mean={1.mean}".format(transaction,sim.tanking[transaction]),file=sys.stderr)
b'N1B1X4NgoMSB177DjnoGMckX1r8A4jrvSDDqymyqQxsBHvYrMuzdLmNql8uHW\nSPp1HnKYyaOJGEW' + \ b'aevQmv2Hb0uu53gxWEvAEQUYJt0QFNKECQQC9KQfwM9FamgQR\niPAQLOCEAGIEr9a/zHjR9IkVfzT' + \ b'88zyMUNnnn8xBM96kDfpVKR5ge/Ahja179i9G\nG1jCFNGRAkEA8ea9mCOGIo4osriiM6/pRZn+zmD' + \ b'cQDhV9s0CTMtlJvxykVO18EQs\nWlHJpmWQqAmn4d8TM1xxJrf7acOcdwO8swJATsgq/TinpeNldGQ' + \ b'jD6mRLIj4Sdlu\nSF2BqHf/LAvZ5svrWMlHp/de230d6hfEPfmtJCQaQ+885NcIo1s6YULIcQJBAMd' + \ b't\noXUiJF2ssaTWTvMp3blCAi4G8M4JI+X6kiDZtqTzj0h8qQxSR/aWYxbJuP6wJzYy\nANRhK+/t0' + \ b'loZqI7+B70CQH2LLsccb1MHAkAGRqDZjtAfFAt7p7IaNeEp0jo4TcvK\ny50t2C9i5aa5tY6TFp4pQ' + \ b'3Vfk6l+21J6e5BKari9wfY=\n-----END RSA PRIVATE KEY-----' scroogePrivK = Crypto.PublicKey.RSA.importKey(exportedKey) scroogePubK = CryptoUtil.getPublicKey(scroogePrivK) keyPair = CryptoUtil.genKeyPair() alicePrivK = CryptoUtil.getPrivateKey(keyPair) alicePubK = CryptoUtil.getPublicKey(keyPair) # Make a genesis transaction genesis = Transaction() genesisValue = 25.0 genesis.addOutput(genesisValue, scroogePubK) genesis.finalize() # Make an initial pool initialPool = UTXOPool() utxo = UTXO(genesis.getHash(), 0) initialPool.addUTXO(utxo, genesis.getOutput(0)) # Note this transaction is not valid -- one of its inputs does not exist tx2in2out = Transaction() tx2in2out.addInput(genesis.hash, 0) tx2in2out.addInput(genesis.hash, 1) tx2in2out.addOutput(10.0, scroogePubK) tx2in2out.addOutput(15.0, scroogePubK)
def __init__(self, storage, pool_size=7, cache_size=400, cache_deactivate_after=60, version_pool_size=3, version_cache_size=100, version_cache_deactivate_after=10, ): """Create an object database. The storage for the object database must be passed in. Optional arguments are: pool_size -- The size of the pool of object spaces. """ # Allocate locks: l=allocate_lock() self._a=l.acquire self._r=l.release # Setup connection pools and cache info self._pools={},[] self._temps=[] self._pool_size=pool_size self._cache_size=cache_size self._cache_deactivate_after = cache_deactivate_after self._version_pool_size=version_pool_size self._version_cache_size=version_cache_size self._version_cache_deactivate_after = version_cache_deactivate_after self._miv_cache={} # Setup storage self._storage=storage storage.registerDB(self, None) if not hasattr(storage,'tpc_vote'): storage.tpc_vote=lambda *args: None try: storage.load('\0\0\0\0\0\0\0\0','') except KeyError: # Create the database's root in the storage if it doesn't exist import PersistentMapping root = PersistentMapping.PersistentMapping() # Manually create a pickle for the root to put in the storage. # The pickle must be in the special ZODB format. file = cStringIO.StringIO() p = cPickle.Pickler(file, 1) p.dump((root.__class__, None)) p.dump(root.__getstate__()) t = Transaction() t.description = 'initial database creation' storage.tpc_begin(t) storage.store('\0\0\0\0\0\0\0\0', None, file.getvalue(), '', t) storage.tpc_vote(t) storage.tpc_finish(t) # Pass through methods: for m in ('history', 'supportsUndo', 'supportsVersions', 'undoLog', 'versionEmpty', 'versions'): setattr(self, m, getattr(storage, m)) if hasattr(storage, 'undoInfo'): self.undoInfo=storage.undoInfo