Are You an Ambitious Entrepreneur Aspiring to Launch a World-Class Web3 Project? GRAB your WEB3 EXPERT CONSULTATION!
Book a Session!

Blockchain Technology Examples And Types of Blockchain Codes

different types of blockchain codes

The cryptocurrency community has valued blockchain technology very highly for almost ten years. It emerged in 2008 designed by Satoshi Nakamoto. Initially, it served as a platform for Bitcoin currency transactions. Over time, it has matured and developed into a multi-purpose public ledger capable of solving a wide range of tasks. In order to deploy a blockchain, you are welcome to go through our tutorial and choose the best-matching blockchain code example.

With blockchain implementation, one can distribute and share digital information in a decentralized manner. In addition, it is possible to decrease data forgery, copying, and tampering. Secure transparency is a valuable blockchain peculiarity that contributes positively to the workflow of various industries and enhances their productivity and efficiency.

Bitcoin appeared as the first cryptocurrency and gained tremendous popularity. As of today, the total Bitcoin market cap is approximately $111 billion. Besides Bitcoin, there have appeared numerous other cryptocurrencies currently used for financial transactions within blockchain platforms:

Types Of Blockchains

Currently, there are many blockchains producing the above-mentioned cryptocurrencies. Moreover, they all hold certain digital value. Current types of blockchain are public, private, and federated. Let’s take a closer look at them and define their distinctive features.

Public Blockchain Technology Example

Public blockchains are likely to substitute a majority of functions provided by common financial establishments. This is possible due to enhanced software that changes traditional financial system approaches.

Most of blockchains use the proof of work (PoW) consensus algorithms that are publicly accessible and defined as non permissioned. In particular, this means that all users:

  • can participate in this type of blockchain without any restrictions
  • are able to download the source code and run a node on their personal devices and validate the process of transactions
  • can transact payments via the network and participate in the blockchain
  • can view transaction history while still remaining anonymous, due to transparency

Bitcoin is one of the brightest public examples of blockchain, holding a position among Ethereum, and Litecoin.

These blockchain technologies provide a chance of fundamentally changing common business models. They also reduce costs by eliminating server maintenance fees and providing almost free possibilities of decentralized applications deployment.

Private Blockchain Technology Example

Private blockchains solve issues of effectiveness, safety, security, and deception. While private blockchains don’t have the great potential of causing revolutionary changes to traditional financial systems as public blockchains, they have a range of other advantages.

Private blockchains provide write permissions to a centralized entity. Read permissions can be accessible or restricted according to a desired degree. Private example of blockchain applications involves internal company’s data governance and audit. Hence, in this case, the necessity of public access isn’t necessary. In a different situation, public access is desirable.

Businesses choose private blockchains for internal use rather than sharing information. Hence, a limited group of people can track and view the company’s transactions.

One of the drawbacks of such a system is that it is similar to a centralized one, and therefore is more vulnerable. However, private blockchains win in scalability aspects and better compliance with regulatory policies.

MONAX and Multichain serve as examples of private blockchain technology.

Private blockchains:

  • reduce costs
  • reduce data excess
  • simplify documentation process
  • lower the use of manually-maintained mechanisms

Federated Blockchain Technology Example

Federated blockchain, also referred to as Consortium, functions are led by a group of users. These blockchains don’t allow any user to interfere with the information concerning transactions and their verification. This example of blockchain is fast and has extended privacy settings. This is evidenced by the fact that many companies in the banking sector and similar institutions use it. A set of selected-in-advance nodes manage the process of reaching consensus. For instance, to reach consensus, no less than ten out of fifteen participants have to sign and approve a block. Only then is it valid. In addition, federated blockchain can include options to be read by public or restricted to the view.

R3, EWF and B3i are examples of consortium blockchains.

The impact of these blockchains is the same as private blockchain. With federated blockchains one can:

  • reduce costs and data redundancy
  • eliminate the use of mechanisms that require manual management

See the following comparison table:

types of blockchains
As of April 2018, public and private blockchains were used the most. Together they make up 44% of worldwide organizations that implement blockchain. Next follow consortium blockchains (36%) and finally, all other types of blockchains (3%).

Issues Concerning Blockchain Development

In order to create a strong and powerful blockchain, it is crucial to be aware of possible issues in advance, in order to avoid them. These issues concern security, resource management, the efficiency of performance/productivity, and isolation.

Security Issue

Blockchains provide an increased level of safety and privacy. Therefore, they must be highly secure. The written code should be hack-resistant and eliminate possible bugs and vulnerabilities. Since anyone can usually view the source code, it is easy to find and solve any possible problems.

On the other hand, hackers are programmers as well. This means that blockchain has a high likelihood of suffering attacks. This requires creating smart and complex code structure which is impossible to tamper with. That is why the development and deployment of a new blockchain takes time and extra effort. It has to be precisely and wisely created to further serve all users. Because of the immutable and irreversible nature of the blockchain technology, this task is vital.

Resource Management Issue

While deploying a new blockchain, keep in mind that the task isn’t done in one step. After the blockchain implementation, there will be further steps to take, and problems to solve. Thus, it is necessary to keep up with modern network requirements and demands. All kinds of requests will have to be managed and taken care of whether they are remote or local. Constant upgrades will necessary to meet all demands of the network. Examples include suitability with the latest applications, currency acceptance, etc.

High Performance Issue

Any blockchain must provide the highest efficiency, and be capable of handling a range of numerous tasks. In order to guarantee optimal performance, developers must choose the most flexible and suitable coding language to deal with all requirements, such as distributed operations or resource management. This may involve the solving tasks in a parallel manner. Some blockchains don’t provide such an option. Hence, the programmer should decide at the very beginning which exact solutions to solve and the required measures to undertake.

This issue might seem complex, as it directly deals with multiple transactions that cannot be performed in parallel to eliminate double spending, for instance. Therefore, some languages suit best in parallel operations when others – in non-parallel ones.

Isolation Issue

Isolation solves problems with deterministic behavior. To understand what deterministic means, consider the following equation:

While deploying a blockchain, all transactions are to be deterministic, meaning one transaction cannot behave in different ways. Moreover, the same applies to smart-contract functionality. One smart contract has a unique working scheme which cannot just suddenly change.

Contact Applicature if you have any questions considering smart contract development.

In order to solve such problems, you have to isolate transactions or smart contracts (SCs) from the elements that are not deterministic.

Blockchain Code Tutorial

In order to code for any blockchain, developers have to evaluate the above-mentioned challenges and choose the best-matching coding language. As of today, there exist numerous ways of coding blockchain. Below, we will show the most common coding languages with a blockchain code example concerning each of them.

Such languages as C/C++, Go, Python, and Javascript are the most commonly used.

C++ is one of the first coding languages designed by Bjarne Stroustrup. It is more flexible and efficient than C language and additionally is object-oriented. C++ is designed like OOP (Object Oriented Programming) language. As a result, its main idea is to allow a programmer to write code according to his preferences, following a compiler complication mechanism.

Javascript is one of the core languages used in web programming, commonly for interactive webpage creation. With the appearance of Node.JS, which is similar to a programming platform, one can use Google’s V8 JavaScript Engine that allows JavaScript to interact with I/O via its API, written in C++.

Python, created by Dutch programmer Guido van Rossum in 1991, aims to make the code simpler and as minimal as possible. Consequently, it provides simplicity by eliminating the use of curly brackets or keywords substituted by white spaces. Python is considered to be a scripting language that has a lot of libraries. Hence, this allows a programmer to work with system processes without memory management.

Solidity language has recently gained much popularity. It is perfect for decentralized application deployment or for those running initial coin offerings. Solidity is deliberately simplified, freely-typed language with an ECMAScript or C++ similar syntax. Follow the link to find out more about ICO setup and launch using Solidity.

Azure, is a platform better suited to designing applications representing multi-party workflows determined by the code of configuration and SCs. Azure is simple in development, speeds up processes and provides enhanced security and scalability.

C++ Blockchain Example Code

C++ simple example is the “Hello World” program:

#include

using namespace std;

int main(){

cout << "Hello World!";

return 0;

}

Pretty simple, right? It is worth mentioning that the Bitcoin blockchain is programmed on it! The reasons why C++ is so valuable in the blockchain community are due to the following features:

1. Memory Control: in order to solve the above-mentioned challenges of resource management and security issues, C++ helps fully control central point unit and memory. All network nodes can accept/reject exact blocks to avoid the possibility of chain forks.

2. Threading: concerns the issue of parallelized tasks performance. C++ suits well to handle both parallelized and non-parallelized tasks as its threading ability allows simultaneous instruction and transaction execution.

3. Move semantics: one of the most advantageous C++ features allowing to move content between the objects instead of copying semantics purposely.

When we are using the move semantics, the value of “b” need not be unchanged. That is the difference between copy semantics and move semantics.

The biggest advantage of move semantics is that you can get copies of certain data only when you need them, which greatly decreases redundancy in the code and gives a huge performance boost.

4. Compile Time Polymorphism: is an object-oriented programming property. C++ implements this property with:

The compile time polymorphism separates responsibilities in different functions by increasing the system performance.

5. Code Isolation: namespace features can be entered across different programs in order to avoid name collisions. In addition, due to C++ classes, it functions as an API boundary to provide clear separation.

6. Maturity: C++ is considered to be a mature and regularly upgraded language. Additionally, its features solve numerous real issues from performance profiling to problem detection.

Javascript Blockchain Example Code

To create a blockchain using Javascript, let’s go through the basics.

Each block in a chain of blocks has a hash of a previous block. In the event of an attack or malicious behavior, the hash is significantly changed, which affects the whole blockchain, freezing it and therefore eliminating the chance of changing the block.

To create a block, consider the details it contains:

1. Create a Block. Blockchain code example:

const SHA256 = require("crypto-js/sha256");

class Block

{

constructor(index, timestamp, data, previousHash = '')

{

this.index = index;

this.previousHash = previousHash;

this.timestamp = timestamp;

this.data = data;

this.hash = this.calculateHash();

}

calculateHash()

{

return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();

}

}

Code Analysis:

  • Include crypto-js library.
  • Declare the constructor that will be called during instantiation of the class. The goal of a constructor is to initialize class instance.
  • Hash all the content to receive the block hash.
  • Use the JSON.stringify function to format block data.

2. Create a blockchain:

Create a genesis block, the first block that invokes immediately on the blockchain.

createGenesisBlock()

{

return new Block(0, “01/01/2018”, “Genesis block”, “0”);

}

Add other blocks. In order to connect blocks, use this function:

getLatestBlock()

{

return this.chain[this.chain.length - 1];

}
addBlock(newBlock) {

newBlock.previousHash = this.getLatestBlock().hash;

newBlock.hash = newBlock.calculateHash();

this.chain.push(newBlock);

}

Make sure that values of the previous and current blocks should match, in order for n the new block to be considered valid.

Validate the chain, checking everything for stability and eliminating vulnerabilities.

for (let i = 1; i < this.chain.length; i++)

{

const currentBlock = this.chain[i];

const previousBlock = this.chain[i - 1];

if (currentBlock.hash !== currentBlock.calculateHash()) {

return false;

}

if (currentBlock.previousHash !== previousBlock.hash)

{

return false;

}

}

return true;

}

Finally, you are able to use your blockchain!

Blockchain Python Example

As we have mentioned before, Python is a simplified coding language which is efficient to use. As an example, here is the “Hello World” Python program:

print(‘Hello, world!’)

That’s actually it. In contrast to C++ program, you can see how simple Python is.

Now let’s move on to the development stages:

1. Create a block by adding a hashlib:

class Block:
def __init__(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.hash_block()

def hash_block(self):
sha = hasher.sha256()
sha.update(str(self.index) +
str(self.timestamp) +
str(self.data) +
str(self.previous_hash))
return sha.hexdigest()

2. Create a genesis block (the first one on blockchain) by entering datetime as date:

def create_genesis_block():

return Block(0, date.datetime.now(), “Genesis Block”, “0”)

3. Create and connect the other blocks via the following function:

def next_block(last_block):
this_index = last_block.index + 1
this_timestamp = date.datetime.now()
this_data = "Hey! I'm block " + str(this_index)
this_hash = last_block.hash
return Block(this_index, this_timestamp, this_data, this_hash)

Block data:

4. The next step is blockchain creation:

blockchain = [create_genesis_block()]
previous_block = blockchain[0]

num_of_blocks_to_add = 15

for i in range(0, num_of_blocks_to_add):
block_to_add = next_block(previous_block)
blockchain.append(block_to_add)
previous_block = block_to_add
# Tell everyone about it!
print "Block #{} has been added to the blockchain!".format(block_to_add.index)
print "Hash: {}n".format(block_to_add.hash)

Here, we’ve created a genesis block assigning it the “previous block” value. Then, we’ve decided on a number of blocks to add and then printed the number of the added blocks along with their hashes.

This is how the print out can look like:

python blockchain code example print out

It’s up to you to add any other complicated features!

Solidity Example Code

Solidity is widely used by programmers and developers to code within dApp deployment and for ICO launches. Here’s how the example code looks:

contract BasicIterator

{

address creator; // reserve one "address"-type spot

uint8[10] integers; // reserve a chunk of storage for 10 8-bit unsigned integers in an array

function BasicIterator()

{

creator = msg.sender;

uint8 x = 0;

//Section 1: Assigning values

while(x < integers.length) {

integers[x] = x;

x++;

} }

function getSum() constant returns (uint) {

uint8 sum = 0;

uint8 x = 0;

//Section 2: Adding the integers in an array.

while(x < integers.length) {
sum = sum + integers[x];

x++;
}

return sum;

}

// Section 3: Killing the contract

function kill()

{

if (msg.sender == creator)

{

suicide(creator);

}

}

}

Now let’s take a closer look at development stages:

1. First of all, assign the values: fill up the integers array with a “while loop”:

while(x < integers.length) {

integers[x] = x;

x++;

}

The x integer holds the value of 0. Furthermore, the while loop starts from 0 and represents the integer length capacity. If it goes up to 9, you’ll get the following value: 0,1,2,3,4,5,6,7,8,9.

2. Add the contents of an array using the while loop and a “sum” variable.

3. Finally, call “Kill the Contract” function to return remained funds to the contract creator.

These are the main events to create the blockchain in Solidity language. Learn more about creating smart contracts in Solidity language here.

Azure Decentralized App Example

Last, but not the least, is the Azure coding platform. It can serve as Azure blockchain example as well. It is mostly used for decentralized applications deployment.
First, create a configuration file. Its metadata determines enhanced workflows and dAPP models of interaction.

First of all, choose the editor you prefer, and create a “HelloBlockchain.json” file.

Then follow these steps:

1. Create application metadata: add its name and description. Include application roles and the blockchain participants according to functionality:

{
"ApplicationName": "HelloBlockchain",
"DisplayName": "Hello, Blockchain!",
"Description": "A simple application to send request and get response",
"ApplicationRoles": [
{
"Name": "Requestor",
"Description": "A person sending a request."
},
{
"Name": "Responder",
"Description": "A person responding to a request"
}
],

2. Define workflows of the contract stages and actions:

"Workflows": [
{
"Name": "HelloBlockchain",
"DisplayName": "Request Response",
"Description": "A simple workflow to send a request and receive a response.",
"Initiators": [ "Requestor" ],
"StartState": "Request",
"Properties": [
{
"Name": "State",
"DisplayName": "State",
"Description": "Holds the state of the contract.",
"Type": {
"Name": "state"
}
},
{
"Name": "Requestor",
"DisplayName": "Requestor",
"Description": "A person sending a request.",
"Type": {
"Name": "Requestor"
}
},
{
"Name": "Responder",
"DisplayName": "Responder",
"Description": "A person sending a response.",
"Type": {
"Name": "Responder"
}
},
{
"Name": "RequestMessage",
"DisplayName": "Request Message",
"Description": "A request message.",
"Type": {
"Name": "string"
}
},
{
"Name": "ResponseMessage",
"DisplayName": "Response Message",
"Description": "A response message.",
"Type": {
"Name": "string"
}
}
],
"Constructor": {
"Parameters": [
{
"Name": "message",
"Description": "...",
"DisplayName": "Request Message",
"Type": {
"Name": "string"
}
}
]
},

This workflow can include state properties:

"States": [
{
"Name": "Request",
"DisplayName": "Request",
"Description": "...",
"PercentComplete": 50,
"Value": 0,
"Style": "Success",
"Transitions": [
{
"AllowedRoles": ["Responder"],
"AllowedInstanceRoles": [],
"Description": "...",
"Function": "SendResponse",
"NextStates": [ "Respond" ],
"DisplayName": "Send Response"
}
]
},
{
"Name": "Respond",
"DisplayName": "Respond",
"Description": "...",
"PercentComplete": 90,
"Value": 1,
"Style": "Success",
"Transitions": [
{
"AllowedRoles": [],
"AllowedInstanceRoles": ["Requestor"],
"Description": "...",
"Function": "SendRequest",
"NextStates": [ "Request" ],
"DisplayName": "Send Request"
}
]
}
]
}
]
}

You can include functions to present the general contract flow:

"Functions": [
{
"Name": "SendRequest",
"DisplayName": "Request",
"Description": "...",
"Parameters": [
{
"Name": "requestMessage",
"Description": "...",
"DisplayName": "Request Message",
"Type": {
"Name": "string"
}
}
]
},
{
"Name": "SendResponse",
"DisplayName": "Response",
"Description": "...",
"Parameters": [
{
"Name": "responseMessage",
"Description": "...",
"DisplayName": "Response Message",
"Type": {
"Name": "string"
}
}
]
}
],

Save your file. Now you’re ready with basic blockchain!

Conclusion

We have outlined the blockchain codes of various programming languages. Inspired to build and create new blockchains? We hope so! Just choose the code that best suits your needs and requirements. If you are not a developer, but interested in the idea of blockchain technology, don’t hesitate to contact Applicature, and our programmers will build one for you.

Also, make sure to check out the product development framework for blockchain projects presented by Applicature CEO Ihor Pidruchny.

Insights from our Consulting Department

December 1, 2022
Applicature helps Kingaru with development, funding and token launch for Web3 immersive e-commerce
October 3, 2022
Dissecting Crypto Winter— Opportunities for Family Offices and Private Funds

Leave a Reply

Your email address will not be published. Required fields are marked *

+1-209-813-2474 |  25 Belle Avenue, San Rafael