def prova_ledger(): r2 = topology_node('r2', 'R') r3 = topology_node('r3', 'R') r5 = topology_node('r5', 'R') tx = transaction(r2, r5) tx2 = transaction(r3, r5) txset = transaction_set([tx, tx2]) l = full_ledger(0, txset) b = light_blockchain() b.add_ledger(l) b.add_ledger(l) b.add_ledger(l) ledgers = b.ledgers() print ledgers l2 = full_ledger(2, txset) l3 = full_ledger(3, txset) l4 = full_ledger(4, txset) l5 = full_ledger(5, txset) l6 = full_ledger(6, txset) l7 = full_ledger(7, txset) b = full_blockchain((7, 3)) b.add_ledger(l) b.add_ledger(l2) b.add_ledger(l3) b.add_ledger(l4) b.add_ledger(l5) b.add_ledger(l6) print 'size: ' + str(b.size()) b.add_ledger(l7) print 'size after: ' + str(b.size()) ledgers = b.ledgers() print ledgers
def prova_scambio_proposal(): r2 = topology_node('r2', 'R') r3 = topology_node('r3', 'R') r5 = topology_node('r5', 'R') tx = transaction(r2, r5) tx2 = transaction(r3, r5) trans = [tx, tx2] b = light_blockchain() s = server('127.0.0.100', 10000, 0.8, 5, 10, {}, {}, 10, 20, validators=[], unl=['127.0.0.101:10000']) s2 = server('127.0.0.101', 10000, 0.8, 5, 10, {}, {}, 10, 20, validators=[], unl=['127.0.0.100:10000']) c = client('127.0.0.102', '10000', [s, s2]) c.ask_client_registration() c.send_transactions(trans) s.start() s2.start() time.sleep(10) s.stop() s2.stop()
def prova_stampa_proposal(): r2 = topology_node('r2', 'R') r3 = topology_node('r3', 'R') r5 = topology_node('r5', 'R') tx = transaction(r2, r5) tx2 = transaction(r3, r5) txset = transaction_set([tx, tx2]) my_pos = proposal('0', 1, txset, '0') print str(my_pos.tx_set())
def prova_transazioni(): r2 = topology_node('r2', 'R') r3 = topology_node('r3', 'R') r5 = topology_node('r5', 'R') tx = transaction(r2, r5) tx2 = transaction(r3, r5) tx3 = transaction(r3, r5) unapproved = {tx: 0, tx2: 0} if tx3 in unapproved: print 'OK' assert tx2 == tx3
def prova_id_txset(): r2 = topology_node('r2', 'R') r3 = topology_node('r3', 'R') r5 = topology_node('r5', 'R') tx = transaction(r2, r5) tx2 = transaction(r3, r5) txset = transaction_set([tx, tx2]) r2b = topology_node('r2', 'R') r3b = topology_node('r3', 'R') r5b = topology_node('r5', 'R') txb = transaction(r2b, r5b) tx2b = transaction(r3b, r5b) txset2 = transaction_set([tx, tx2]) return txset.id() == txset2.id()
def prova_invio_messaggi(): s = server('127.0.0.3', 10005, []) c = client('127.0.0.4', 10005, [s]) r2 = topology_node('r2', 'R') r3 = topology_node('r3', 'R') r5 = topology_node('r5', 'R') tx = transaction(r2, r5) tx2 = transaction(r3, r5) txset = transaction_set([tx, tx2]) mh = message_header(c.id(), c.signature(), 'm1', 0, message_type.transaction_set) mp = message_payload(txset) msg = message(mh, mp) c.send_all(msg)
def install(self, raise_exc=True, log_exc=True): __traceback_info__ = self.productname package = self.package product = self.product productname = self.productname initializer = self.initializer permissions = self.permissions folder_permissions = get_folder_permissions() init_data = None try: self.set_package_module_aliases() self.set_package_misc_attrs() # allow entry points that are "dummies" (e.g. just the module) # in case the product doesn't have an initialize function that # needs to be called if callable(initializer): init_data = initializer(self) self.set_package_ac_permissions() self.munge_package_meta_types() self.set_package_methods() if self.new_permissions: new_permissions = self.new_permissions.items() for permission, names in new_permissions: folder_permissions[permission] = names new_permissions.sort() Folder.__ac_permissions__ = tuple( list(Folder.__ac_permissions__) + new_permissions) if not doInstall(): transaction().abort() else: transaction.get().note('Installed product ' + productname) transaction.commit() except: if log_exc: zLOG.LOG('Zope', zLOG.ERROR, 'Couldn\'t install %s' % productname, error=sys.exc_info()) transaction.abort() if raise_exc: raise return init_data
def install(self, raise_exc=True, log_exc=True): __traceback_info__ = self.productname package = self.package product = self.product productname = self.productname initializer = self.initializer permissions = self.permissions folder_permissions = get_folder_permissions() init_data = None try: self.set_package_module_aliases() self.set_package_misc_attrs() # allow entry points that are "dummies" (e.g. just the module) # in case the product doesn't have an initialize function that # needs to be called if callable(initializer): init_data = initializer(self) self.set_package_ac_permissions() self.munge_package_meta_types() self.set_package_methods() if self.new_permissions: new_permissions = self.new_permissions.items() for permission, names in new_permissions: folder_permissions[permission]=names new_permissions.sort() Folder.__ac_permissions__=tuple( list(Folder.__ac_permissions__)+new_permissions) if not doInstall(): transaction().abort() else: transaction.get().note('Installed product '+productname) transaction.commit() except: if log_exc: zLOG.LOG('Zope',zLOG.ERROR,'Couldn\'t install %s' % productname, error=sys.exc_info()) transaction.abort() if raise_exc: raise return init_data
def test_transaction(self): from ptah.sqlautils import transaction class SA(object): commited = False rollbacked = False raise_commit = False def commit(self): if self.raise_commit: raise RuntimeError() self.commited = True def rollback(self): self.rollbacked = True sa = SA() trans = transaction(sa) with trans: pass self.assertTrue(sa.commited) sa = SA() trans = transaction(sa) try: with trans: raise ValueError() except: pass self.assertTrue(sa.rollbacked) sa = SA() sa.raise_commit = True trans = transaction(sa) try: with trans: pass except: pass self.assertTrue(sa.rollbacked)
def prova_ledger_equality(): r2 = topology_node('r2', 'R') r3 = topology_node('r3', 'R') r5 = topology_node('r5', 'R') tx = transaction(r2, r5) tx2 = transaction(r3, r5) txset = transaction_set([tx, tx2]) l = full_ledger(0, txset) tx3 = transaction(r2, r5) tx4 = transaction(r3, r5) txset2 = transaction_set([tx4, tx3]) l2 = full_ledger(0, txset2) print 'Test: transaction_set sono uguali \n' assert txset == txset2 print 'Test: ledger sono uguali \n' assert l == l2 print 'Test: ledger sono diversi \n' l3 = full_ledger(1, txset2) assert l != l3
def __init__(self, f): self.txns = [] f.readline() #ignore header for line in f: id, lbls, vec = line.translate(None, ',]\n').split('[') lbls = lbls.split() vec = map(float, vec.split()) vec = [i for i, e in enumerate(vec) if e > 0] t = transaction(id, lbls, vec) self.txns.append(t)
def get_honest_transactions_tree(num): ''' Returns a list of transactions arranged as directed binary tree (arrows from father to children) :param num: Number of transactions to be created, representing the edges in the tree :return: list of transactions ''' i = 1 # Incremental ID for the routers t = 0 # Number of inserted transactions routers = {} trans = [] while (t < num): routers['r' + str(i)] = topology_node('r' + str(i), 'R') routers['r' + str(2*i)] = topology_node('r' + str(2*i), 'R') routers['r' + str(2*i+1)] = topology_node('r' + str(2*i+1), 'R') trans.append(transaction(routers['r' + str(i)], routers['r' + str(2*i)])) trans.append(transaction(routers['r' + str(i)], routers['r' + str(2*i + 1)])) i += 1 t += 2 if i == num+1: del trans[len(trans)-1] return trans
def get_honest_transactions(): ''' Returns the list of (104) honest transactions to be inserted in the blockchain. The topology is a directed Mesh (from r1 you reach r60): r1 -> r2 -> r3 -> ... -> r10 | | | ... | v v v ... v ................ r51 -> r52 -> r53 -> ... -> r60 ''' routers = {} for i in range(1, 61): routers['r'+str(i)] = topology_node('r'+str(i), 'R') trans = [] #Add orizzontal transactions for i in range(1, 60): if i % 10 != 0: # Add orizontal edge trans.append(transaction(routers['r'+str(i)], routers['r'+str(i+1)])) if i <= 50: # Add vertical edge trans.append(transaction(routers['r' + str(i)], routers['r' + str(i + 10)])) return trans
def build_txset_from_topo(topo): # First build dictionary having key = node_name, value = node nodes = {} for n in topo: node = topology_node(n["Name"], n["Type"]) nodes[n["Name"]] = node # Then create transactions and finally pass them to the transaction_set transactions = [] for n in topo: for to in n["Neighbors"]: tx = transaction(nodes[n["Name"]], nodes[to]) transactions.append(tx) return transaction_set(transactions)
def prova_transazioni_delete(): def configure_client(config_file): '''Uses the parameters defined in the configuration file to create a client and return it.''' with open(config_file, 'r') as file: obj = json.load(file) ip = obj["ip"] port = obj["port"] validators = [] for v in obj["validators"]: v_id = v["ip"] + ":" + v["port"] validators.append(v_id) return client(ip, port, validators) c = configure_client("file_config_prova/client1_config.json") c.ask_client_registration() trans = [] r3 = topology_node('r3', 'R') r4 = topology_node('r4', 'R') r2 = topology_node('R2', 'R') trans.append(transaction(r3, r4, False)) trans.append(transaction(r4, r3, False)) c.send_transactions(trans)
def add_easy(): args = request.form if not ("fro" in args.keys()): return form_add_easy() if not ("too" in args.keys()): return form_add_easy() if not ("value" in args.keys()): return form_add_easy() if not ("mne" in args.keys()): return form_add_easy() fro, too, value, mne = [args[zw] for zw in ["fro", "too", "value", "mne"]] if len(mne) < 10 or mne == "auto": if "mne" in session.keys(): mne = session["mne"] value = int(value) if value <= 0: return with_go_back( "Nice try noob. Setting your Balance to -1 Million Euros. Please pay up as soon as you are able to.<br><br>Measuring your worth....<br><br>Estimation suggests that you wont be able to pay this back....<br><br>Contacting credit institutes.....<br><br>Not enough. Require Payback.....<br>Contacting dark net hitman...<br><br>Positive Confirmation...<br><br>In case of succesful assasination, your death will be billed to your closest Relative...<br><br><br>Good bye. Hope you are happy with our service." ) try: sk, pk, opk = gen_keys(mne) except: return with_go_back( "This is not a valid mnemonic. Please try again or contact your nodes host" ) #u=load_user(fro) try: u = load_user(fro) except: return with_go_back( f"The user {fro} was not found and can thus not pay anything") if not u.key == opk.hex(): return with_go_back( f"This is not the rigth mnemonic for the user {fro}. Sadly, mnemonics can not be reconstructed, but maybe you just try again." ) t = transaction(fro, too, value) t.signate(sk) if not t.verify(pk): return with_go_back( f"This transaction did not pass the self test. Contact your nodes host." ) t.save() push() return with_go_back( f"Gratulations! This worked and you are now {value} ct poorer")
def prova_size_txset(): c = client('127.0.0.12', 10000, []) r2 = topology_node('r2', 'R') r3 = topology_node('r3', 'R') r5 = topology_node('r5', 'R') r6 = topology_node('r6', 'R') r7 = topology_node('r7', 'R') r8 = topology_node('r8', 'R') tx = transaction(r2, r5) tx2 = transaction(r3, r5) tx3 = transaction(r6, r5) tx4 = transaction(r2, r6) tx5 = transaction(r2, r7) tx6 = transaction(r2, r8) tx7 = transaction(r3, r6) tx8 = transaction(r3, r7) tx9 = transaction(r3, r8) tx10 = transaction(r7, r8) transactions = [tx] tx_set = transaction_set(transactions) header = message_header(c.id(), c.signature(), 'id', 0, message_type.transaction_set) payload = message_payload(tx_set) msg = message(header, payload) msg_bin = pickle.dumps(msg) print 'Size in bytes with one transaction: ' + str(sys.getsizeof(msg_bin)) tx_set.add_transaction(tx2) payload = message_payload(tx_set) msg = message(header, payload) msg_bin = pickle.dumps(msg) print 'Size in bytes with 2 transaction: ' + str(sys.getsizeof(msg_bin)) transactions = [tx3, tx4, tx5] for t in transactions: tx_set.add_transaction(t) payload = message_payload(tx_set) msg = message(header, payload) msg_bin = pickle.dumps(msg) print 'Size in bytes with 10 transaction: ' + str(sys.getsizeof(msg_bin))
def test_user_repo(clean_db): with transaction(): assert user_repo.list() == [] with transaction(): user1_id = user_repo.add(User('celine', 'Celine Yeh')) assert user1_id == 1 user2_id = user_repo.add(User('antonio', 'Antonio Hong')) assert user2_id == 2 with transaction(): user_info = [ (user.id, user.username, user.display_name) for user in user_repo.list() ] assert user_info == [ (1, 'celine', 'Celine Yeh'), (2, 'antonio', 'Antonio Hong'), ] with transaction(): user = user_repo.get(1) assert user.username == 'celine' assert user.display_name == 'Celine Yeh' with transaction(): user_repo.delete(1) with transaction(): user_info = [ (user.id, user.username, user.display_name) for user in user_repo.list() ] assert user_info == [ (2, 'antonio', 'Antonio Hong'), ] with transaction(): with pytest.raises(NoResultFound): user_repo.get(1)
# # x to exit # # ignore anything else # userInput = input("") if (userInput == 'x'): exit() #create a transaction and update the blockchain # # #************************TODO**************************** # this must be updated or put into a function so that it can # send updated blocks to the other machine's in the elif (userInput == 't'): newTransaction = transaction(2) #our store number is 2 newTransaction.setTransaction() newBlock = newTransaction.makeBlock() updateBlockchain(newBlock) updateOtherBlockchains(newBlock) continue #********************************************************* elif (userInput == 's'): #this is the search tree. This will continue until the user backs out of it while (True): print( "Type 'd' to search by date, 's' to search by store ID, or 't' to search by transaction id. (type 0 to return to main screen)" ) check = input("") if (check == 'd'): searchByDateInterface()
def prova_deletion(): r3 = topology_node('r3', 'R') r3b = topology_node('r1', 'R') r4a = topology_node('X4', 'A') r5a = topology_node('X5', 'A') r6a = topology_node('X6', 'A') r7a = topology_node('X7', 'A') r2 = topology_node('R2', 'R') r5 = topology_node('r5', 'R') tx = [ transaction(r3, r4a), transaction(r4a, r3), transaction(r3, r7a), transaction(r7a, r3), transaction(r5, r4a), transaction(r2, r3), transaction(r2, r7a), transaction(r3b, r3), transaction(r6a, r4a), transaction(r5, r3), transaction(r5, r7a), transaction(r7a, r2) ] c = configure_client("file_config_prova/client1_config.json" ) # TODO va specificato da linea di comando register_client(c) c.send_transactions(tx) choice = raw_input( "\n---------Press any button to delete r5 -----------\n") tx = [transaction(r5, None, False)] c.send_transactions(tx)
def newcustomerlogin(): count = 0 print("Please Enter the credentials:") name = input("Please Enter Your Name :") if name.isalpha(): pass else: print("Name Entered Is Not According To Rules: ") newcustomerlogin() cus_dob = input("Please Enter the DOB: in format 'yy-mm-dd'") year, month, day = cus_dob.split('-') isValidDate = True try: datetime.datetime(int(year), int(month), int(day)) except ValueError: isValidDate = False if (isValidDate): pass else: print("DOB Entered Is Not According To Rules: ") newcustomerlogin() cus_address = input("Please Enter address:") cus_phone = int(input("Enter your phone no. must be a 10 digit no.")) if len(str(cus_phone)) == 10: pass else: print("Phone No. Entered Is Not According To Rules: ") newcustomerlogin() cus_adhar = int(input("Enter your addhaar card no.")) if len(str(cus_adhar)) == 10: pass else: print("addhaar No. Entered Is Not According To Rules: ") newcustomerlogin() cus_pan = input("Enter your pan card details:") if len(cus_pan) == 10: if cus_pan.isalnum(): count1 = 1 if count1 == 0: print("Pan No. Entered Is Not According To Rules: ") newcustomerlogin() cus_balance = int(input("Enter the Opening Amount:")) cus_pas = input( "Enter Your Password to database: \n Must be atleast of 8 characters and must contain a special character and a number " ) if cus_pas.isalnum(): if len(cus_pas) > 7: if re.match(r'[A-Za-z0-9@#$%^&+=]{8,}', cus_pas): count = 1 pass if count == 1: print("Password Entered Is Not According To Rules: ".center()) newcustomerlogin() cus_id = "" while (len(cus_id) != 10): n = random.randrange(0, 10) cus_id = cus_id + str(n) con = sql.connect("localhost", "root", "purbalok1", "bank") cu = con.cursor() qry = "Select * from customer" cu.execute(qry) count1 = cu.rowcount con.commit() con.close() del qry qry = ( "INSERT INTO customer " "(Name, Account_No, Date_Of_Birth, Address, phone_no, Adhaar_No, PAN_No, Password, balance) " "VALUES (%s, %s, %s, %s, %s, %s,%s,%s,%s)") data = (name, cus_id, cus_dob, cus_address, cus_phone, cus_adhar, cus_pan, cus_pas, cus_balance) con = sql.connect("localhost", "root", "purbalok1", "bank") cu = con.cursor() cu.execute(qry, data) count2 = cu.rowcount con.commit() con.close() transaction(name, cus_id, cus_balance) if count2 > count1: print("data entered successful!!!") inputuser() else: print("data not entered!!!!!") inputuser()
value = int(input("How much do you pay\n")) if value <= 0: print("nice try, noob") exit() mnemo = input( f"To verify this transaction, please add the mnemonic of {fro}\n") sk, pk, opk = gen_keys(mnemo) u = load_user(fro) if not u.key == opk.hex(): print("This is not the rigth mnemonic. Canceling...") exit() t = transaction(fro, too, value) t.signate(sk) test = t.verify(pk) if test: print("Passed the self test") else: print("Failed the self test") exit() while input("Is this ok?, enter 'y' to save,strg+c to cancel") != "y": pass t.save()
dic['B_Hash'] = None dic['size'] = None h.update(str(dic)) self.B_Hash = h.getsha256() return True def getHash(self): h = libhash() dic = self.to_dict() dic['B_Hash'] = None dic['size'] = None h.update(str(dic)) return h.getsha256() if __name__ == "__main__": t = transaction() data = {} data['TXID'] = "123" t.update(data) b = block() b.add(t) print(b.to_dict()) print(type(b.header))