Tutorial 1 : Eethereum : The complete End-To-End tutorial.

In this blog you will be learn about Setup Private Ethereum Blockchain and Write Smart Contract, deploy and Access from web. Already enough explanation available about Ethereum and Solidity. We can directly jump into the steps.

Language & Tools We are going to use :


Language : Go-Ethereum(Geth-1.9.14), Javascript, Html
Tools : RemixIDE, Truffle, Ganache
Operations : Development of Smart Contract, Compile, Test, Deployment & Access of Smart Contract from private Ehterum blockchain.


The entire process comprise below 5 steps

  • Step 1: Download, Install & Start private Ethereum blockchain using Geth CLIs.
  • Step 2: Download & Install, Truffle & Ganache
  • Step 3: Writing Smart Contract
  • Step 4: Compile, Test & Deployment using Truffle & Ganache
  • Step 5: Invoke smart contract from web browser using Java Sctipt.

Step 1 : Download, Install & Start private Ethereum blockchain using Geth CLIs.

1.1: Download & Install Geth as mentioned in go-ethereum wiki :

Using Homebrew:

https://github.com/ethereum/go-ethereum/wiki/Installation-Instructions-for-Mac

Or.

Using tar.gz:

https://geth.ethereum.org/downloads/

  1. Download Geth & Tools.tar.gz and unzip it.
  2. mention the path in .base_profile available under your name(vi ~/.base_profile)
  3. GOPATH = /Users/myusername/Desktop/geth-install/geth-alltools-darwin-amd64-1.9.14-6d74d1e5
    PATH="${PATH}:${GOPATH}"
  4. Reset Terminal
1.2: Initiate & Start a new private network with genesis.json
  1. Create a new folder "eth_private_network".
  2. Create a new file "genesis.json" inside "eth_private_network".
  3. Copy below sample code to genesis.json file. You can refer in Ethereum Wiki
    {
      "alloc": {},
      "config": {
        "chainId": 2022,
        "homesteadBlock": 0,
        "DAOForkBlock": 0,
        "DAOForkSupport": true,
        "eip150Block": 0,
        "eip155Block": 0,
        "eip158Block": 0
      },
      "difficulty": "0x400",
      "gasLimit": "0x989680",
      "nonce": "0x0000000000000042",
      "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
      "coinbase": "0x0000000000000000000000000000000000000000",
      "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
      "extraData": "",
      "timestamp": "0x00"
    }   
                      
  4. Initiate Geth a new private blockchain with below command in new terminal
     
    $ cd path_to_eth_private_network
    $ geth --datadir ./datadir init ./genesis.json
                      
  5. After initiate start new Private Blockchain the command
    $ geth --datadir ./datadir --networkid 2022 --rpc --rpcport 30303 --allow-insecure-unlock console 2>> ./tmp.log
                      
    Note : This will create tmp.log file using 'tail -f tmp.log' you can see the logs output and you will get geth console.
    You can read more about API in the Ethereum Wiki.
  6. Create 2 new accounts in geth console using personal api.
    > personal.newAccount('sample1');
    > personal.newAccount('sample2');  
                      
  7. Start Miners to mine the blocks
    > miner.start()
                      
  8. Every new block creation minor can get reward points to find the total ether count use below web3 api.
    > web3.fromWei(eth.getBalance(eth.coinbase))
                      
  9. You can find account address using following commands
    > eth.accounts OR > personal.listAccounts  
                      
  10. Unlock Accounts using password before sending the Ethers.
    > personal.unlockAccount('0xd857b288ec2053953754cdacf066ae84dbd614b6 ','sample1',0)
                      
  11. You can send mined ethers from one account to another accounts.
    > eth.sendTransaction({from:eth.accounts[0],to:eth.accounts[1],value:web3.toWei('1','ether')})
                      

Step 2. Download & Install, Truffle & Ganache.

2.1: Download & Install Truffle
  1. Truffle can be install using NPM (Node Package Manager). In new Terminal run.
    $ npm install -g truffle
                        
    you can find full details intrufflesuite
  2. Create a folder called "calculator"
    $ cd calculator
    $ truffle init
                        
    This will generate all required folders, Migration.sol & Script files.
2.2: Download & Install Ganache
  1. Ganache is GUI tool for Compile, Test & Deploy smart contract on Ethereum Blockchain. Download Ganache
  2. Install Ganache. Open Ganache GUI, Create a new workspace with name calculator.

Step 3. Writing Smart Contract

3.1 Using Remix IDE :
  1. In a browser open https://remix.ethereum.org/ this will open new IDE with some sample files.
  2. Open plugin Manger isntall SOLIDITY COMPILER & DEPLOY & RUN TRANSACTIONS plugins
  3. Create a new file called "calculator.sol". Copy below snipet of code to calculator.sol
    // SPDX-License-Identifier: GPL-3.0
    pragma solidity >=0.4.16 <0.7.0;
    
    contract Calculator {
        uint256 result;
    
        constructor() public {
            result = 10;
        }
    
        function getResult() public view returns (uint256) {
            return result;
        }
    
        function addToNumber(uint256 num1, uint256 num2) public returns (uint256) {
            result = num1 + num2;
            return result;
        }
    
        function substractFromNumber(uint256 num1, uint256 num2)
            public
            returns (uint256)
        {
            result = num1 - num2;
            return result;
        }
    }
                        
  4. Compile & Deploy using the plugins
  5. Invoke methods after deploy in Remix IDE and test it.
  6. To learn more about solidity : read Solidity Wiki
3.2 : Smart Contract Development using Truffle
  1. In Senction 2.1 You have already executed truffle init and it created all the required folders. Using VSCode Or any IDE you can open the folder.
  2. Under Contract folder -> Create a new file called "calculator.sol"
  3. Copy and paste the code we have written in Remix IDE(calculator.sol)
  4. Under Migration folder -> create a new file called "2_calcualtor_migration.js"
  5. copy the below code snipet into 2_calculator_migration.js file
    
    const Calculator = artifacts.require("Calculator");
    
    module.exports = function(deployer) {
    deployer.deploy(Calculator);
    };
                      

Step 4. Compile, Test & Deploy of Smart Contract using Truffle & Ganache.

4.1 : Compile, Test & Deploy using Truffle
  1. Once you copied calculator.sol file in a new terminal run below cmd. This will compile new calculator.sol file.
    > truffle compile
                        
  2. Update truffle-config.js file to deploy and run smart contracts. uncomment below lines and change the port and network_id
    development: {
      host: "127.0.0.1",     
      port: 30303 ,            
      network_id: "2022",       
    },
                        
  3. run truffle migrate command(unlock account before deploy new smart contract).
    > truffle migrate
                        
  4. once compiled and migrate then we can test with below command.
    > truffle console
                        
  5. In console
    > let cal = await Calculator.deployed()
    > cal.addToNumber(12,12)
                        
    Note : you will get the result transaction details.
4.1 : Compile, Test & Deploy using Ganache.
  1. In truffle-config.js file add below lines for ganache after 'development' property.
    ganache: {
      host: "127.0.0.1",     
      port: 7545,            
      network_id: "2022"       
    },
                      
  2. Open Ganache and create a new workspace, hit add project and select truffle-config.js
  3. Choose network id 2022 and leave all other setting to default
  4. Hit save workspace which open up the default accounts details.
  5. Goto Contract page it says contract not deployed.
4.2 : Deploying Contract.
  1. Open new Terminal and cd to truffle-cofig.js folder and type below command
    > truffle migrage --network ganache 
                      
4.3 :Invoke deployed smart contract
  1. Open new Terminal and cd to truffle-cofig.js folder and type below command
    > truffle console --network ganache
    > let cal = await Calculator.deployed()
    > cal.addToNumber(12,12)
                      
    Note : You will get the transaction result.

Step 5. Invoke smart contract from web browser using Java Sctipt.

5.1 : Using simple Html File with Javascript
  1. create a new file called index.html to truffle-cofig.js folder in your faviorte IDE and copy the below code into index.html
    
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Smart Contract</title>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous">
            <style>
                td {
                    padding: 5px;
                }
            </style>
        </head>
        <body>
            <div style="padding: 3%;">
                <h2>Ethereum Network Setup details.</h2>
                <table>
                    <tr>
                        <td>
                            <label>Ethereum Ganache RPC Server Url</label>
                        </td>
                        <td>
                            <input type="text" name="url" id="url" placeholder="http://127.0.0.1:8545">
                        </td>
                    </tr>    
                    <tr>
                        <td>
                            <label>Network Id from truffle-config.js file</label>
                        </td>
                        <td>
                            <input type="text" name="networkId" id="networkId" placeholder="2023">
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <input type="button" value="Click to initiate network." id="btn_initiate_network">
                        </td>
                    </tr>
                </table>
                <label style="color: green;" id="metadata_message_1"></label>
                <br>
                <label style="color: green;" id="metadata_message_2"></label>
            </div>
            <div id="smart_contract_meta_data" style="padding: 3%;" hidden  >
                <h2>Deployed Smart Contract Meta data.</h2>
                <table>
                    <tr>
                        <td>
                            Account Address : 
                        </td>
                        <td>
                            <input type="text" id="account_address" style="width: 400px;" required>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Account Private Key: 
                        </td>
                        <td>
                            <input type="text" id="account_private_key" style="width: 400px;" required >
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <label style="color: green;"><b>Note : </b>Account Address and private key you can get it from Ganache -> Accounts -> Show Private Key. Use the first Account.</label>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label>Deployed Smart Contract Address.</label>
                        </td>
                        <td>
                            <input type="text" id="address_smartcontract" style="width: 400px;" placeholder="Smart Contract Address get from Ganache -> Contract Tab." required >
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label></label>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <label><b>ABI for Calculator Smart Contract you can get it after compile of Smart Contract from build/contracts folder.</b></label>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            ABI of Calculator Smart Contract:
                        </td>
                        <td>
                            <textarea style="width: 400px; height: 300px;" id="abi_data" required>
    
    [
        {
          "inputs": [],
          "stateMutability": "nonpayable",
          "type": "constructor"
        },
        {
          "inputs": [],
          "name": "getResult",
          "outputs": [
            {
              "internalType": "uint256",
              "name": "",
              "type": "uint256"
            }
          ],
          "stateMutability": "view",
          "type": "function",
          "constant": true
        },
        {
          "inputs": [
            {
              "internalType": "uint256",
              "name": "num1",
              "type": "uint256"
            },
            {
              "internalType": "uint256",
              "name": "num2",
              "type": "uint256"
            }
          ],
          "name": "addToNumber",
          "outputs": [
            {
              "internalType": "uint256",
              "name": "",
              "type": "uint256"
            }
          ],
          "stateMutability": "nonpayable",
          "type": "function"
        },
        {
          "inputs": [
            {
              "internalType": "uint256",
              "name": "num1",
              "type": "uint256"
            },
            {
              "internalType": "uint256",
              "name": "num2",
              "type": "uint256"
            }
          ],
          "name": "substractFromNumber",
          "outputs": [
            {
              "internalType": "uint256",
              "name": "",
              "type": "uint256"
            }
          ],
          "stateMutability": "nonpayable",
          "type": "function"
        }
      ]
                            </textarea>
                        </td>
                    </tr>
                </table>
                <h2>Calculator Smart Contract</h2>
                <table>
                    <tr>
                        <td>
                            <label>Enter A Number : </label>
                        </td>
                        <td>
                            <input type="number" id="input_a" required value="12" style="width: 150px;"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label> Enter B Number: </label>
                        </td>
                        <td>
                            <input type="number" id="input_b" required value="15" style="width: 150px;"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label> Opetaions: </label>
                        </td>
                        <td>
                            <input type="button" name="Add" id="btn_add" value="Add" style="margin-right: 2%;">
                            <input type="button" name="Get Result" id="btn_getResult" value="Get Current Value">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label> Result </label>
                        </td>
                        <td>
                            <label id="final_result" style="color: green;"></label>
                        </td>
                    </tr>
                </table>
            </div>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>
            <script src="https://cdn.jsdelivr.net/npm/truffle-contract@4.0.31/dist/truffle-contract.min.js"></script>
            <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
            <script src="https://cdn.ethers.io/scripts/ethers-v4.min.js" charset="utf-8" type="text/javascript"></script>
            <script>
                //You need to start Ganache network in port. 
                let url = "http://127.0.0.1:8545";
                let networkId = 2023;
                let httpProvider;
                let contract_address;
                let account_address;
                let account_private_key;
                let abi;
                let wallet;
                let contractWithSigner;
                let contract;
    
                $(window).on('load',function() {
                    init();
                });
    
                function init() {
                    pageSetup();
                }
    
                function pageSetup() {
                    $('#btn_initiate_network').click(function() {
                        url = $('#url').val();
                        networkId = $('#networkId').val();
                        console.log("The url is",url);
                        console.log("And the network id Is ", networkId);
                        ethereumNetworkSetup();
                    });
    
                    $('#btn_add').click(function () {
                        initiateMetaData();
                        contract = new ethers.Contract(contract_address,abi,httpProvider);
                        wallet = new ethers.Wallet(account_private_key, httpProvider);
                        contractWithSigner = contract.connect(wallet);
                        
                        let valA = $('#input_a').val();
                        let valB = $('#input_b').val();
                        contractWithSigner.addToNumber(valA,valB).then((tx) => {
                            console.log("called the smart contract successfull. And the Has is : ", tx.hash);
                            tx.wait().then(() => {
                                contract.getResult().then((newValue) => {
                                    console.log(newValue);
                                    $('#final_result').text(newValue);
                                });
                            });
                        });
                    });
    
                    $('#btn_getResult').click(function () {
                        initiateMetaData();
                        contract = new ethers.Contract(contract_address,abi,httpProvider);
                        contract.getResult().then((result) => {
                            $('#final_result').text(result);
                        });
                    });
                    
                }
    
                function initiateMetaData() {
                    contract_address = $('#address_smartcontract').val();
                    abi = $('#abi_data').val();
                    account_address = $('#account_address').val();
                    account_private_key = $('#account_private_key').val();
                }
    
                function ethereumNetworkSetup() {
                    try {
                        httpProvider = new ethers.providers.JsonRpcProvider(url);
                        httpProvider.getBlockNumber().then((blockNu) => {
                            $('#metadata_message_1').text("Network Initiated Successfully. The total number of Block is : "+ blockNu + ".");
                            $('#metadata_message_2').text("Browser succecssfully able to communicate with your Ganache Network and its ready to invoke Calculator Smart Contract.")
                            $('#smart_contract_meta_data').show();
                        })
                    } catch(e) {
                        console.log(e);
                        alert('Error while setting up network. Check Ganache network up and running and Url is correct.');
                    }
                }
            </script>
        </body>
    </html>
    
    

Tutorial 2 : Deploy & Invoke Smart Contract in Infura Or Your Private Network dynamically.

In this blog you will be learning How to Deploy and Invoke Smart Contract in Infura Or Your private network.

Notes :

1 : To proceed with Tutorial 2. You need to complete Tutorial 1 Or You need to have basic understanding of Ethereum Blockchain.

2 : To proceed with Tutorial 2. You need to have Infura Account on any TestNets Or Your Private Ethereum Network Account Or Ganache to Depoy Smart Contract

3 : Using Metamask you can have your own TestNet accounts and using Ropsten Faucet You can get Ethers.



Connecting to Ethereum



Deploying New smart contract



Invoking Deployed Contract.


Is View Function? :

Tutorial 3 : BIP-39 Mnemonic Generation.

In this blog you will be learning How to Generate Mnemonic. Using this mnemonic you generate wallet address.

The Detailed explantion about Mnenonie Generation you can find in Medium Blog


Mnemonic Generation :


Step 1 : Mnemonic Calculation :





Step 2 : Initial Entropy Generation :



Step 3 : Finding Checksum :


Note : Finding Checksum is a manual process. We need linux or Unix Or Mac Device and need to execute below command.
echo initial_checksum | shasum -a 256 -0
Example : echo 00010101001000110100011101010001100001010001010001010010010000100101001100010000001001000010011001010001100000100010010100111000 | shasum -a 256 -0
You will get the Hash value. Enter the hash value in the text.


Step 4 : Final Entropy Bits :




Step 5 : Final Entropy String :



Step 6 : Validte Generated Entropy String :


Hige Security Zone.


Step 7 : Generate Seed :



Note : The Salt Key and Mnemonics(Final Entropy String) is very important. If you forgot any one. It is not possible to recover your address.
Note : You can note down your Mnemonics. But Your salt Key should be kept in secret.

Step 7 : Generate Address :


Tutorial 4 : Private Ethereum Wallet

Welcome to Private Ethereum Wallet. This is Offline Wallet & No Cokkies.
All the operation in Browser session only. Referesh browser leads to lossing the data.


Step 1 : Generate Address




Ethereum Wallet :

Wallet Operations :


Select Ethereum Network :

Accounts :