← Back to News

Cryptocurrency

The Fundamental Code of a Blockchain

A blockchain is defined as ‘a continuously growing list of records, called blocks, which are linked and secured using cryptography.’ This article will break down some of the most fundamental aspects of how a blockchain is made, and how it executes.   Block structure One of the first steps to building a blockchain is to […]

By CJ Reichel · May 7, 2018
The Fundamental Code of a Blockchain

A blockchain is defined as ‘a continuously growing list of records, called blocks, which are linked and secured using cryptography.’ This article will break down some of the most fundamental aspects of how a blockchain is made, and how it executes.

 

Block structure

One of the first steps to building a blockchain is to determine block structure. In order for the code to execute, the hash power of the previous block must be shown on the current block in order to maintain the data’s integrity. Initial code for establishing block structure would look something like this:

 

class Block {

constructor(index, previousHash, timestamp, data, hash) {

this.index = index;

this.previousHash = previousHash.toString();

this.timestamp = timestamp;

this.data = data;

this.hash = hash.toString();

}

}

 

Block hash

Block hash is required to keep the integrity of the data on the chain. Many blockchains have their own unique mining algorithms to give their chain particular advantages. The SHA-256 algorithm is the most common mining algorithm throughout cryptocurrency. The code for this algorithm would look similar to this:

 

var calculateHash = (index, previousHash, timestamp, data) => {

return CryptoJS.SHA256(index + previousHash + timestamp + data).toString();

};

 

SHA-256 stands for “secure hash algorithm.” Block processing time is usually around six to ten minutes. The most effective way to mine this algorithm is with ASIC hardware. Here are some of the coins that run on the SHA-256 algorithm

 

Bitcoin (BTC)

Bitcoin Cash (BCH)

Peercoin (PPC)

Namecoin (NMC)

Unobtanium (UNO)

Betacoin (BET)

Bytecoin (BTE)

Joulecoin (XJO)

Devcoin (DVC)

Ixcoin (IXC)

Terracoin (TRC)

Battlecoin (BCX)

 

Generating a block

After establishing a mining algorithm its now time to generate blocks. In order to generate the next block the hash of the previous block must be included. Also, the generation of a new block includes other factors such as an index, data, or timestamp. This information is usually provided by the end client.

 

var generateNextBlock = (blockData) => {

var previousBlock = getLatestBlock();

var nextIndex = previousBlock.index + 1;

var nextTimestamp = new Date().getTime() / 1000;

var nextHash = calculateHash(nextIndex, previousBlock.hash, nextTimestamp, blockData);

return new Block(nextIndex, previousBlock.hash, nextTimestamp, blockData, nextHash);

};

 

Storing the blocks

Once a block is generated it must be stored on the blockchain. Here, a Javascript array is used to store the blocks. “My genesis block” is the first block created on the chain.

 

var getGenesisBlock = () => {

return new Block(0, “0”, 1465154705, “my genesis block!!”, “816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7”);

};

 

var blockchain = ;

 

Validating the integrity of blocks

It is essential that a block or a chain of blocks are valid. Blocks are received through nodes and they must be valid in order to add them to the chain. Here is what the source code of block validation would look like:

 

var isValidNewBlock = (newBlock, previousBlock) => {

if (previousBlock.index + 1 !== newBlock.index) {

console.log(‘invalid index’);

return false;

} else if (previousBlock.hash !== newBlock.previousHash) {

console.log(‘invalid previoushash’);

return false;

} else if (calculateHashForBlock(newBlock) !== newBlock.hash) {

console.log(‘invalid hash: ‘ + calculateHashForBlock(newBlock) + ‘ ‘ + newBlock.hash);

return false;

}

return true;

};

 

Nodes and the validation of blocks

Nodes are required to provide an avenue for transactions. By using a random selection of nodes on the network, the blockchain can eliminate double spending. (Sending the same bitcoin to two different addresses). Vitalik Buterin of Ethereum said the double spending problem was one of ‘the most difficult computer science problems to solve.’

 

Chain Conflicts

When blocks are being created there cannot be two chains with the same block numbers. For example, if a block is labeled 21 on one chain and 21 on another chain, the longer chain is ruled valid. Photo credit here

Source code for determining the longest chain:

 

var replaceChain = (newBlocks) => {

if (isValidChain(newBlocks) && newBlocks.length > blockchain.length) {

console.log(‘Received blockchain is valid. Replacing current blockchain with received blockchain’);

blockchain = newBlocks;

broadcast(responseLatestMsg());

} else {

console.log(‘Received blockchain invalid’);

}

};

 

 

Communicating with other nodes

As previously mentioned, nodes provide an avenue for transactions. Nodes are connected through the bitcoin network. In order for the network to be successful it must execute through a similar process:

 

—When a node generates a new block, it is broadcasted onto the network

 

—When a node connects to a new peer it querys for the latest block

 

—When a node encounters a block that has an index larger than the current known block, it either adds the block to its current chain or querys for the full blockchain.

 

In order for a node to be successful it must be able to be controlled. Controlling a node can be done by setting up an HTTP server.

 

A server gives the user the ability to list all blocks, create a new block with content given by the user, and add peers. The source code for this would look like this:

 

const initHttpServer = ( myHttpPort: number ) => {

const app = express();

app.use(bodyParser.json());

 

app.get(‘/blocks’, (req, res) => {

res.send(getBlockchain());

});

app.post(‘/mineBlock’, (req, res) => {

const newBlock: Block = generateNextBlock(req.body.data);

res.send(newBlock);

});

app.get(‘/peers’, (req, res) => {

res.send(getSockets().map(( s: any ) => s._socket.remoteAddress + ‘:’ + s._socket.remotePort));

});

app.post(‘/addPeer’, (req, res) => {

connectToPeers(req.body.peer);

res.send();

});

 

app.listen(myHttpPort, () => {

console.log(‘Listening http on port: ‘ + myHttpPort);

});

};

 

Overall, this article provides a brief outline of the way a blockchain functions. There are many aspects which are not included in this article. For example, various mining algorithms, block structure (index, data, timestamp, hash, and previous hash). If you are curious about additional blockchain information here are some in-depth sources:

 

https://lhartikk.github.io/jekyll/update/2017/07/14/chapter1.html

https://medium.com/@lhartikk/a-blockchain-in-200-lines-of-code-963cc1cc0e54

https://www.coindesk.com/bitcoin-nodes-need/

Disclaimer: I am not a financial adviser . This is not financial advice. Please do your research independently and make object decisions. This article is intended to educate readers on the code and architecture of blockchain technology. I am invested in various cryptocurrencies.