Blockchain – AppDividend https://appdividend.com Latest Code Tutorials Sat, 15 Dec 2018 01:01:52 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Blockchain – AppDividend https://appdividend.com 32 32 How To Create Blockchain In JavaScript https://appdividend.com/2018/12/15/how-to-create-blockchain-in-javascript/ https://appdividend.com/2018/12/15/how-to-create-blockchain-in-javascript/#comments Sat, 15 Dec 2018 00:58:09 +0000 http://localhost/wordpress/?p=2554 Javascript Blockchain Tutorial With Example From Scratch

In this tutorial, we will see How To Create Blockchain In JavaScript. Blockchain keeps the record of all data exchanges — this record is referred to as the “ledger” in the cryptocurrency world, and each data exchange is the “transaction.“ Every verified transaction is added to the ledger as a “block.” It utilizes the distributed system to verify each […]

The post How To Create Blockchain In JavaScript appeared first on AppDividend.

]]>
Javascript Blockchain Tutorial With Example From Scratch

In this tutorial, we will see How To Create Blockchain In JavaScript. Blockchain keeps the record of all data exchanges — this record is referred to as the “ledger” in the cryptocurrency world, and each data exchange is the “transaction.“ Every verified transaction is added to the ledger as a “block.” It utilizes the distributed system to verify each transaction — the peer-to-peer network of nodes. Once signed and verified, a new transaction is added to the blockchain and cannot be altered.

The blockchain is a structure of data that represents the financial ledger entry, or a record of a transaction. Each transaction is digitally signed to ensure its authenticity and that no one tampers with it, so a ledger itself and the existing transactions within it are assumed to be of high integrity.

In this tutorial, we will create the simple blockchain in javascript in which we use Javascript as a language and Node.js as a backend to run the small project.

How To Create Blockchain In JavaScript

Now if we need to create a simple Blockchain in Node.js, then we need to have one Genesis Block

You can refer to Genesis Block as the first block of Blockchain because Blockchain is an array of blocks and Genesis is the first block of the Blockchain.

Genesis Block

The genesis block is the first block of the blockchain. The genesis block is generally hardcoded in the applications that utilize its blockchain. The Genesis Block is also known as Block Zero or Block 0. It is an ancestor that every Blockchain network’s block that can be traced to its origin back. Remember how every block in the Blockchain is linked back to the previous block using the hash in the block header? You keep going back, and you realize every block is hence connected to the genesis block.

Our Genesis Block contains the following fields or properties.

  1. timestamp
  2. lastHash
  3. hash
  4. data

So, if we combine all these properties into one object, then it will become a Genesis Block. So based on this block, we will mine the second block. Then from the second block, we will extract the third block and so on. That is why we need a Genesis Block to start a Blockchain.

Now, let us start a project by creating a project folder and then start building awesome blockchain using Javascript.

Step 1: Create a project and create a Genesis Data

The first step is to create a project. Type the following command.

mkdir cryptochain

Go inside that folder.

cd cryptochain

Now, generate the package.json file in the case in future, we need to install any node modules.

npm init -y

Remember, I am using Node v11.3.0. 

Next step is to create a new file inside the root called genesis.js and add the following code.

// genesis.js

const GENESIS_DATA = {
    timestamp: Date.now(),
    lastHash: '64b7edc786326651e031a4d12d9838d279571946d8c9a5d448c70db94b0e143f',
    hash: 'c671c84681b9d682b9fd43b2a2ef01a343eab7cfa410df9835f8165007d38467',
    data: 'krunal'
};

module.exports = { GENESIS_DATA };

Here, we have taken an object with its initial values.

As I have defined earlier, our block contains the four properties. This is a genesis data, so we need to hardcode this values.

The properties timestamp and data are you can understand. But I have used SHA256 algorithm to convert the simple text into hash text.

Actual text for lastHash is a krunal, and actual text for the hash is a krunalHash.

You can verify it by going to this URL: https://passwordsgenerator.net/sha256-hash-generator/

Here, you can enter my name as a text, and it will give the SHA256 hash of that text. Now, you need to convert that text to lowercase by using Javascript’s toLowercase(). That is it. You will find the exact hash like me. Cool!! So now, you have Genesis Data is ready. The next thing is to create a Block from this data.

Step 2: Create a Block

Inside your project root, create a file called block.js and add the following code.

// block.js

const { GENESIS_DATA } = require('./genesis.js');

class Block {
    constructor({timestamp, lastHash, hash, data}) {
        this.timestamp = timestamp;
        this.lastHash = lastHash;
        this.hash = hash;
        this.data = data;
    }

    static genesis() {
        return new this(GENESIS_DATA);
    }
}

module.exports = Block;

So, here we have imported the GENESIS_DATA for our block.

Then we have defined the Block class and passed the parameters to the constructor when we create an object of the Block.

We have also defined the static method called genesis() which is responsible for returning the Genesis Block for our blockchain.

Remember, we have previously defined the GENESIS_DATA not block. After creating an object of this class, it will become a Genesis Block.

Step 3: Create a hash based on a previous block.

We need to define a function that can create a hash based on the previous block’s hash.

So, first let us create a new file inside the root called crypto-hash.js and add the following code inside it.

// crypto-hash.js

const crypto = require('crypto');

const cryptoHash =(...inputs) => {
    const hash = crypto.createHash('sha256');
    hash.update(inputs.sort().join(' '));
    return hash.digest('hex');
}

module.exports = cryptoHash;

Now, to create a Hash, we need the three properties.

  1. timestamp
  2. lastHash
  3. data

So, we have first required the crypto module provided by the Node.js.

Then we have defined the function called cryptoHash() which will accept the inputs. Here we have used spread operator which is the syntax of ES6.

Inside that function, we have called the createHash() method and pass the sha256 as a parameter. That means we need to create a hash based on the sha256 algorithm.

Then we have sorted and join that three parameters and return its hex values.

So, finally, we can get the current block’s hash based on the previous block’s three properties.

Step 4: Mine a new Block based on a previous Block

So, we got the Genesis Block and the hash of that block. Now, we need to write the function that can generate a new Block based on the previous block. Right now, in our case, it is a Genesis Block.

Now, import the crypto-hash module inside the block.js file and create a new function called mineBlock() and pass the two parameters.

  1. lastBlock
  2. data

So, our final block.js file looks like this.

// block.js

const { GENESIS_DATA } = require('./genesis.js');
const cryptoHash = require('./crypto-hash');

class Block {
    constructor({timestamp, lastHash, hash, data}) {
        this.timestamp = timestamp;
        this.lastHash = lastHash;
        this.hash = hash;
        this.data = data;
    }

    static genesis() {
        return new this(GENESIS_DATA);
    }

    static mineBlock({lastBlock, data}) {
        const timestamp = Date.now();
        const lastHash = lastBlock.hash;
        return new this({
            timestamp,
            lastHash,
            data,
            hash: cryptoHash(timestamp, lastHash, data)
        });
    }
}
module.exports = Block;

So, here we have defined the method called mineBlock and pass the two parameters. The mineBlock() will return a complete new Block based on the previous block.

Now, it is the time to create a Blockchain from these blocks.

Step 5: Create a Blockchain

We have completed the step of creating a Genesis Block and mining a new Block. Now it is the time to develop a blockchain. That is why create a new file inside the root called blockchain.js and add the following code inside it.

// blockchain.js

const Block = require('./block');

class Blockchain {

    constructor() {
        this.chain = [Block.genesis()];
    }

    addBlock({ data }) {
        const newBlock = Block.mineBlock({
            lastBlock: this.chain[this.chain.length-1],
            data
        });

        this.chain.push(newBlock);
    }
}

module.exports = Blockchain;

So, first, we have imported the Block.js file and then create a class called Blockchain.

The Blockchain class is responsible for adding a new block inside the blockchain.

The blockchain is an array of the blocks starts with Genesis block.

So in the constructor, we have not defined an empty array. Instead, we have filled the chain array with the Genesis block.

Then we have defined one function called addBlock() which accepts the data.

Now, before adding a new block to the chain array, we need to mine it. That is why we have called the Block class’s mineBlock() method to extract a new block.

For mining a new block, we need a previous block and data. That is why we have used this code this.chain[this.chain.length-1] because it will return the last block in the blockchain and data is already we are passing to that function. So we get the new block based on the previous block and data.

Next step is to add that newly mined block inside our blockchain, and that is it.

The last step is to run this project and get the blockchain.

Step 6: Run the project and get the blockchain.

Now, the last step is to create a file inside the root of the project called server.js and add the following code.

// server.js

const Blockchain = require('./blockchain');
const Block = require('./block');

const blockchain = new Blockchain();

for(let i=0; i<5; i++) {
    const newData = 'krunal'+i;
    blockchain.addBlock({data: newData});
}

console.log(blockchain);

So, here we have imported both the block.js and blockchain.js file and created an object of the Blockchain.

Then we will loop through that blockchain and add the data to that blockchain and created the six blocks in the blockchain because one is Genesis and five based on previous blocks.

Go to the terminal and start the node server.

node server

You will see an output like this.

 

How To Create Blockchain In JavaScript

Finally, How To Create Blockchain In JavaScript Tutorial With Example is over. Now you have a clear understanding of Blockchain technology and how we can start coding in it. Above example is an elementary example of implementing a blockchain. Real-world examples are very complicated but this is the first step to enter the blockchain world and become a blockchain developer.

Github Code

The post How To Create Blockchain In JavaScript appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/15/how-to-create-blockchain-in-javascript/feed/ 1
How To Create Your First Smart Contract In Solidity https://appdividend.com/2018/04/09/how-to-create-your-first-smart-contract-in-solidity/ https://appdividend.com/2018/04/09/how-to-create-your-first-smart-contract-in-solidity/#comments Mon, 09 Apr 2018 14:38:42 +0000 http://localhost/wordpress/?p=380

How To Create Your First Smart Contract In Solidity? In this tutorial, We will learn how to write the Smart Contract in Solidity Programming Langauge and deploy it to the local ethereum blockchain. If you are new to Blockchain world, then please check out my previous tutorial Ethereum Blockchain Tutorial From Scratch How Blockchain Works? Blockchain […]

The post How To Create Your First Smart Contract In Solidity appeared first on AppDividend.

]]>

How To Create Your First Smart Contract In Solidity? In this tutorial, We will learn how to write the Smart Contract in Solidity Programming Langauge and deploy it to the local ethereum blockchain. If you are new to Blockchain world, then please check out my previous tutorial Ethereum Blockchain Tutorial From Scratch

How Blockchain Works?

Blockchain apps work entirely different from web apps. In the web application, data is stored on the central database server. Clients communicate with a web application, and web application writes and reads to the database then responds according to it. In Blockchain technology, all the clients are nodes, and there is no such thing as a central database. Data is completely immutable, and after created, we can not change it back. So Blockchain provides high-end security. So our application is fully decentralized on the Blockchain. Data is ultimately distributed across the multiple nodes.

The blockchain is the network of peer to peer nodes. They communicate with each other. Once you are connected to the Blockchain, now you are part of the blockchain. You are one of the nodes of the Blockchain.

You can sum it as Blockchain is the database and network. Ethereum Blockchain allows us to write the code that we can deploy it to the blockchain and node of the network can execute this code.

Smart Contract

Ethereum Blockchain allows us to write the code that gets executed on Ethereum Virtual Machine with Smart Contracts. That means all of the business logic of our application resides on the smart contract. It will read and write the data, transferring value and execute any business logic that we program on the blockchain.

Solidity

Solidity is the language, in which we can write our smart contracts. These smart contracts then deploy on the blockchain. All the reading and writing data logic is defined in this Solidity language. It is like a microservices that live on the blockchain.

How To Create Your First Smart Contract In Solidity

We will start our project by installing the dependencies to build this small decentralized application.

If you have not installed Node.js on your machine, then you can install it using the following command.

brew install node

It also comes with NPM, which is node package manager.

Next thing, we need to install is Ganache. It quickly fires up a personal Ethereum blockchain which you can use to run tests, execute commands, and inspect state while controlling how the chain operates. Go to this Link. You can install it according to your OS. After installing, you can see something like this.

Ganache Blockchain Tutorial

Install Truffle Framework

Next, install the Truffle FrameworkTruffle is the most popular development framework for Ethereum with a mission to make your life a whole lot easier. Install using the following command.

sudo npm install -g truffle

Truffle Framework Features

  • Built-in smart contract compilation, linking, deployment and binary management.
  • Automated contract testing for rapid development.
  • Scriptable deployment & migrations framework.
  • Network management for deploying to both public & private networks.
  • External script runner that executes scripts within a truffle environment.
  • Access to hundreds of external packages.
  • Built for speed.

Install Metamask Chrome Extension.

You can install it using this link.

Install Solidity Extension on Visual Studio Code.

If you have not installed Visual Studio Code yet, then please install it, it is by far best editor in my opinion. You can check out my article on How To Install Visual Studio Code On Mac.

Solidity Tutorial with Example

Do not turn off the Ganache. Keep is open. It is Local blockchain, and in that, there are  10 Users are already there. You can see their address. 

Now, we need to create the project to write the smart contracts in Solidity language. We have already installed Truffle Framework, so we can use that to generate the boilerplate for our project. So go to your general project directory and type the following command to create the project folder. Go into that folder.

mkdir blocksol
cd blocksol

Okay, now generate the truffle boilerplate using the following code.

truffle unbox pet-shop

Open the project in your editor using the following command. I have VScode so,

code .

You can see that our primary folder structure looks like below.

 

Truffle Framework Tutorial

Create the Smart Contracts.

In the folder structure, you can see that there is one folder called contracts. We will create all our contracts in that folder. Let us create one contract called Football.sol. Here the file extension is .sol because we are using Solidity language to code the contract. Write the following code inside it.

pragma solidity ^0.4.2;

contract Football {

    string public team;

    function Football () public {
        team = "Real Madrid";
    }
}

In the first line, we have defined the version of solidity, which is above 0.4.2. Then we have established the contract Football. Also, I have taken the variable called a team, and it is public. Now, we can use that public variable as a method to return its value. So the variable, which defined as a public in the contract, we can call as a function as well to get the value of that variable.

Create the migration of Football Contract.

Create one file inside migrations folder called 2_football_migration.js file.

// 2_football_migration

var Football = artifacts.require("./Football.sol");

module.exports = function(deployer) {
  deployer.deploy(Football);
};

Okay, now deploy the contract to the blockchain network by using the following command.

truffle network

Do not worry about compilation warnings; it is okay.

Interact With The Blockchain.

You can interact with our application using the following command.

truffle console

Now, type the following in your terminal.

Football.deployed().then(function(instance) {app = instance})

Smart Contracts returns a Promise, which is mainly a JavaScript concept, which is an Asynchronous behavior. Like if we need to wait for some processes to finish it, it can send us the promise, which either resolves or reject. Now, after complete the event, it will give us a result, and that is app. So we can further query like this.

app.address

Now, In return, you can see the address in the string.

We can also get the team name by the following function.

app.team()

It will return a Real Madrid. But wait, we have not defined any function called team still it will return a value.

Because public variables are itself a getter function. So we can call it as a function, and in return, we can get its value.

Smart Contracts With Pragma Solidity Tutorial

So, finally, we have deployed our First Smart Contract In Solidity. 

That is it for the today’s How To Create Your First Smart Contract In Solidity tutorial. We will build fully decentralized Application using Ethereum Blockchain the future.

The post How To Create Your First Smart Contract In Solidity appeared first on AppDividend.

]]>
https://appdividend.com/2018/04/09/how-to-create-your-first-smart-contract-in-solidity/feed/ 2
Ethereum Blockchain Tutorial From Scratch https://appdividend.com/2018/01/12/ethereum-blockchain-programming-tutorial-scratch/ https://appdividend.com/2018/01/12/ethereum-blockchain-programming-tutorial-scratch/#comments Fri, 12 Jan 2018 22:02:46 +0000 http://localhost/appdividend/?p=1504 Ethereum Blockchain Tutorial From Scratch

Ethereum Blockchain Tutorial From Scratch is today’s leading topic. Blockchain is right now google’s one of the most search keywords, and many of you have already heard of Bitcoin or Ethereum. All these cryptocurrencies are based on this technology called Blockchain. What is Blockchain Blockchain is one of the best technological inventions of the 21st century. The brain behind the Blockchain is a person or group […]

The post Ethereum Blockchain Tutorial From Scratch appeared first on AppDividend.

]]>
Ethereum Blockchain Tutorial From Scratch

Ethereum Blockchain Tutorial From Scratch is today’s leading topic. Blockchain is right now google’s one of the most search keywords, and many of you have already heard of Bitcoin or Ethereum. All these cryptocurrencies are based on this technology called Blockchain.

What is Blockchain

Blockchain is one of the best technological inventions of the 21st century. The brain behind the Blockchain is a person or group of people known by the pseudonym,  Satoshi NakamotoBlockchain allows digital information to be distributed, but not copied, and decentralized. Blockchain technology has created the new type of internet.

Ethereum Blockchain Tutorial

We will use Ethereum Blockchain to start our programming and understand the different libraries around it. In this tutorial, we just see what the language we will use to begin the development in the Ethereum Blockchain and how we can create a server and fetch the data into the webpage is. We will dive deeper into the following tutorials. It is a just basic overview of the Ethereum.

Step 1: Install the packages.

First, we will create a project folder, and in that, we will create a package.json file by typing the following command. You need to have Node.js installed on your machine.

npm init

It will create a package.json file. Now install the following package.

npm install --save-dev nodemon

When we save the Node.js server file then it will restart the server automatically, so we do not need to restart the server manually.

Now, we will install the express node.js web framework by typing the following command.

npm install --save express

Okay, also create one folder called public in the root directory and in that folder, make one HTML file called index.html.

Our package.json file looks like this.

{
  "name": "ethereum-blockchain",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon server"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^1.14.11"
  },
  "dependencies": {
    "express": "^4.16.2"
  }
}

Now, create a server.js file inside the root folder and write the node.js server code.

// server.js

const express = require('express');
let app = express();
const PORT = 3000;

app.get('/', function(req, res){
   res.sendFile(__dirname + '/public/index.html');
});

app.listen(PORT, function(){
   console.log('Server is started on port:',PORT);
});

Step 2: Modify the index.html file.

We need to make an ajax request to the nodej.js server to display the data on the webpage. For the sending the ajax request, we can use jQuery, axios or fetch library. But right now, we will use plain javascript to make and send the AJAX request.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Ethereum Blockchain Tutorial</title>
</head>
<body>
   <p id="blockchain">Ethereum tutorial</p>
   <button onclick="EthereumServer()">Connect to the Ethereum</button>
</body>
<script>
   function EthereumServer()
   {
      alert('blockchain');
   }
</script>
</html>

Here, I have just tested the onclick function, and now in that function, we need to send an ajax request to a node.js server.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Ethereum Blockchain Tutorial</title>
</head>
<body>
   <p id="blockchain">Ethereum tutorial</p>
   <button onclick="EthereumServer()">Connect to the Ethereum</button>
</body>
<script>
   function EthereumServer()
   {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
         document.getElementById("blockchain").innerHTML = this.responseText;
         }
      };
      xhttp.open("GET", "/blockchain", true);
      xhttp.send();
   }
</script>
</html>

In the server.js file.

// server.js

const express = require('express');
let app = express();
const PORT = 3000;

app.get('/', function(req, res){
   res.sendFile(__dirname + '/public/index.html');
});

app.get('/blockchain', function(req,res){
   res.json('ethereum request got it');
})

app.listen(PORT, function(){
   console.log('Server is started on port:',PORT);
});

Step 3: Install blockchain stack.

We need two things.

  1. testrpc network
  2. web3

We need to install testrpc globally in our system. It will work as a virtual blockchain network in our memory. We can play around with this, and when we get ready for the production, then we will use actual ethereum blockchain to develop decentralized apps.(DApps)

We need to install testrpc globally, so type the following command in your terminal.

npm install -g ethereumjs-testrpc

After installing the package, now you can see how it looks like by the typing the following command.

testrpc

 

ethereum blockchain

You can see here; it has its network and some test accounts to work with. We will fetch the accounts and display on the frontend. So first we need to communicate the testrpc network with our node.js application.

Step 4: Install web3.js

We need to install version 1.0.0 of the web3. So type the following command in your terminal.

npm install web3

Now, include this in our server.js file.

// server.js

const express = require('express');
let app = express();
const PORT = 3000;

const Web3 = require('web3');
let web3 = new Web3();


app.get('/', function(req, res){
   res.sendFile(__dirname + '/public/index.html');
});

app.get('/blockchain', function(req,res){
   res.json('ethereum request got it');
});

app.listen(PORT, function(){
   console.log('Server is started on port:',PORT);
});

We can call providers methods on the class web3 like the following.

If we want to know, what type of providers are used to communicate with the testrpc then simply console.log the providers.

console.log(Web3.providers);

It will give us three types of providers.

  1. IPC
  2. HTTP
  3. WebSocket

We will use HTTP Provider since testrpc is using that and will be running at port: 8545

So we can fetch the accounts from the testrpc to node.js application.

//server.js

const Web3 = require('web3');
let web3 = new Web3();

web3.setProvider(new Web3.providers.HttpProvider('http://localhost:8545'));

web3.eth.getAccounts(function(err, res){
   console.log(err, res);
});

It will give an array of accounts. The first argument is an error. In this case, it is a null and second argument is an array of accounts.

Final Touches

Our final server.js file looks like this. Remeber, we need to have running two servers at a time.

  1. testrpc
  2. node.js

If one of them is stopped, then our whole system will crash. So blockchain network will never stop, and it will run forever in real time. So in that network blocks will be added in the future. More the blocks are added, and more the network will be secure.

// server.js

const express = require('express');
let app = express();
const PORT = 3000;

const Web3 = require('web3');
let web3 = new Web3();

web3.setProvider(new Web3.providers.HttpProvider('http://localhost:8545'));

app.get('/', function(req, res){
   res.sendFile(__dirname + '/public/index.html');
});

app.get('/blockchain', function(req,res){
   web3.eth.getAccounts(function(err, accounts){
      if(err == null) res.send(JSON.stringify(accounts));
   });
});

app.listen(PORT, function(){
   console.log('Server is started on port:',PORT);
});

So, finally in the frontend, when you click the button, the array of accounts will be displayed. That accounts are in the network of ethereum, and we have successfully connected our node.js application to the ethereum network.

Github code of the Ethereum Blockchain Tutorial.

Fork Me On Github

The post Ethereum Blockchain Tutorial From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/01/12/ethereum-blockchain-programming-tutorial-scratch/feed/ 4