How Blockchain works with PHP and JSON?

In this article, we will see how blockchain works with PHP and JSON and create a simple blockchain to add new blocks.

Structure of Blockchain

How Blockchain works: As we already know, a blockchain may be used to record data other than economic transactions. Furthermore, the most interesting blockchain systems have a distributed design in which no one person is the true owner of the record.

As a first step into the field of blockchains, I’d like to make things as basic as possible: we’ll build a centralized (rather than distributed) blockchain. That can log transactions conducted with SofthuntCoin, our selected test currency for this article.

Each new piece of data (a transaction) on a blockchain is kept in a block placed at the end of the chain. This last block, which will be added to the chain, leverages some information from the preceding block to ensure the log’s integrity and immutability.

Our initial task will be to define the structure of our blockchain’s blocks. To store the blockchain, I chose a simple JSON file. JSON is a well-known format that can be readily read and written using Php. The programming language we will use to interface with data.

Let’s start by building our basic blockchain with the first block in it, in a new file called chain.json

{"chain":		
	[{
	"index":0,
	"hashid":"first-block",
	"timestamp":1541152127213,
	"proof-of-work":"xyz",
	"content":
		{
		"from":"network",
		"to":"Ranjeet",
		"amount":1
		}
	}]
}

Description of Attributes

Our blockchain to manage SofthuntCoin transactions is made by blocks, each one having the following attributes:

  1. Index : a basic unique numeric integer ID (beginning at 0) Keeping it simple will allow us to simply count the total blocks in our chain at any moment.
  2. Hashid : For this first block, I select an arbitrary value. In the next blocks, we will utilize a specific function to calculate the value of the hashid property. Which will use some of the data stored in the previous block to generate a unique and consistent result.
  3. Timestamp : The creation date of the block. In this case, I am using a simple Unix Timestamp (in milliseconds).
  4. Proof of Work : Proof of work is required in a fully operating blockchain system in order to add a new block to the chain. Proof of work is often the answer to a complicated cryptographic issue, although it may be anything depending on the blockchain ecosystem you are creating. 
  5. Content : This attribute contains structured data about the transaction. A financial transaction is identifiable in its most basic form by a sender (from), a receiver (to), and the amount of cash transferred (amount). The sender of this first transaction is the system (network), the recipient is a user named Ranjeet, and the value traded is 1 SofthuntCoin.

Reading this blockchain, we can see that a user named “Ranjeet” received 1 SofthuntCoin from the SoftuntCoin System, which was recognized by the particular user “network”. This unique user is the only one who can generate new SofthuntCoins. Other users can exchange SofthuntCoins with one another.

Read the Blockchain

Once the basic structure of our blockchain has been defined, we can start coding a basic Data Access Object in Php. Our object should be able to:

  • read our blockchain
  • read data about the last block in the blockchain
  • calculate a valid hash to be use by a new block, and insert it in the blockchain

The following code is place in includes/blockchain.php

<?php

class Blockchain {

  function read_all() {
    try {
      $jsondata = file_get_contents(dirname(dirname(__FILE__))."/chain.json");
      $arr_data = json_decode($jsondata, true);
      return $arr_data;
    }
    catch(Exception $e) {
      echo "Error: " . $e->getMessage();
      exit();
    }
  }

  function get_previous_hashid($chain){
    $lastEl = array_values(array_slice($chain, -1))[0];
    return $lastEl["hashid"];
  }

  function get_previous_index($chain){
    $lastEl = array_values(array_slice($chain, -1))[0];
    return $lastEl["index"];
  }

 function get_new_hashid($previous_hashid,$index,$timestamp,$content){
   $full_string = $previous_hashid.$index.$timestamp.$content;
   $hash  = hash('sha256',$full_string);
   return $hash;
 }

 function read_content($content) {
   $arr_content = json_decode($content);
   return $arr_content;
 }
}
?>

read_all() reads the whole blockchain and stores it in a multidimensional array. This little prototype is useful for testing, but it should not be utilize in a production situation where the blockchain might expand to terabytes of data.

The get_previous_hashid() and get_previous_index() functions help us retrieve the index and hashid values of the last inserted block in the chain. We need those values in order to compute the right hashid for the next block we want to append.

Each system develops its own procedures for calculating the data of a new block. In our SofthuntCoin system, we have decided that each new block must have an attribute called hashid. Which is the hash (sha256) of four strings: hashid, index, and timestamp from the previous block, and content from the new block that we are producing. You can now see why the first block does not have any calculated hashid.

The last function in blockchain.php, read_content(). Allows us to save the content of a block (sender, receiver, and amount) in a multidimensional array. So that we may work on them later when constructing a new block.

Write a New Block

Now that we’ve finished our Data Access Object, we can develop a simple script to begin experimenting with our blockchain prototype. In the root of our application folder, we create a new file called chain.php and begin writing the code below. Which allows us to read and display the whole blockchain.

<?php
  // including basic configuration file and Data Access Object class
  include_once("./includes/config.php");
  include_once("./includes/blockchain.php");

  // initializing the class
  $Blockchain = new BLOCKCHAIN();

  // loading the full blockchain in an array and showing it as output on the webpage
  $full_chain = $Blockchain->read_all();
  echo "full blockchain loaded:<br />";
  echo '<pre>',print_r($full_chain["chain"],1),'</pre>';
  echo "<hr />";

The following code helps us to read the index and hashid of the last block in the blockchain:

<?php 
// reading last block's hash id
  $previous_hashid = $Blockchain->get_previous_hashid($full_chain["chain"]);
  echo "reading last block's hash id:<br />";
  echo $previous_hashid;
  echo "<hr />";

  // reading last block's index to calculate next index
  $previous_index = $Blockchain->get_previous_index($full_chain["chain"]);
  $next_index = $previous_index+1;
  echo "reading last block's index to calculate next index:<br />";
  echo "Last: " .$previous_index. " | Next: ".$next_index;
  echo "<hr />";

Now we can calculate the new block values. Retrieving the index of the new block is pretty straightforward: in our SofthuntCoin environment index is an integer, just the previous block’s index incremented by 1.

The new hashid is calculated using get_new_hashid() method in the Blockchain class. It will be a new hash (sha256) based on the concatenation of:

  • last block’s hash id +
  • new block’s index +
  • new block’s timestamp +
  • new block’s content
<?php 
  echo "New hashid:<br />";
  $timestamp = round(microtime(true) * 1000);
  // example content
  // $content = '{"from": "network","to": "Ranjeet","amount": 1000}';
  $content = $_POST["json_data"];
  $new_hashid = $Blockchain->get_new_hashid($previous_hashid,$next_index,$timestamp,$content);
  echo $new_hashid;
  echo "<hr />";

You’ve probably noticed that the variable $content. Which should hold our transaction’s significant data, has the value of a “json data” POST variable. To experiment with our mini blockchain environment. We can develop a basic form in a new file named post.php and place it in the same folder that can POST JSON data to our chain.php script. By manually uploading new transactions to our blockchain, we can ensure that each new block is accurately added.

Here’s our post.php file:

<form action="chain.php" method="post">
<textarea name="json_data">
  {
    "from": "network",
    "to": "Ranjeet",
    "amount": 1
  }
</textarea>
<input type="submit">
</form>

This form, as you can see, transmits raw JSON data to chain.php. Changing the From, To, and Amount variables will result in various transactions being record in our blockchain.

Conclusion of How Blockchain works

That’s all for How Blockchain works with PHP and JSON. If you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. What is Blockchain and How Does it Work?
  2. Creating Simple Cryptocurrency Blockchain Using JavaScript and Node.js

Leave a Comment