mascoda/php-blockchain

A simple blockchain written in PHP

dev-main 2022-10-28 14:49 UTC

This package is auto-updated.

Last update: 2024-06-28 16:31:26 UTC


README

php-blockchain

php-blockchain | a simple full-featured blockchain written in php

About php-blockchain

This project grew out of a Python-Blockchain course. I translated the Python code to PHP. Why? - Because I love PHP. It is neither an out-of-the-box nor a ready-to-use blockchain for productive use. Rather, it should help to understand the principles of a blockchain. You could say it's an educational library. Some things are a bit simplified, but all the functions that a real blockchain has are included. I am happy if this package helps to understand the great idea behind the blockchain.

Features

  • Simple structure to quickly understand the blockchain principle
  • Create wallets with a predefined amount of money
  • Create transactions to transfer money from one wallet to another
  • Calculate a valid block from the mempool (mining) and write it into the blockchain
  • Simple JSON storage to be able to understand all actions transparently
  • Easy to expand and configure

License

This software is distributed under the LGPL 2.1 license. Please read LICENSE for information on the software availability and distribution.

Legacy versions

php-blockchain supports >= PHP 8

php-blockchain

Installation

php-blockchain is available on Packagist, and installation via composer is the recommended way to install php-blockchain. Just add this line to your composer.json file:

"mascoda/php-blockchain": "dev-main"

or run

composer require mascoda/php-blockchain

php-blockchain declares the namespace Mascoda\PhpBlockchain.

Blockchain

Create an instance of blockchain, this will be created a genesis block if not exists

use Mascoda\PhpBlockchain\Chain;

$blockchain = new Chain();

/*
* Difficulty Explanation. The difficulty is a measure of how difficult it is to mine a Bitcoin block, or in more technical terms,
* to find a hash below a given target. A high difficulty means that it will take more computing power to mine the same
* number of blocks, making the network more secure against attacks.
*
* Caution: A high value can have a huge impact on performance. It is recommended to test with the default value of 2.
*/
$blockchain->setDifficulty(2);

/*
* Use the setConfig method to add various attributes to the blockchain. You can add as many attributes as you want via key->value.
* Existing attributes are overwritten using the setConfig method.
* The attributes are permanently stored in the associated json file (blockchain.json).
*/
$blockchain->setConfig("coinname", "chaincoin");
$blockchain->setConfig("symbol", "cc");
$blockchain->setConfig("description", "Description of my blockchain");

/*
* The configured attributes can be loaded via the get method via the key.
*/
$blockchain->get("coinname");

php-blockchain

Wallets

Create new wallets

use Mascoda\PhpBlockchain\Wallet;

/*
* A blockchain wallet is a digital wallet that allows users to store and manage their coins.
* For testing, it is therefore recommended to use the setDefaultValue function so that transactions between the wallets are possible.
*/
$wallet = new Wallet();

/*
* Set a default balance for the wallet (optional)
* (default amount of coins in the new wallet)
*/
$wallet->setDefaultValue(1.0);

/*
* Creates a new wallet with an associated public/private key pair. If no default value has been set, the wallet contains a sum of money of 0.
* For testing, it is therefore recommended to use the setDefaultValue function so that transactions between the wallets are possible.
*/
$new_wallet = $wallet->create();

/*
* The wallet data can be accessed as follows.
*/
$new_wallet->public_key;
$new_wallet->private_key;
$new_wallet->value;

php-blockchain

Transactions

A transaction is similar to a bank transfer. A defined sum of coins is exchanged between debtor and recipient. The transfer is verified using the debtor's private key.

use Mascoda\PhpBlockchain\Transaction;

// The public key from the creditor
$creditor = "47db88753ef6fdeb4ae117353901d389a880ae32f3861638e4499412d726d5c9";
// The private key from the creditor
$private_key = "c640afeaaa73afdddc4f94fa16bc0cdc92a6f1af90687d372972d22d2c1bd7bb";
// The public key (wallet id) from the creditor
$debitor = "dda000b6bd36936d340d4999245cb9e9556df1f6546d81b82892c0ebd668bd37";
// The amount to be transferred to the debitor.
$amount = 0.001;

// Create a new transaction with the parameters shown above.
$transaction = new Transaction($creditor, $private_key, $debitor, $amount);


/*
* Whether a **transaction** is valid can be checked using the isValid method. While it is possible to add the transaction directly
* to the mempool, it will then be rejected. The isValid method gives a notification on an invalid transaction as to why it is invalid,
* if valid returns TRUE.
*/
$response = $transaction->isValid();
var_dump($response);

/*
* If the **transaction** is valid, it can be added to the **mempool** using the add method.
* More about the mempool is explained below.
*/
$response = $transaction->add();

php-blockchain

Mempool

In blockchain terminology, a mempool is a waiting area for the transactions that haven't been added to a block and are still unconfirmed. This is how a Blockchain node deals with transactions that have not yet been included in a block.

use Mascoda\PhpBlockchain\Mempool;

/*
* In blockchain terminology, a **mempool** is a waiting area for the transactions that haven't been added to a block and are
* still unconfirmed. This is how a Blockchain node deals with transactions that have not yet been included in a block.
* Note: After the unconfirmed transactions have been added to a block (mining), they are permanently deleted from the mempool.
*/
$mempool = new Mempool();

/*
* The get method can be used to see all current "waiting" transactions from the mempool.
*/
$unconfirmed_transactions = $mempool->get();

foreach ($mempool->get() as $transaction) :
  echo "tx: ", $transaction->tx, "<br>" . PHP_EOL;
  echo "timestamp: ", $transaction->timestamp, "<br>" . PHP_EOL;
  echo "amount: ", $transaction->amount, "<br>" . PHP_EOL;
  echo "from creditor: ", $transaction->creditor, "<br>" . PHP_EOL;
  echo "to debitor: ", $transaction->debitor, "<br>" . PHP_EOL;
  echo "<br><br>" . PHP_EOL;
endforeach;

php-blockchain

Nodes & Mining

In this blockchain, the mining process is shown in a simplified way. Usually, different computers (miners) run in a kind of competition, the winner is the one who has the fastest time to calculate a valid hash based on the difficulty. The winner then receives a defined number of coins and the transaction fees.

In this app, the mining process is simulated and calculated using an imaginary node. This node also takes the difficulty into account and tries to calculate a valid hash. The number of attempts it takes to calculate a valid hash is also called "Nonce". The nonce is added to each block as an integer value.

use Mascoda\PhpBlockchain\Chain;
use Mascoda\PhpBlockchain\Node;

$blockchain = new Chain();
$node = new Node();

/*
* The node calculates a valid hash based on the difficulty. If successful, the block is returned with a valid hash.
*/
$new_block = $node->mining();
var_dump($new_block);

/*
* The valid block can now be added to the blockchain. All transactions are validated and settled.
* The mempool is then automatically emptied.
*/
$blockchain->addBlock($new_block);

/*
* Reminder: All transactions are now on the blockchain. In our example in the "blockchain.json"
*/

php-blockchain

Security

This package is for educational purposes only, you are warned against productive use.

Changelog

See changelog.

ToDos

  • Explorer class - provides various methods for explore the blockchain.