Ejemplo n.º 1
0
    def mineBlock(
        lastBlock, data:
        "Series of hashes from transactions and a hash calculated from last block"
    ):
        # Calculate hash of given transaction
        mt = mlt.MerkleTools(hash_type="sha256")
        mt.add_leaf(
            data, True
        )  # set the optional do_hash to true to have your value hashed prior to being added to the tree.
        mt.make_tree()

        # Calculated hash that needs to have Difficulty leading zeros
        lastHash = lastBlock.hash

        # Random value that will be incremented
        for nonce in count(0):
            timestamp = datetime.now().strftime("%d-%m-%Y-%H-%M-%S")
            hash = Block.hash(timestamp, lastHash, mt.get_merkle_root(), nonce)
            # Check whether hash has required number of leading 0's
            if hash[:BlockChain.Difficulty].__eq__('0' *
                                                   BlockChain.Difficulty):
                print(
                    f"[*] New block! Difficulty: {BlockChain.Difficulty}, Nonce: {nonce}, New block: {Block(timestamp, lastHash, hash, data, nonce)}"
                )
                return Block(timestamp, lastHash, hash, data, nonce)
Ejemplo n.º 2
0
def get_merkle_root(txns):
    mt = merkletools.MerkleTools(hash_type='SHA256')

    for tx in txns:
        mt.add_leaf(tx.hash)
    mt.make_tree()

    return mt.get_merkle_root()
Ejemplo n.º 3
0
def build_merkle_tree(leaves, hash_type, expected_root=None):
    mt = merkletools.MerkleTools(hash_type=hash_type)
    mt.leaves = leaves
    mt.make_tree()
    if expected_root is not None:
        assert mt.merkle_root == expected_root
        print("Root matches!")
    return mt
Ejemplo n.º 4
0
def get_genesis_merkle_root():
    ''' Get first '''
    _mt = merkletools.MerkleTools()

    for single_hash in GENESIS_INIT_DATA["hashes"]:
        _mt.add_leaf(single_hash)
    _mt.make_tree()
    # get merkle_root and return
    return _mt.get_merkle_root()
Ejemplo n.º 5
0
def convert_to_merkle(
    transactions: List[SignedRawTransaction],
) -> merkletools.MerkleTools:
    mt = merkletools.MerkleTools(hash_type="sha256")

    mt.add_leaf([t.SerializeToHex() for t in transactions])
    mt.make_tree()

    return mt
Ejemplo n.º 6
0
def get_merkle_root(file_name):
    mt = m.MerkleTools(hash_type="md5")
    for i in range(0, get_num_blocks(file_name)):
        mt.add_leaf(get_data(file_name, i), True)
    mt.make_tree()

    while not mt.is_ready:
        print("Waiting")
        time.sleep(1)
    return mt.get_merkle_root()
Ejemplo n.º 7
0
def get_merkle_root(prescriptions):
    # Generate merkle tree
    mt = merkletools.MerkleTools()  # Default is SHA256
    # Build merkle tree with Rxs
    for rx in prescriptions:
        mt.add_leaf(rx.signature)
    mt.make_tree()
    # Just to check
    print mt.get_leaf_count()
    # get merkle_root and return
    return mt.get_merkle_root()
Ejemplo n.º 8
0
def create_merkle_tree():
    global merkle_root_place_holder
    global merkleRoot
    global dirname

    mt = merkletools.MerkleTools()
    calculate_hashed_digests(mt, dirname)
    mt.make_tree()
    assert(mt.is_ready)
    root_val = mt.get_merkle_root()
    merkle_root_place_holder.configure(text=root_val)
    merkleRoot = int(mt.get_merkle_root(), 16)
Ejemplo n.º 9
0
def get_merkle_root(prescriptions):
    # Generate merkle tree
    logger = logging.getLogger('django_info')
    mt = merkletools.MerkleTools()  # Default is SHA256
    # Build merkle tree with Rxs
    for rx in prescriptions:
        mt.add_leaf(rx.rxid)
    mt.make_tree()
    # Just to check
    logger.error("Leaf Count: {}".format(mt.get_leaf_count()))
    # get merkle_root and return
    return mt.get_merkle_root()
Ejemplo n.º 10
0
    def hashBigfile(self,
                    read_func,
                    size,
                    piece_size=1024 * 1024,
                    file_out=None):
        self.site.settings["has_bigfile"] = True

        recv = 0
        try:
            piece_hash = CryptHash.sha512t()
            piece_hashes = []
            piece_recv = 0

            mt = merkletools.MerkleTools()
            mt.hash_function = CryptHash.sha512t

            part = ""
            for part in self.readFile(read_func, size):
                if file_out:
                    file_out.write(part)

                recv += len(part)
                piece_recv += len(part)
                piece_hash.update(part)
                if piece_recv >= piece_size:
                    piece_digest = piece_hash.digest()
                    piece_hashes.append(piece_digest)
                    mt.leaves.append(piece_digest)
                    piece_hash = CryptHash.sha512t()
                    piece_recv = 0

                    if len(piece_hashes) % 100 == 0 or recv == size:
                        self.log.info(
                            "- [HASHING:%.0f%%] Pieces: %s, %.1fMB/%.1fMB" %
                            (float(recv) / size * 100, len(piece_hashes),
                             recv / 1024 / 1024, size / 1024 / 1024))
                        part = ""
            if len(part) > 0:
                piece_digest = piece_hash.digest()
                piece_hashes.append(piece_digest)
                mt.leaves.append(piece_digest)
        except Exception as err:
            raise err
        finally:
            if file_out:
                file_out.close()

        mt.make_tree()
        merkle_root = mt.get_merkle_root()
        if type(merkle_root) is bytes:  # Python <3.5
            merkle_root = merkle_root.decode()
        return merkle_root, piece_size, {"sha512_pieces": piece_hashes}
Ejemplo n.º 11
0
def proof():
    mt = merkletools.MerkleTools()

    if not merkleRoot:
        messagebox.showinfo('Uh Oh', f'This graduating class does not exist!')
        return

    db = Database(config('DATABASE'), config('USER'), config('PASSWORD'),
                  config('HOST'), config('PORT'))
    db_cursor = db.cursor

    select_hashes_command = f'SELECT hash FROM gc{graduating_class}'

    db_cursor.execute(select_hashes_command)
    index = None
    count = 0

    rows = db_cursor.fetchall()

    db.close()

    for row in rows:
        hash = row[0]
        if hash == student_hash.get():
            index = count
        count += 1
        mt.add_leaf(hash)

    mt.make_tree()

    if index is None:
        messagebox.showinfo('Uh Oh',
                            f'This hash is not part of the graduating class.')
        return

    hex_merkle_root = hex(merkleRoot).split('x')[-1]
    merkle_proof = mt.get_proof(index)

    is_valid = mt.validate_proof(merkle_proof, student_hash.get(),
                                 hex_merkle_root)

    if index is None or not is_valid:
        messagebox.showinfo('Uh Oh',
                            f'This hash is not part of the graduating class.')
        return
    else:
        answer = messagebox.askyesno(
            'Question', 'Would you like to send this to your employer?')

        if (answer):
            send_link_to_employer(str(merkle_proof))
Ejemplo n.º 12
0
def is_rx_in_block(target_rx, block):
    #  We need to create a new tree and follow the path to get this proof
    mtn = merkletools.MerkleTools()
    rx_hashes = block.data["hashes"]
    n = 0
    for index, hash in enumerate(rx_hashes):
        mtn.add_leaf(hash)
        if target_rx.signature == hash:
            n = index
    # Make the tree and get the proof
    mtn.make_tree()
    proof = mtn.get_proof(n)
    print proof
    return mtn.validate_proof(proof, target_rx.signature, block.merkleroot)
Ejemplo n.º 13
0
def is_rx_in_block(target_rx, block):
    #  We need to create a new tree and follow the path to get this proof
    logger = logging.getLogger('django_info')
    mtn = merkletools.MerkleTools()
    rx_hashes = block.data["hashes"]
    n = 0
    for index, hash in enumerate(rx_hashes):
        mtn.add_leaf(hash)
        if target_rx.rxid == hash:
            n = index
    # Make the tree and get the proof
    mtn.make_tree()
    proof = mtn.get_proof(n)
    logger.error("Proof: {}".format(proof))
    return mtn.validate_proof(proof, target_rx.rxid, block.merkleroot)
Ejemplo n.º 14
0
import timeit
from itertools import count
import merkletools

LOOPS = 10

mt = merkletools.MerkleTools(hash_type="sha512")

timer = timeit.Timer("mt.make_tree()", globals=globals())

print("LEAVES,BUILD_TIME")
for i in count(1):
    mt.add_leaves([str(l) for l in range(i * 1000)], do_hash=True)
    t = timer.timeit(number=LOOPS)
    print(f"{len(mt.leaves)},{t / LOOPS}")
    mt.reset_tree()

Ejemplo n.º 15
0
def verify_proof(proof, data, merkle_root):
    mt = m.MerkleTools(hash_type="md5")
    h = hashlib.md5()
    h.update(str(data).encode('utf-8'))
    return mt.validate_proof(proof, h.hexdigest(), merkle_root)
Ejemplo n.º 16
0
# -*- coding: utf-8 -*-
import merkletools

mt = merkletools.MerkleTools(hash_type="SHA256")

Txs = [
    'Sam get $100 by POW', 'Tim give Jimmy $100', 'Johb give Jimmy $100',
    'Jimmy give Tom $100'
]

mt.add_leaf(Txs, True)
mt.make_tree()

print(mt.get_merkle_root())
Ejemplo n.º 17
0
def main():

    myDomain = input(
        "Step1 Please enter a domainname to generate a certificate: ")

    mytime = str(int(round(time.time() * 1000)))
    randomEvidenceMerkleRoot = hashlib.sha256(mytime.encode()).hexdigest()
    #considering evidences collected

    #CertificateKey
    private_key = RSA.generate(2048)
    public_key = private_key.publickey()
    #print(private_key.exportKey(format='PEM'))
    #print(public_key.exportKey(format='PEM'))
    with open("GeneratedCerts\\" + myDomain + mytime + "PrivateKeyRSA.pem",
              "w") as prv_file:
        print("{}".format(private_key.exportKey()), file=prv_file)
        prv_file.close()
    with open("GeneratedCerts\\" + myDomain + mytime + "PublicKeyRSA.pem",
              "w") as pub_file:
        print("{}".format(public_key.exportKey()), file=pub_file)
        pub_file.close()
        PublicKeyFileName = "GeneratedCerts\\" + myDomain + mytime + "PublicKeyRSA.pem"
        myPublicKeyinJsonFriendlyPem = open(PublicKeyFileName,
                                            "r").read().replace('b\''
                                                                '',
                                                                '').replace(
                                                                    '\''
                                                                    '', '')
    print("Step2 is finilized: Web key for the certificate is generated")

    #DomainKey
    d_private_key = RSA.generate(2048)
    d_public_key = d_private_key.publickey()
    #print(d_private_key.exportKey(format='PEM'))
    #print(d_public_key.exportKey(format='PEM'))
    with open(
            "GeneratedCerts\\" + myDomain + mytime + "DomainPrivateKeyRSA.pem",
            "w") as d_prv_file:
        print("{}".format(d_private_key.exportKey()), file=d_prv_file)
        d_prv_file.close()
    with open(
            "GeneratedCerts\\" + myDomain + mytime + "DomainPublicKeyRSA.pem",
            "w") as d_pub_file:
        print("{}".format(d_public_key.exportKey()), file=d_pub_file)
        d_pub_file.close()
    print("Step3 is finilized: Domain key for the CVR is generated")

    myRandomIdentifier = os.urandom(8).hex()  #Random Nonce 8 Bytes

    cert = {}
    cert['V'] = '4'
    cert['H'] = 'SHA256'
    cert['VT'] = '2020-12-25T13:28:06.419Z'
    cert['CN'] = myDomain
    cert['PublicKey'] = myPublicKeyinJsonFriendlyPem
    json_data = json.dumps(cert)

    certhash = hashlib.sha256(json_data.encode()).hexdigest()
    with open(
            "GeneratedCerts\\" + myDomain + mytime +
            "CertificateFileWithPublicKeyRSAUnsigned.jcrt", "w") as jcrt_file:
        print("{}".format(json_data), file=jcrt_file)

    certhash_bytes = bytes(certhash, "utf-8")

    signHash = SHA256.new(data=certhash_bytes)
    signer = PKCS1_v1_5.new(d_private_key)
    signature = signer.sign(signHash)

    cvr = {}
    cvr['C'] = cert
    cvr['I'] = myRandomIdentifier
    cvr['S'] = str(signature.hex())

    cvr_json_data = json.dumps(cvr)
    with open(
            "GeneratedCerts\\" + myDomain + mytime +
            "CVRFileWithPublicKeyRSASigned.jcrt", "w") as cvr_jcrt_file:
        print("{}".format(cvr_json_data), file=cvr_jcrt_file)

    print(
        "Step4 is finilized: Certificate W/O Proof and Signed CVR are generated"
    )
    print("The Identifier for the APKME and domain publickey locator is: " +
          myRandomIdentifier)

    mariadb_connection = mariadb.connect(user='******',
                                         password='******',
                                         host='consensuspkidbhost',
                                         database='consensuspki')
    mariadb_connection2 = mariadb.connect(user='******',
                                          password='******',
                                          host='consensuspkidbhost',
                                          database='consensuspki')
    cursor = mariadb_connection.cursor()
    insertCursor = mariadb_connection2.cursor()
    cursor.execute("select random_hash, domain from vw_tmp_random")

    print("Step5 is finilized: Random domains are selected")

    mt = merkletools.MerkleTools()
    certificateMerkleTree = []
    myCertificateRandomPosition = (random.randint(1, 1023) * 2)
    # in the ConsensusPKI the certificates are placed in the certificates merkle tree based on the lexicographic order of the the hash values of the certificates
    #myCertificateRandomPosition = int(random.randint(1,7) * 2) ; # in the PoC we used the random order to demonstrate the process
    i = 0

    for random_hash, domain in cursor:
        if i == myCertificateRandomPosition:
            certificateMerkleTree.append(certhash)
            certificateMerkleTree.append(randomEvidenceMerkleRoot)
            certificateMerkleTree.append(
                format(random_hash).replace("'", "").replace(",", "").replace(
                    "(", "").replace(")", ""))

            mySubject = calculate_hash(
                format(domain).replace("'", "").replace(",", "").replace(
                    "(", "").replace(")", "").encode())
            insertCursor.execute(
                "insert into subjects (YEAR,HEIGHT,SUBJECT) values (%s,%s,%s)",
                ('2020', '0', mySubject))

            insertCursor.execute(
                "insert into subjects (YEAR,HEIGHT,SUBJECT) values (%s,%s,%s)",
                ('2020', '0', calculate_hash(myDomain.encode())))
            print(
                "Step6 is finilized: The certificate is placed in the Merkle tree"
            )

        else:
            certificateMerkleTree.append(
                format(random_hash).replace("'", "").replace(",", "").replace(
                    "(", "").replace(")", ""))

            mySubject = calculate_hash(
                format(domain).replace("'", "").replace(",", "").replace(
                    "(", "").replace(")", "").encode())
            insertCursor.execute(
                "insert into subjects (YEAR,HEIGHT,SUBJECT) values (%s,%s,%s)",
                ('2020', '0', mySubject))

        i = i + 1
    #print(certificateMerkleTree);
    mt.add_leaf(certificateMerkleTree, False)

    mt.make_tree()
    #print(mt.get_leaf_count());
    root = mt.get_merkle_root()
    print(
        "Step7 is finilized. The merkle tree is constructed. The position of the certificate is: "
        + str(myCertificateRandomPosition))

    print("Step8 is finilized: Merkle Root of Certificate No: " +
          str(myCertificateRandomPosition))
    print(root)

    proof = mt.get_proof(myCertificateRandomPosition)
    print("Step 8: the Proof of Certificate No: " +
          str(myCertificateRandomPosition))
    print(proof)

    certWithProof = {}
    certWithProof['C'] = cert
    certWithProof['P'] = proof
    json_data_with_proof = json.dumps(certWithProof)
    with open(
            "GeneratedCerts\\" + myDomain + mytime +
            "CertificateFileWithPublicKeyRSAWithProof.jcrt",
            "w") as jcrt_file_with_proof:
        print("{}".format(json_data_with_proof), file=jcrt_file_with_proof)

    #print(int(round(time.time() * 1000)));

    targetHash = mt.get_leaf(myCertificateRandomPosition)
    #print("Targethash");
    #print(targetHash);
    #print("Certhash");
    #print(certhash);

    merkleRoot = root
    print(
        "Step 9 and 10 are finilized: All subjects are inserted into the subjects table"
    )

    insertCursor.execute(
        "insert into certificateblockchain  (Year,Height,PreviousBlockHeader,BlockHeader,MerkleRoot,Nonce,BlockTimestamp)  values (%s,%s,%s,%s,%s,%s,now())",
        ('2020', '0', 'p', 'b', root, '1'))
    print(
        "Step 11 is finilized: the record is inserted into the certificateblockchain table"
    )
    print("Step 12: Updating the temporary fields to start PoW")
    insertCursor.execute(
        "update subjects s set height = (select max(height) + 1 from certificateblockchain c where c.year = s.YEAR) where s.year = 2020 and s.height =0"
    )
    insertCursor.execute(
        "update certificateblockchain s set height = (select max(height) + 1 from certificateblockchain c where c.year = s.YEAR) , s.PreviousBlockHeader =  (select BlockHeader from certificateblockchain t where t.year = s.YEAR and t.height = (select max(height) from certificateblockchain z where t.year = z.YEAR)) where s.year = 2020 and s.height =0"
    )

    print("Step 12: PoW is Started")
    insertCursor.execute(
        "call PoWCertificateBlockchain(2020,(select max(c.Height) from certificateblockchain c where c.Year = 2020),@nonce, @tstamp, @bheader)"
    )
    insertCursor.execute(
        "update certificateblockchain a set a.Nonce = @nonce, a.BlockTimestamp = @tstamp, a.BlockHeader =@bheader where a.Year= 2020 and a.Height = (select max(c.Height) from certificateblockchain c where c.Year = 2020)"
    )
    print("Step 12 is finilized: PoW is Finilized")
    mariadb_connection2.commit()
    print("Fingerprint of the Certificate No: " +
          str(myCertificateRandomPosition))
    print(targetHash)
    print(
        "Step 13 is finilized: The certificate and all related records are generated"
    )

    is_valid = mt.validate_proof(proof, targetHash, merkleRoot)

    #print (is_valid);
    #print (merkleRoot);

    CalculatedMerkelRoot = get_MerkleRootFromProof(targetHash, proof)

    #print (CalculatedMerkelRoot);
    print("The validation result of the Merkle root in the certificate file")
    print(CalculatedMerkelRoot == root)
Ejemplo n.º 18
0
def form():
    form = EmployerForm()

    semester_to_num = {
        'Fall': '1',
        'Winter': '2',
        'Spring': '3',
        'Summer': '4'}
    semester_value = form.semester.data
    year_value = form.year.data
    student_hash = form.hash.data

    session['semester'] = semester_value
    session['year'] = year_value
    session['hash'] = student_hash
    session['submitted_form'] = True

    if form.validate_on_submit():
        session['semester'] = semester_value
        session['year'] = year_value
        session['hash'] = student_hash
        session['submitted_form'] = True

        if semester_value and year_value and student_hash:
            try:
                uploaded_file = request.files['file']
                filename = secure_filename(uploaded_file.filename)

                if filename != '':
                    file_ext = os.path.splitext(filename)[1]
                    if file_ext not in current_app.config['UPLOAD_EXTENSIONS']:
                        abort(400)
                    uploaded_file.save(
                        os.path.join(
                            current_app.config['UPLOAD_PATH'],
                            f'merkle_proof_{student_hash}.txt'))
            except:
                abort(400)

            contract_address = Web3.toChecksumAddress(
                config('CONTRACT_ADDRESS'))

            w3 = Web3(HTTPProvider(config('WEB3_PROVIDER')))
            w3.eth.enable_unaudited_features()

            contract = w3.eth.contract(
                address=contract_address, abi=contract_abi.abi)

            converted_semester_value = semester_to_num[semester_value]
            graduating_class = int(converted_semester_value + year_value)
            merkle_root = contract.functions.getRoot(graduating_class).call()

            if merkle_root:
                mt = merkletools.MerkleTools()

                hex_merkle_root = hex(merkle_root).split('x')[-1]

                merkle_proof_file = open(
                    f'uploads/merkle_proof_{student_hash}.txt', 'r')
                merkle_proof_string = merkle_proof_file.read().replace("'", '"')
                merkle_proof = json.loads(merkle_proof_string)

                is_valid = mt.validate_proof(
                    merkle_proof,
                    student_hash,
                    hex_merkle_root)

                session['is_valid'] = is_valid

        return redirect(url_for('result.verification'))

    return render_template('form.html', form=form)
Ejemplo n.º 19
0
 def merkle_root(self):
     """Merkle root."""
     mt = merkletools.MerkleTools()
     mt.add_leaf(self.data, True)
     mt.make_tree()
     return mt.get_merkle_root()
Ejemplo n.º 20
0
def test_mining(total_utxo_set_size_for_merkle_tree,
                total_utxo_set_size_for_accumulator, num_of_inputs_in_tx,
                num_of_outputs_in_tx, num_of_txs_in_block):
    print("----------------------")
    print("total_utxo_set_size_for_merkle_tree =",
          total_utxo_set_size_for_merkle_tree)
    print("total_utxo_set_size_for_accumulator =",
          total_utxo_set_size_for_accumulator)
    print("num_of_inputs_in_tx =", num_of_inputs_in_tx)
    print("num_of_outputs_in_tx =", num_of_outputs_in_tx)
    print("num_of_txs_in_block =", num_of_txs_in_block)

    print("--> initialize and fill up Merkle tree state")
    merkle_tree = merkletools.MerkleTools()
    elements_for_merkle_tree = create_random_list(
        total_utxo_set_size_for_merkle_tree)
    tik = time.time()
    for i in range(len(elements_for_merkle_tree)):
        merkle_tree.add_leaf(str(i), True)
    merkle_tree.make_tree()
    tok = time.time()
    merkle_add_timing.append(tok - tik)
    print("<--   Done.", merkle_add_timing[-1])

    print("--> initialize and fill up accumulator state")
    n, A0, S, order = setup()
    if total_utxo_set_size_for_accumulator < num_of_inputs_in_tx * num_of_txs_in_block:
        print("please select larger total_utxo_set_size_for_accumulator.")
        return None
    elements_for_accumulator = create_random_list(
        total_utxo_set_size_for_accumulator)
    inputs_for_accumulator = elements_for_accumulator[0:(num_of_inputs_in_tx *
                                                         num_of_txs_in_block)]
    outputs_for_accumulator = create_random_list(num_of_outputs_in_tx *
                                                 num_of_txs_in_block)
    tik = time.time()
    A_post_batch_add, proof = batch_add(A0, S, elements_for_accumulator, n)
    inputs_nonces_list = [S[x] for x in inputs_for_accumulator]
    tok = time.time()
    acc_batch_add_genesis_timing.append(tok - tik)
    print("<--   Done.", acc_batch_add_genesis_timing[-1])

    print("--> prove membership Merkle tree")
    times = []
    merkle_proofs = []
    for i in range(num_of_inputs_in_tx * num_of_txs_in_block):
        tik = time.time()
        merkle_proofs.append(merkle_tree.get_proof(i))
        tok = time.time()
        times.append(tok - tik)
    sum_times = sum(times)
    merkle_proof_timing.append(sum_times /
                               num_of_inputs_in_tx)  # average ; per tx
    print("<--   Done. total:", sum_times, "; per tx:",
          merkle_proof_timing[-1])

    print("--> prove membership accumulator")
    times = []
    acc_mem_proofs = []
    for i in range(num_of_txs_in_block):
        tik = time.time()
        inputs_list = []
        for j in range(num_of_inputs_in_tx):
            inputs_list.append(inputs_for_accumulator[num_of_inputs_in_tx * i +
                                                      j])
        acc_mem_proofs.append(batch_prove_membership(A0, S, inputs_list, n))
        tok = time.time()
        times.append(tok - tik)
    sum_times = sum(times)
    acc_batch_prove_mem_timing.append(sum_times / len(times))  # average
    print("<--   Done. total:", sum_times, "; per tx:",
          acc_batch_prove_mem_timing[-1])

    print("--> prove membership accumulator with NI-PoE")
    times = []
    acc_mem_proofs_with_NIPoE = []
    for i in range(num_of_txs_in_block):
        tik = time.time()
        inputs_list = []
        for j in range(num_of_inputs_in_tx):
            inputs_list.append(inputs_for_accumulator[num_of_inputs_in_tx * i +
                                                      j])
        acc_mem_proofs_with_NIPoE.append(
            batch_prove_membership_with_NIPoE(A0, S, inputs_list, n,
                                              A_post_batch_add))
        tok = time.time()
        times.append(tok - tik)
    sum_times = sum(times)
    acc_batch_prove_mem_with_NIPoE_timing.append(sum_times /
                                                 len(times))  # average
    print("<--   Done. total:", sum_times, "; per tx:",
          acc_batch_prove_mem_with_NIPoE_timing[-1])

    print("--> Merkle tree verify membership")
    merkle_root = merkle_tree.get_merkle_root()
    merkle_leaves = []
    for i in range(num_of_inputs_in_tx * num_of_txs_in_block):
        merkle_leaves.append(merkle_tree.get_leaf(i))

    tik = time.time()
    for i in range(num_of_txs_in_block):
        for j in range(num_of_inputs_in_tx):
            assert merkle_tree.validate_proof(merkle_proofs[i],
                                              merkle_leaves[i], merkle_root)
    tok = time.time()
    merkle_verify_mem_per_block_timing.append(tok - tik)
    merkle_verify_mem_per_tx_timing.append(
        (tok - tik) / num_of_txs_in_block)  # average
    print("<--   Done. total (per block):",
          merkle_verify_mem_per_block_timing[-1], "; per tx:",
          merkle_verify_mem_per_tx_timing[-1])

    print("--> accumulator batch verify membership")
    tik = time.time()
    for i in range(num_of_txs_in_block):
        inputs_list = []
        for j in range(num_of_inputs_in_tx):
            inputs_list.append(inputs_for_accumulator[num_of_inputs_in_tx * i +
                                                      j])
        # TODO: nonces should be given by the proofs?
        nonces_list = list(map(lambda x: S[x], inputs_list))
        assert batch_verify_membership(A_post_batch_add, inputs_list,
                                       nonces_list, acc_mem_proofs[i], n)
    tok = time.time()
    acc_batch_verify_mem_per_block_timing.append(tok - tik)
    acc_batch_verify_mem_per_tx_timing.append(
        (tok - tik) / num_of_txs_in_block)  # average
    print("<--   Done. total (per block):",
          acc_batch_verify_mem_per_block_timing[-1], "; per tx:",
          acc_batch_verify_mem_per_tx_timing[-1])

    print("--> accumulator batch verify membership with NIPoE")
    tik = time.time()
    for i in range(num_of_txs_in_block):
        inputs_list = []
        for j in range(num_of_inputs_in_tx):
            inputs_list.append(inputs_for_accumulator[num_of_inputs_in_tx * i +
                                                      j])
        # TODO: nonces should be given by the proofs?
        nonces_list = list(map(lambda x: S[x], inputs_list))
        assert batch_verify_membership_with_NIPoE(
            acc_mem_proofs_with_NIPoE[i][0], acc_mem_proofs_with_NIPoE[i][1],
            acc_mem_proofs_with_NIPoE[i][2], inputs_list, nonces_list,
            A_post_batch_add, n)
    tok = time.time()
    acc_batch_verify_mem_with_NIPoE_per_block_timing.append(tok - tik)
    acc_batch_verify_mem_with_NIPoE_per_tx_timing.append(
        (tok - tik) / num_of_txs_in_block)  # average
    print("<--   Done. total (per block):",
          acc_batch_verify_mem_with_NIPoE_per_block_timing[-1], "; per tx:",
          acc_batch_verify_mem_with_NIPoE_per_tx_timing[-1])

    print("--> accumulator batch delete spent TXOs + first NI-PoE")
    tik = time.time()
    agg_inputs_indexes = []
    for i in range(num_of_txs_in_block):
        agg_inputs_indexes.append(
            [num_of_inputs_in_tx * i, num_of_inputs_in_tx * (i + 1)])
    # TODO: can we get the NI-PoE proofs here?
    A_post_batch_delete, niope1 = batch_delete_using_membership_proofs(
        A_post_batch_add, S, inputs_for_accumulator, acc_mem_proofs, n,
        agg_inputs_indexes)
    tok = time.time()
    acc_batch_delete_timing.append(tok - tik)
    print("<--   Done.", acc_batch_delete_timing[-1])

    print("--> accumulator batch add new UTXOs + second NI-PoE")
    tik = time.time()
    A_post_batch_add_new, niope2 = batch_add(A_post_batch_delete, S,
                                             outputs_for_accumulator, n)
    outputs_nonces_list = [S[x] for x in outputs_for_accumulator]
    tok = time.time()
    acc_batch_add_per_block_timing.append(tok - tik)
    print("<--   Done.", acc_batch_add_per_block_timing[-1])

    print("--> accumulator verify first NI-PoE & second NI-PoE")
    tik = time.time()
    assert batch_verify_membership_with_NIPoE(niope1[0], niope1[1],
                                              A_post_batch_delete,
                                              inputs_for_accumulator,
                                              inputs_nonces_list,
                                              A_post_batch_add, n)
    assert batch_verify_membership_with_NIPoE(niope2[0], niope2[1],
                                              A_post_batch_delete,
                                              outputs_for_accumulator,
                                              outputs_nonces_list,
                                              A_post_batch_add_new, n)
    tok = time.time()
    acc_batch_verify_two_NIPoE_post_mining.append(tok - tik)
    print("<--   Done.", acc_batch_verify_two_NIPoE_post_mining[-1])
Ejemplo n.º 21
0
import merkletools

sentence = 'I love chicken!'
# sentence = 'In our village, folks say God crumbles up the old moon into stars.'
input_words = [x for x in sentence.split()]
print(input_words)

mt = merkletools.MerkleTools()
mt.add_leaf(input_words, True)
print('leaves = ', mt.leaves)
print('hashes_of_leaves_in_hex = ', [x.hex() for x in mt.leaves])

mt.make_tree()
print("root = %s" % mt.get_merkle_root())