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 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 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 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 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 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 valid_chain(chain): ''' Determine if a given blockchain is valid by looping through each block and verifying both hash and the proof :param chain: <list> A blockchain to verify :return: <bool> True if valid, else False ''' last_block = chain[0] current_index = 1 while current_index < len(chain): block = chain[current_index] print(f'{last_block}') print(f'{block}') print('\n-------\n') # Check of the current block is correct if block['previous_hash'] != Hash.hash(last_block): return False # Check that the proof of work is correct # by validating the last blocks proof against the current blocks proof if not Proof.valid_proof(last_block['proof'], block['proof']): return False last_block = block current_index += 1 # If all above checks pass, then the block is valid. return True
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 wrapper(proof: Proof, rule: Rule, sentence: SignedSentence, *args, **kwargs): old = proof.nodes.getleaf(sentence.branch) # Rule usage fin = func(rule, sentence, *args, **kwargs) assert fin is not None, "Reguła nie zwróciła nic" layer = proof.append(fin, sentence.branch) ProofNode.insert_history( len(fin) * ([[0]] if rule.reusable else [[sentence.sentence]]), old.children) if rule.name.startswith('false'): _, (_, a) = sentence.sentence.getComponents() tid = a.getMainConnective() + 2 else: tid = sentence.sentence.getMainConnective() context = {'sentenceID': sentence.id, 'tokenID': tid} proof.metadata['usedrules'].append( UsedRule(layer, sentence.branch, rule.name, proof, context=context, auto=True)) return old.descendants
def test_proof_of_work(self): ''' Ensures that given the proof of one, the next proof is 72608 for 4 leading zero solution. ''' result = Proof.proof_of_work(1) self.assertEqual(72608, result)
def solver(proof: Proof) -> bool: """ Funkcja solvera, zwraca informację, czy dowód udało się ukończyć (powinna być zawsze True) """ containers = group_by_rules(proof) s = _solver(proof, ROOT_RULE, containers, check_closure) proof.metadata['used_solver'] = s return s
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 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 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_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()
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 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 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 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)