def init_environment(): """ This runs before every test """ global interface interface = make_interface("ganache") mainblocks = 100 fork_index = 50 forkblocks = 100 pt = ProofTool("../data/proofs/") ( proof_name, fork_name, lca, fork_header, fork_header_map, fork_interlink_map, ) = pt.create_proof_and_forkproof(mainblocks, fork_index, forkblocks) global proof proof = Proof() proof.set(pt.fetch_proof_by_name(proof_name)) global fork fork = Proof() fork.set( pt.fetch_proof_by_name(fork_name), header=fork_header, header_map=fork_header_map, interlink_map=fork_interlink_map, )
def init_environment(): """ This runs before every test """ global backend global proof global changed_interlink_proof global missing_blocks_proof global replaced_blocks_proof backend = "ganache" proof = Proof() changed_interlink_proof = Proof() missing_blocks_proof = Proof() replaced_blocks_proof = Proof() original_proof = ProofTool("../data/proofs/").fetch_proof(100) proof.set(original_proof) _changed_interlink_proof = change_interlink_hash( original_proof, int(changed_interlink_proof.size / 2)) changed_interlink_proof.set(_changed_interlink_proof) _missing_blocks_proof = original_proof.copy() _missing_blocks_proof = skip_blocks(_missing_blocks_proof, -3) missing_blocks_proof.set(_missing_blocks_proof) _pt = ProofTool() _replaced_blocks_proof = _pt.fetch_proof( "../data/proofs/proof_100_replaced_mid_block.pkl") replaced_blocks_proof.set(_replaced_blocks_proof)
def init_environment(): """ This runs before every test """ global backend global submit_proof global small_contest_proof global small_lca global large_contest_proof global large_lca backend = "ganache" pt = ProofTool() pt.fetch_proof(1000) ( submit_proof_name, small_contest_proof_name, small_lca, small_header, small_header_map, small_interlink_map, ) = pt.create_proof_and_forkproof(1000, 200, 100) ( submit_proof_name, large_contest_proof_name, large_lca, large_header, large_header_map, large_interlink_map, ) = pt.create_proof_and_forkproof(1000, 100, 200) submit_proof = Proof() submit_proof.set(pt.fetch_proof(submit_proof_name)) small_contest_proof = Proof() small_contest_proof.set( pt.fetch_proof(small_contest_proof_name), header=small_header, header_map=small_header_map, interlink_map=small_interlink_map, ) large_contest_proof = Proof() large_contest_proof.set( pt.fetch_proof(large_contest_proof_name), header=large_header, header_map=large_header_map, interlink_map=large_interlink_map, )
def test_case_3(): # This test case should return True # in this test case we prove a -> a a = Variable("a") assumptions = [] proof = [ # Axiom 2 with a -> a instead of q Implies(Implies(a, Implies(Implies(a, a), a)), Implies(Implies(a, Implies(a, a)), Implies(a, a))), # Axiom 1 with a -> a instead of q Implies(a, Implies(Implies(a, a), a)), # Modus ponens of the first 2 axioms Implies(Implies(a, Implies(a, a)), Implies(a, a)), # Axiom 1 Implies(a, Implies(a, a)), # Modus ponens Implies(a, a) ] test = Proof(assumptions, proof) return test.verify()
def test_case_4(): # This test case should return True a = Variable("a") na = Not(a) nna = Not(na) nnna = Not(nna) nnnna = Not(nnna) assumptions = [nna] proof = [ # Axiom 1 Implies(nna, Implies(nnnna, nna)), # Modus ponens on the last step and the assumption Implies(nnnna, nna), # Axiom 3 Implies(Implies(nnnna, nna), Implies(na, nnna)), # Modus ponens on the last 2 steps Implies(na, nnna), # Axiom 3 Implies(Implies(na, nnna), Implies(nna, a)), # Modus ponens on the last 2 steps Implies(nna, a), # Modus ponens on the last step and the assumption a ] test = Proof(assumptions, proof) return test.verify()
def proof_search(self, problem): self.count_all = 0 self.count_valid = 0 self.method.start(problem) self.unique = {problem} result = None while (self.method.remaining() > 0): self.count_all += 1 path = self.method.remove() current = path[-1] if (current.is_valid()): self.count_valid += 1 if (self.search_limit is not None and self.count_valid > self.search_limit): return None if (current.is_done()): result = path break if (self.print): print(current) self.current = current self.path = path self._find_frontier_nodes() self.unique = None return None if result == None else Proof(result)
def test_dispute_invalid(init_environment): """ Try to dispute valid proof """ block_of_interest_index = 0 interface = make_interface(backend) invalid_index = int(proof.size / 2) invalid_proof = Proof() invalid_proof.set(change_interlink_hash(proof.proof, invalid_index)) res = submit_event_proof( interface, invalid_proof, block_of_interest_index, profile=True ) assert res["result"] == True res = dispute_existing_proof( interface, invalid_proof, block_of_interest_index, invalid_index, profile=True, ) assert res["result"] == True
def test_case_10(): # This test case should return True a = Variable("a") b = Variable("b") c = Variable("c") na = Not(a) nb = Not(b) assumptions = [ # Proof by contradiction Implies(Implies(a, b), Implies(Implies(a, nb), na)), # Proof by contradiction - deduction theorem Implies(a, b), Implies(a, nb), # Implication of inconsistency Implies(na, Implies(a, c)) ] proof = [Implies(Implies(a, nb), na), na, Implies(a, c)] test = Proof(assumptions, proof) return test.verify()
def main(): """ Test for backends """ proof_tool = ProofTool("../data/proofs/") proof_tool.fetch_proof(80) (submit_n, contest_n, _, _, _, _) = proof_tool.create_proof_and_forkproof(80, 10, 25) proof = Proof() proof.set(proof_tool.fetch_proof_by_name(submit_n)) c_proof = Proof() c_proof.set(proof_tool.fetch_proof_by_name(contest_n)) interface = ContractInterface(contract={ "path": "../OldContract.sol", "ctor": [] }, backend="geth") result = interface.call( "submitEventProof", function_args=[proof.headers, proof.siblings, proof.headers[-1]], value=pow(10, 17), ) sum = 0 print(result) for e in result["events"]: print(e[0], "\t", e[1]) sum += e[1] print("Sum:", sum) result = interface.call( "submitContestingProof", function_args=[c_proof.headers, c_proof.siblings, c_proof.headers[-1]], ) interface.end() sum = 0 print(result) for e in result["events"]: print(e[0], "\t", e[1]) sum += e[1] print("Sum:", sum)
def test_case_1(): # This test case should return False a = Variable("a") b = Variable("b") test = Proof([a, b], [a, b, Implies(a, b)]) return test.verify()
def __init__(self, transactions, previous_hash): self.transactions = transactions self.previous_hash = previous_hash self.timestamp = str(time()) proof = Proof(self) proof.run() self.hash = proof.hash self.nounce = proof.nounce self.tip = "true"
def init_proofs(backend, mainchain_blocks, fork_point, additional_blocks): """ create proofs for two contesting chains mainchain_blocks +-------------+ v v --------+-----> Chain A | +-> +--------> Chain B | | ^ ^ | | | | +--------+ | | fork_point additional_blocks """ pt = ProofTool() pt.fetch_proof(mainchain_blocks) ( submit_proof_name, contest_proof_name, contest_lca, contest_header, contest_header_map, contest_interlink_map, ) = pt.create_proof_and_forkproof(mainchain_blocks, fork_point, additional_blocks) submit_proof = Proof() submit_proof.set(pt.fetch_proof(submit_proof_name)) contest_proof = Proof() contest_proof.set( pt.fetch_proof(contest_proof_name), header=contest_header, header_map=contest_header_map, interlink_map=contest_interlink_map, ) return (submit_proof, contest_lca, contest_proof)
def init_environment(): """ This runs before every test """ backend = "ganache" global interface interface = make_interface(backend) global proof global headless_proof proof = Proof() headless_proof = Proof() original_proof = ProofTool("../data/proofs/").fetch_proof(100) proof.set(original_proof) _headless_proof = original_proof.copy() remove_genesis(_headless_proof) headless_proof.set(_headless_proof)
def init_environment(): """ This runs before every test """ global backend global interface backend = "ganache" interface = ContractInterface( { "path": "../contractNipopow.sol", "ctor": [genesis, m, k] }, backend=backend, ) global submit_proof global contest_proof pt = ProofTool() pt.fetch_proof(20) ( submit_proof_name, contest_proof_name, contest_lca, contest_header, contest_header_map, contest_interlink_map, ) = pt.create_proof_and_forkproof(100, 50, 50) submit_proof = Proof() submit_proof.set(pt.fetch_proof(submit_proof_name)) contest_proof = Proof() contest_proof.set( pt.fetch_proof(contest_proof_name), header=contest_header, header_map=contest_header_map, interlink_map=contest_interlink_map, )
def test_smaller_k(init_environment): """ Submit a proof with k=1 """ proof = Proof() proof.set(pt.fetch_proof("../data/proofs/proof_100_m15_k1.pkl")) interface = make_interface(backend) with pytest.raises(Exception) as ex: submit_event_proof(interface, proof, 0)
def test_case_2(): # This test case should return True a = Variable("a") b = Variable("b") assumptions = [a, b] proof = [a, b, Implies(a, Implies(b, a))] test = Proof(assumptions, proof) return test.verify()
def test_case_8(): # This test case should return False a = Variable("a") b = Variable("b") assumptions = [a] proof = [Implies(Implies(Not(a), Not(b)), Implies(b, a)), Implies(b, a)] test = Proof(assumptions, proof) return test.verify()
def init_environment(): """ This runs before every test """ global backend global proof backend = "ganache" blocks = 10 proof = Proof() proof.set(ProofTool("../data/proofs/").fetch_proof(blocks))
def test_case_12(): # This test case should return True a = Variable("a") b = Variable("b") c = Variable("c") assumptions = [Implies(a, b), Implies(b, c)] proof = prove_implication_transitivity(a, b, c) test = Proof(assumptions, proof) return test.verify()
def test_case_5(): # This test case should return True a = Variable("a") b = Variable("b") c = Variable("c") assumptions = [a, Implies(a, b), Implies(b, c)] proof = [b, c] test = Proof(assumptions, proof) return test.verify()
def main(): """ Test for backends """ available_backends = ContractInterface.available_backends() parser = argparse.ArgumentParser( description="Benchmark Py-EVM, Ganache and Geth") parser.add_argument( "--backend", choices=available_backends + ["all"], required=True, type=str, help="The name of the EVM", ) group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--blocks", type=int, help="Number of blocks") group.add_argument("--proof", type=str, help="Name of proof") parser.add_argument("--timer", action="store_true", help="Enable timers") args = parser.parse_args() backend = args.backend blocks = args.blocks proof_name = args.proof if backend == "all": backend = available_backends else: backend = [backend] proof_tool = ProofTool("../data/proofs/") if blocks is not None: proof = proof_tool.fetch_proof(blocks) elif proof_name is not None: proof = proof_tool.fetch_proof(proof_name) else: print("You need to provice --blocks of --proof") print("Proof lenght:", len(proof)) _p = Proof() _p.set(proof) for _b in backend: print("Testing", _b) res = run_nipopow(_b, _p) print("Result:", res)
def get_last_proof(self): response = requests.get(self.base_url + '/bc/last_proof/', headers={'Authorization': self.player.token}) try: data = response.json() except ValueError: print("Error: Non-json response") print("Response returned:") print(response) return self.player.next_action_time = time.time() + float( data.get('cooldown')) self.last_proof = Proof(data.get('proof'), data.get('difficulty'), data.get('cooldown'), data.get('message'), data.get('errors')) print("Response:", data)
def test_case_13(): # This test case should return True a = Variable("a") aa = Implies(a, a) a_aa = Implies(a, aa) n_a_aa = Not(a_aa) nn_a_aa = Not(n_a_aa) na = Not(a) nna = Not(na) assumptions = [Implies(a_aa, Implies(Implies(a_aa, a), a))] proof = [ # Axiom 1 a_aa, # Axiom 3 Implies(Implies(nn_a_aa, nna), Implies(na, n_a_aa)), # Axiom 3 Implies(Implies(na, n_a_aa), Implies(a_aa, a)), # Combine last 2 steps *prove_implication_transitivity(Implies(nn_a_aa, nna), Implies(na, n_a_aa), Implies(a_aa, a)), # It is now proven that: Implies(Implies(nn_a_aa, nna), Implies(a_aa, a)), # Axiom 1 Implies(nna, Implies(nn_a_aa, nna)), # Combine last 2 steps *prove_implication_transitivity(nna, Implies(nn_a_aa, nna), Implies(a_aa, a)), # It is now proven that Implies(nna, Implies(a_aa, a)), # Modus ponens for the assumption and the first formula Implies(Implies(a_aa, a), a), # Combine the last step with proof[6] *prove_implication_transitivity(nna, Implies(a_aa, a), a), # We have proven that Implies(nna, a) ] test = Proof(assumptions, proof) return test.verify()
def get_last_proof(self): response = requests.get(self.base_url + '/bc/last_proof/', headers={'Authorization': self.player.token}) try: data = response.json() except ValueError: print(self.player.token) print("Error: Non-json response") print("Response returned:") print(response) return self.last_proof = Proof(data.get('proof'), data.get('difficulty'), data.get('cooldown'), data.get('messages'), data.get('errors')) timer = time.time() + float(data.get('cooldown')) cooldown = max(0, (timer - time.time())) + 0.01 time.sleep(cooldown) print("Response:", data) return data
def calculate_proof(self): self.proof = Proof(self.current_block) work = 0 while True: work = self.proof.run(work) if type(work) == int: self.check_messages() else: break if (work == None): return self.current_block.nonce = work.nonce self.current_block.hash = work.hash self.current_block.print() print("T: ", current_thread().name, "[MINED] [BLOCK]") self.blockchain.add_block(self.current_block) network.Network.distribute_block(self.current_block, self)
def testping(self): # si utilizza funzione ping.py test_type = 'ping' start = datetime.fromtimestamp(timestampNtp()) elapsed = 0 try: # Il risultato deve essere espresso in millisecondi elapsed = ping.do_one(self._host.ip, self._timeout) * 1000 except Exception as e: errorcode = errors.geterrorcode(e) error = '[%s] Errore durante la misura %s: %s' % (errorcode, test_type, e) logger.error(error) raise Exception(error) if (elapsed == None): elapsed = 0 return Proof(test_type, start=start, value=elapsed, bytes=0)
def test_case_9(): # This test case should return True a = Variable("a") b = Variable("b") c = Variable("c") na = Not(a) nna = Not(na) ab = Implies(a, b) bc = Implies(b, c) assumptions = [a, Implies(a, nna)] proof = [ nna, # Axiom 1 Implies(nna, Implies(Not(Implies(ab, Not(bc))), nna)), # MP Implies(Not(Implies(ab, Not(bc))), nna), # Axiom 3 Implies(Implies(Not(Implies(ab, Not(bc))), nna), Implies(na, Implies(ab, Not(bc)))), # MP Implies(na, Implies(ab, Not(bc))), # Axiom 2 Implies(Implies(na, Implies(ab, Not(bc))), Implies(Implies(na, ab), Implies(na, Not(bc)))), # MP Implies(Implies(na, ab), Implies(na, Not(bc))) ] test = Proof(assumptions, proof) return test.verify()
def test_case_11(): # This test case should return True a = Variable("a") b = Variable("b") c = Variable("c") d = Variable("d") assumptions = [a, Implies(a, b), Implies(b, c)] proof = [ # MP b, # MP c, # Axiom 1 Implies(c, Implies(Not(d), c)), # MP Implies(Not(d), c) ] test = Proof(assumptions, proof) return test.verify()
from uuid import uuid4 from flask import Flask, jsonify, request from blockchain import Blockchain from consensus import Consensus from hash import Hash from nodes import Nodes from proof import Proof # Initialise a Node and generate a globally unique address app = Flask(__name__) node_id = str(uuid4()).replace('-', '') blockchain = Blockchain() proof = Proof() nodes = Nodes() consensus = Consensus() @app.route('/mine', methods=['GET']) def mine(): ''' Mine a new block. ''' # Get the previous block and proof and find the new proof. previous_block = blockchain.last_block previous_proof = previous_block["proof"] new_proof = proof.proof_of_work(previous_proof)
def testftpup(self, bytes, path): global ftp, file, size, filepath filepath = path test_type = 'upload' size = 0 elapsed = 0 file = Fakefile(bytes) timeout = max(self._timeout, 12) start = datetime.fromtimestamp(timestampNtp()) try: ftp = FTP(self._host.ip, self._username, self._password, timeout=timeout) except ftplib.all_errors as e: errorcode = errors.geterrorcode(e) error = '[%s] Impossibile aprire la connessione FTP: %s' % ( errorcode, e) logger.error(error) raise Exception(error) # TODO Se la connessione FTP viene invocata con timeout, il socket è non-blocking e il sistema può terminare i buffer di rete: http://bugs.python.org/issue8493 function = '''ftp.storbinary('STOR %s' % filepath, file, callback=totalsize)''' setup = 'from %s import file, ftp, totalsize, filepath' % __name__ timer = timeit.Timer(function, setup) try: logger.debug('Test initializing...') start_total_bytes = self._netstat.get_tx_bytes() logger.debug('Testing... ') # pcapper.sniff(Contabyte(self._if_ip, self._host.ip)) # Il risultato deve essere espresso in millisecondi elapsed = timer.timeit(1) * 1000 # pcapper.stop_sniff() # counter_stats = pcapper.get_stats() logger.debug('Test stopping... ') end_total_bytes = self._netstat.get_tx_bytes() logger.debug('Test done!') except ftplib.all_errors as e: errorcode = errors.geterrorcode(e) error = '[%s] Impossibile effettuare il test %s: %s' % ( errorcode, test_type, e) logger.error(error) raise Exception(error) except Exception as e: errorcode = errors.geterrorcode(e) error = '[%s] Errore durante la misura %s: %s' % (errorcode, test_type, e) logger.error(error) raise Exception(error) ftp.quit() ''' TODO: get packet drop from netstat ''' counter_stats = Statistics(byte_up_nem=size, byte_up_all=end_total_bytes - start_total_bytes, packet_drop=0, packet_tot_all=100) # return Proof(test_type, start, elapsed, size, counter_stats) return Proof(test_type, start, elapsed, size, counter_stats)