Building a Simple Blockchain in PHP

shaggyrec

Alex Awesome

Posted on March 21, 2023

Building a Simple Blockchain in PHP

Please don't shout «Whyyyyyyyyy?». It's just a crazy experiment to show that everyone can implement their own blockchain. Probably PHP programmers also want to create a blockchain as best they can.

Blockchain technology has become increasingly popular due to its decentralized nature and the ability to store data securely. In this article, we'll create a simple blockchain using PHP, demonstrating blockchain technology's basic concepts and principles:

  1. Creating a Block class
  2. Creating a Blockchain class
  3. Adding blocks to the blockchain
  4. Validating the blockchain
  5. Additional examples and use cases

Let's get started!

1. Creating a Block class

The first step in creating our blockchain is to define the basic building block: the Block class. Each block will contain an index, a timestamp, data, a previous hash, and its own hash. We'll also create a function to generate the hash for a block.

class Block
{
    public int $index;
    public string $timestamp;
    public $data;
    public string $previousHash;
    public string $hash;

    public function __construct(int $index, string $timestamp, $data, string $previousHash = '')
    {
        $this->index = $index;
        $this->timestamp = $timestamp;
        $this->data = $data;
        $this->previousHash = $previousHash;
        $this->hash = $this->calculateHash();
    }

    public function calculateHash(): string
    {
        return hash(
            'sha256', 
            sprintf(
               '%d%s%s%s',
               $this->index,
               $this->timestamp,
               $this->previousHash,
               json_encode($this->data),
           )
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Creating a Blockchain class

Next, we'll create a Blockchain class that will manage our chain of blocks. This class will have functions for creating the genesis block, adding new blocks, and validating the integrity of the blockchain.

class Blockchain
{
    public array $chain;

    public function __construct()
    {
        $this->chain = [$this->createGenesisBlock()];
    }

    private function createGenesisBlock(): Block
    {
        return new Block(0, '01/01/2023', 'Genesis Block', '0');
    }

    public function getLatestBlock(): Block
    {
        return $this->chain[count($this->chain) - 1];
    }

    public function addBlock(Block $newBlock): void
    {
        $newBlock->previousHash = $this->getLatestBlock()->hash;
        $newBlock->hash = $newBlock->calculateHash();
        $this->chain[] = $newBlock;
    }

    public function isChainValid(): bool
    {
        for ($i = 1, $chainLength = count($this->chain); $i < $chainLength; $i++) {
            $currentBlock = $this->chain[$i];
            $previousBlock = $this->chain[$i - 1];

            if ($currentBlock->hash !== $currentBlock->calculateHash()) {
                return false;
            }

            if ($currentBlock->previousHash !== $previousBlock->hash) {
                return false;
            }
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Adding blocks to the blockchain

Now that we have our Block and Blockchain classes, let's create a new instance of the Blockchain class and add some blocks.

$myBlockchain = new Blockchain();
$myBlockchain->addBlock(new Block(1, '10/03/2023', ['amount' => 50]));
$myBlockchain->addBlock(new Block(2, '15/03/2023', ['amount' => 100]));
Enter fullscreen mode Exit fullscreen mode

4. Validating the blockchain

To ensure the integrity of our blockchain, we'll use the isChainValid() function to check if our chain is valid.

echo 'Is blockchain valid? ' . ($myBlockchain->isChainValid() ? 'Yes' : 'No') . "\n";
Enter fullscreen mode Exit fullscreen mode

5. Additional examples and use cases

Now let's explore a few more examples of using our simple PHP blockchain.

Example: Displaying the blockchain

function displayBlockchain(Blockchain $blockchain): void
{
    foreach ($blockchain->chain as $block) {
        echo "Index: " . $block->index . "\n";
        echo "Timestamp: " . $block->timestamp . "\n";
        echo "Data: " . json_encode($block->data) . "\n";
        echo "Previous Hash: " . $block->previousHash . "\n";
        echo "Hash: " . $block->hash . "\n\n";
    }
}

displayBlockchain($myBlockchain);
Enter fullscreen mode Exit fullscreen mode

Example: Tampering with the blockchain and validating

// Tamper with the second block's data
$myBlockchain->chain[1]->data = ['amount' => 75];

// Check if the blockchain is still valid
echo "Is blockchain valid after tampering? " . ($myBlockchain->isChainValid() ? "Yes" : "No") . "\n";
Enter fullscreen mode Exit fullscreen mode

Conclusion:

In this article, we've built a simple blockchain in PHP. Why? I have no idea! But we've explored the creation of the Block and Blockchain classes, adding blocks to the blockchain, validating the integrity of the chain, and using our blockchain in various examples.

While this implementation is straightforward and suitable for educational purposes, it is important to note that real-world blockchains are far more complex, incorporating consensus algorithms, distributed networks, and more advanced security measures. However, this introduction to the basics of blockchain technology provides a solid foundation for understanding and further exploring the world of decentralized systems.

💖 💪 🙅 🚩
shaggyrec
Alex Awesome

Posted on March 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related