Skip to content

Commit

Permalink
update: merkle root python
Browse files Browse the repository at this point in the history
  • Loading branch information
jambtc committed Jun 19, 2023
1 parent b29d933 commit a0328e9
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 13 deletions.
27 changes: 21 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ corrisponda a quello salvato in blockchain.

## Guida

- Clona questo software oppure scaricalo da questo <a href="https://github.com/jambtc/merkle-root-php/releases/tag/v1.2">link</a> in una cartella sul tuo pc.
- Clona questo software oppure scarica l'ultima versione da questo <a href="https://github.com/jambtc/merkle-root-php/releases/">link</a> in una cartella sul tuo pc.
- Copia i file json sia del Qldb che della Blockchain sotto questa stessa cartella.
- Apri una finestra shell o prompt e digita i seguenti comandi:

Expand All @@ -33,13 +33,15 @@ cd <nomecartella>
php index.php
```

Il software ti permette di selezionare 3 scelte:
Il software ti permette di selezionare 4 scelte:

1. Verifica Merkle Root
2. Estrai i Merkle Root dal file QLDB
3. Estrai i Merkle Root dal file Blockchain
1. Compara i Merkle Root
2. Estrai il Merkle Root dal file QLDB
3. Estrai il Merkle Root dal file Blockchain
4. Mostra gli hash dei file

Dovresti ottenere una risposta di questo tipo:

Selezionando la prima opzione, dovresti ottenere una risposta di questo tipo:

```bash
Merkle Root Calculator
Expand All @@ -49,3 +51,16 @@ Merkle root da Blockchain: 36d12cb8e28699290b0cef1ea5a1fadfd2c6bc4afad02633330e8
Merkle root da QLDB: 36d12cb8e28699290b0cef1ea5a1fadfd2c6bc4afad02633330e86b197b61884
Verifica Merkle root: SUCCESSO
```

## Verifica online in php

Se non si ha a disposizione un ambiente php installato, è possibile effettuare un controllo online
del merkle root.
Si può utilizzare il sito <https://onlinephp.io/> e copiare al suo interno il contenuto del file `online.php`

E' necessario però modificare manualmente il contenuto dell'array `$data`, con i valori di hash che si vuole controllare dal file qldb.

## Verifica online in python

E' possibile anche usare uno script in python che funziona allo stesso modo.
Legge l'array elements e ne produce il merkle root. Il file da usare, in questo caso, è `online.py`
7 changes: 7 additions & 0 deletions func/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ function verificaMerkleRoot($qldb_json, $blockchain_json)
if ($matchDate >= $dateFromPeriod->startDate && $matchDate <= $dateFromPeriod->finishDate) {
// se appartiene al periodo la salvo in array
$qldb_hashes[$matchDate->format('Y-m')][] = $qldb->document_hash;
// $timestamp_qldb_hashes[$qldb->activity_timestamp][] = $qldb->document_hash;

// salvo anche le informazioni del merkle root della blockchain relative
$blockchain_data[$matchDate->format('Y-m')] = $merkleRootByPeriod;
Expand All @@ -93,6 +94,12 @@ function verificaMerkleRoot($qldb_json, $blockchain_json)
}
}

// echo '<pre>' . print_r($timestamp_qldb_hashes, true) . '</pre>';
// asort($timestamp_qldb_hashes);
// echo '<pre>' . print_r($timestamp_qldb_hashes, true) . '</pre>';

// exit;

return [
'qldb_hashes' => $qldb_hashes,
'blockchain_data' => $blockchain_data,
Expand Down
22 changes: 15 additions & 7 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
echo "Merkle Root Calculator\n\n";

echo "Fai la tua scelta:\n\n";
echo " 1. Verifica Merkle Root\n";
echo " 2. Estrai i Merkle Root dal file QLDB\n";
echo " 3. Estrai i Merkle Root dal file Blockchain\n";
echo " 1. Compara i Merkle Root\n";
echo " 2. Estrai il Merkle Root dal file QLDB\n";
echo " 3. Estrai il Merkle Root dal file Blockchain\n";
echo " 4. Mostra gli hash dei file\n";
$scelta = readline();

if ($scelta != '1' && $scelta != '2' && $scelta != '3'){
if ($scelta != '1' && $scelta != '2' && $scelta != '3' && $scelta != '4'){
echo "\nScelta non consentita!\n\n";
die();
}
Expand All @@ -23,6 +24,13 @@

// Estraggo le informazioni dai file
$result = verificaMerkleRoot($qldb_json, $blockchain_json);
if ($scelta == '4'){
unset($result['qldb_hashes']);
echo '<pre>' . print_r($result, true) . '</pre>';
exit;

}


if ($scelta == '1'){
foreach ($result['blockchain_data'] as $period => $merkleRoot) {
Expand All @@ -31,7 +39,7 @@
$qldb_root = $merkle->root($result['qldb_hashes'][$period]);

// stampo il risultato per singolo periodo
echo "Periodo: $period\n";
echo "\nPeriodo: $period\n";
echo "Merkle root da Blockchain: $merkleRoot\n";
echo "Merkle root da QLDB: $qldb_root\n";
echo "Verifica Merkle root: " . ($merkle->verify($result['qldb_hashes'][$period], $merkleRoot) ? 'SUCCESSO' : 'FALLITO') . "\n";
Expand All @@ -47,7 +55,7 @@
$qldb_root = $merkle->root($hashes);

// stampo il risultato per singolo periodo
echo "Periodo: $period\n";
echo "\nPeriodo: $period\n";
echo "Merkle root da QLDB: $qldb_root\n";
}

Expand All @@ -58,7 +66,7 @@
foreach ($result['blockchain_data'] as $period => $merkleRoot) {

// stampo il risultato per singolo periodo
echo "Periodo: $period\n";
echo "\nPeriodo: $period\n";
echo "Merkle root da Blockchain: $merkleRoot\n";
}

Expand Down
58 changes: 58 additions & 0 deletions online.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php
class MerkleRoot
{
/**
* Calcola il Merkle Root
*
* La funzione calcola il Merkle Root a partire dai dati passati come argomento, utilizzando
* la funzione hash SHA256 per calcolare gli hash dei singoli elementi e degli hash intermedi.
* Viene restituito il Merkle Root, ovvero l'hash della radice del Merkle Tree.
*
* @param array $data Array di hash
* @return string Merkle root
*/
public function root(array $data): string
{
// Se il numero di elementi è dispari, duplica l'ultimo elemento
if (count($data) % 2 != 0) {
$data[] = end($data);
}

// Calcola gli hash dei singoli elementi
foreach ($data as $element) {
$merkle_tree[] = hash('sha256', $element);
}

// Calcola gli hash intermedi
while (count($merkle_tree) > 1) {
$level = [];
for ($i = 0; $i < count($merkle_tree); $i += 2) {
$left = $merkle_tree[$i];
$right = isset($merkle_tree[$i + 1]) ? $merkle_tree[$i + 1] : $left;
$level[] = hash('sha256', $left . $right);
}
$merkle_tree = $level;
}

return $merkle_tree[0];
}

}

// array di dati
$data = [
'2b44e6ec8a82f17f87f17c62b7c10b98afb0e84d8247417c7e276a438ae81d1b',
'2b44e6ec8a82f17f87f17c62b7c10b98afb0e84d8247417c7e276a438ae81d1b',
'2b44e6ec8a82f17f87f17c62b7c10b98afb0e84d8247417c7e276a438ae81d1b',
'2b44e6ec8a82f17f87f17c62b7c10b98afb0e84d8247417c7e276a438ae81d1b',
'5f2fb9087b45d6a030b1827a21dcd1816d24fec6833afff8183bafbee95e72a0'
];

// inizializzo la classe
$merkle = new MerkleRoot();

// genero il Merkle root
$root = $merkle->root($data);


echo "Merkle root: $root\n";
32 changes: 32 additions & 0 deletions online.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import hashlib

def merkle_root(data):
# Se il numero di elementi è dispari, duplica l'ultimo elemento
if len(data) % 2 != 0:
data.append(data[-1])

# Calcola gli hash dei singoli elementi
merkle_tree = [hashlib.sha256(element.encode()).hexdigest() for element in data]

# Calcola gli hash intermedi
while len(merkle_tree) > 1:
level = []
for i in range(0, len(merkle_tree), 2):
left = merkle_tree[i]
right = merkle_tree[i + 1] if i + 1 < len(merkle_tree) else left
combined = left + right
level.append(hashlib.sha256(combined.encode()).hexdigest())
merkle_tree = level

return merkle_tree[0]

elements = [
'2b44e6ec8a82f17f87f17c62b7c10b98afb0e84d8247417c7e276a438ae81d1b',
'2b44e6ec8a82f17f87f17c62b7c10b98afb0e84d8247417c7e276a438ae81d1b',
'2b44e6ec8a82f17f87f17c62b7c10b98afb0e84d8247417c7e276a438ae81d1b',
'2b44e6ec8a82f17f87f17c62b7c10b98afb0e84d8247417c7e276a438ae81d1b',
'5f2fb9087b45d6a030b1827a21dcd1816d24fec6833afff8183bafbee95e72a0'
];

result = merkle_root(elements)
print("Merkle root: " + result)

0 comments on commit a0328e9

Please sign in to comment.