Skip to content

Instantly share code, notes, and snippets.

@drupol
Last active December 16, 2019 16:38
Show Gist options
  • Save drupol/f59bb5c2d1b464ed027a40f63dd034da to your computer and use it in GitHub Desktop.
Save drupol/f59bb5c2d1b464ed027a40f63dd034da to your computer and use it in GitHub Desktop.
PHPTree is now having a Merkle node type.
<?php
declare(strict_types=1);
use drupol\launcher\Launcher;
use drupol\phptree\Exporter\Image;
use drupol\phpmerkle\Hasher\DummyHasher;
use drupol\phptree\Node\MerkleNode;
include './vendor/autoload.php';
// Default node capacity.
// This is the maximum number of children that a node can have.
// A Merkle node is a binary tree, so by default it uses 2.
// Using another value is fully possible.
$capacity = 2;
// By default, a Merkle tree uses a double SHA256 encoding.
// For this demo, I'm using a dummy hasher that returns the $value without hashing it.
$hasher = new DummyHasher();
// Create the root node.
$tree = new MerkleNode('root', $capacity, $hasher);
// Prepare the data to use.
$sentence = 'Science is made up of so many things that appear obvious after they are explained .';
$input = array_merge(array_pad([], 14, null), explode(' ', $sentence));
// Add the nodes to the tree.
foreach ($input as $v) {
$tree[] = new MerkleNode($v, $capacity, $hasher);
}
// Export the tree to an image.
$imagePath = (new Image())->setFormat('png')->export($tree);
// To open the image directly, you can use an optional package: drupol/launcher
// do: composer require drupol/launcher
// Then you'll be able to use the Launcher.
Launcher::open($imagePath);
@drupol
Copy link
Author

drupol commented Dec 11, 2019

This script produces this image (using a DummyHasher):

graphvizDogmQZ

Using a DoubleSha256 hasher:

graphvizh8gOxK

@drupol
Copy link
Author

drupol commented Dec 11, 2019

Now using a randomized tree with fake ids as values.

graphvizrexR4H

And the normalization of the tree, needed to computer the hashes:

graphvizsPolqc

@drupol
Copy link
Author

drupol commented Dec 16, 2019

We can even change the maximum amount of children that a node can have. This is no more a binary tree (2 children only). Each node can have maximum 3 children.

graphvizNxheI5

After normalization:

graphvizj1nJUW

@drupol
Copy link
Author

drupol commented Dec 16, 2019

Another example with maximum 4 children:

graphvizLmosLN

After normalization:

graphvizNTGl1T

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment