Consensus Mechanism In Blockchain System | RAJESH GAMI

 What is Consensus

We know that blockchain is a distributed ledger, so let’s say we have 4 mining nodes here. So, all these nodes will have a copy of a blockchain, all these copies will be of same state, so they are exact copies here. If we got a new block to add and it should be added to blockchain. Let’s say that node 4 is adding the block to its blockchain and it’s replicated in all nodes. Now what if node 4 is malicious. How will we make sure that all the nodes follow the same protocol and have the same copy of information?

That’s where consensus algorithm comes to play. In the modern world we have lot of consensus algorithm using which we ensure that all the nodes have the same state of information.

Consensus Mechanism

Based on it is permission less or permissioned blockchain, we have a lot of mechanism. The first one is Proof of Work (PoW) which is one of the famous algorithm and Bitcoin uses the PoW to achieve consensus. All of these nodes will utilise some computational power, and the node with the most computing power will solve the problem and adds a block to the blockchain.

Proof of Work (PoW)

As we saw above whoever adds the block to the blockchain to undergo some mathematical puzzle, where it undergoes inverse hashing technique to solve. The node which solves these puzzles using high computational power will receive some reward.

Why do we need PoW?

If you are using high computational power, the chances of being a malicious node is reduced.

Now if we have 30 blocks and if the malicious node wants to change the 25 blocks. It will affect the hash of all remaining block and we start to recalculate the hash of remaining blocks; it will take some time since each and every block has to under go proof of work and also it consumes some computing power. At the time of doing all these processes, some other node will add a new block. All these works will be in veins.

What is the mathematical puzzle?

The complexity of the puzzle depends on,

  • Network size
  • Active users
  • Blockchain size and many other factors

 The puzzle will be of mathematical calculation like, given a three-digit numbers and find the factors of that number and it also has some more logics. Now this problem may be easy one but the real-world problem will be a difficult one and it take some time to calculate.

There is a famous hashing algorithm called sha256 algorithm which gives a hexadecimal number for each and every input and if you change even a single letter in the input, the whole hexadecimal number will change. So we have regenerate every time to get the correct input.

So, if we have the hexadecimal code and if we want to find the information, that’s where we will be doing a lot of calculations.

DRAWBACKS

  • Loss of computational power, because many nodes will participate in solving mathematical puzzle, but only one node gets the reward.
  • 51 percent attack – if blockchain node have 100 nodes and 51 nodes are malicious, then more than 50 percent of the network is corrupted.

Proof of Stake(PoS)

To overcome the drawbacks of PoW, PoS was introduced. In order to participate in Pos, the validators has to produce some stake. In Pow, the block is mined by the node which has the high computational power. But in PoS the validators are selected in terms of some selection algorithm and the amount of stake they hold and only then that validator will be allowed to add the block and the other validators need not waste any computational power since they are not selected. If the validator founds to be malicious, then they will lose their stake.

DIFFERENCE BETWEEN PoW AND PoS

PROOF OF WORK(PoW)PROOF OF STAKE(PoS)
A proof of work is a piece of data which is difficult to produce but easy for others to verify and which satisfies certain requirementsProof of stake is a proposed alternative to proof of work.
With proof of stake, the resource that’s compared is the amount of bitcoin a miner holds.
The probability of mining a block is dependent on how much work is done by the miner.Person can mine depending on how many stack they hold
Pay-outs become smaller and smaller for bitcoin miners. There is less incentive to avoid a 51% attack.The PoS system makes any 51% attack more expensive.
Proof of work high computing power hardware which is expensiveProof of stake no need of expensive hardware.
Proof of work requires more electric powerProof of stake is energy efficient.

How to clone SQL Table | SQL Server Clone Table | RAJESH GAMI

 

Sometimes, in some situations, we need the exact copy structure of the table or the exact copy structure of a table with data.

In SQL, Clone means when you create an exact copy of your original table or only copy the exact structure of your table.

When we require SQL Clone?

  1. When we perform some tests, there is a chance to change the data, so without affecting the original table, we create a copy of the table and perform all tests on that table.
  2. When we want to make a backup of the original table. So, we create a backup table with a clone.

In such a circumstance, we make a clone table in SQL. In this manner, we spare our time and exertion of making a totally new table and entering all the same information once.

There are three kinds of SQL clones.

1. Simple cloning

This is the simplest way to clone a table. Simple cloning simply means copying data from the original table without inheriting any column attributes or indexes.

Syntax

CREATE TABLE <new_table> SELECT * FROM <original_table>;
SQL

2. Shallow cloning

Shallow cloning is generally employed to form a duplicate of an existing table's information structure and column traits without the information being replicated. This will, as it were, make a purge table based on the structure of the first table.

This type of cloning is done when you only need the structure and all column attributes of the original table.

Syntax

CREATE TABLE <new_table> LIKE <original_table>;
SQL

3. Deep cloning

Deep cloning is similar to shallow cloning in that it copies data from the original table. As a result, deep cloning copies both the data and the structure of the original table.

This strategy is the more broadly utilized one for making clone tables in SQL, as here each property of the first table is kept up just like the records and the auto_increment. From the original table, we get the information replicated to the clone table.

Syntax

CREATE TABLE <new_table> LIKE <original_table>;
INSERT INTO <new_table> SELECT * FROM <original_table>;
SQL

Summary

Cloning means copying data from one table to another.

  • Simple Cloning - Simply copy data from the original table without any column attributes and index.
  • Shallow Cloning - Copy only the structure from the original table with all column attributes and index. However, without table data
  • Deep Cloning - Same as shallow cloning but also clone table data

ASP.NET Core Web API 6.0 With Entity Framework & SQL Procedure | RAJESH GAMI

 We learn ASP.NET Core Web API 6.0 With EF & SQL RepositoryPattern,

STEP 1

Create ASP.NET Core Web API Project 

ASP.NET Core Web Api using 6.0 With Entity FrameWork & Sql Procedure

STEP 2

ASP.NET Core Web Api using 6.0 With Entity FrameWork & Sql Procedure

STEP 3

ASP.NET Core Web Api using 6.0 With Entity FrameWork & Sql Procedure

STEP 4

Create Table in SQL 

CREATE TABLE [dbo].[Tbl_Account](
	[AC_ID] [bigint] IDENTITY(1,1) NOT NULL,
	[AC_Name] [varchar](max) NULL,
	[AC_Number] [nvarchar](max) NULL,
	[AC_isactive] [bit] NULL,
PRIMARY KEY CLUSTERED
(
	[AC_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SQL

Step 5

Create Procedure in SQL

CREATE  proc [dbo].[Proc_InsertAccount]
(
    @AC_ID bigint=null,
    @AC_Name varchar(max)=null,
    @AC_Number varchar(max)=null,
    @AC_Isactive bit=null,
    @Flag varchar(max)=null,
    @AC_IDOutput bigint output
)
as
begin

IF(@Flag ='IN')
BEGIN

insert into Tbl_Account(AC_Name,AC_Number,AC_isactive)
values (@AC_Name,@AC_Number,@AC_Isactive)

SET @AC_IDOutput = @@IDENTITY

END
ELSE IF(@Flag='UP')
BEGIN

UPDATE Tbl_Account SET AC_Name=@AC_Name,AC_Number=@AC_Number,AC_isactive=@AC_isactive WHERE AC_ID=@AC_ID
SET @AC_IDOutput = @AC_ID
END
ELSE IF(@Flag='DE')
BEGIN

DELETE FROM Tbl_Account  WHERE AC_ID=@AC_ID

END

end
SQL

Step 6

CREATE Proc [dbo].[Proc_Account]
as
select * from Tbl_account
retrun
SQL

Step 7

Add EFCoreEntity & EFSql Entity from nuget package

Step 8

Add the Connection string in Appsettings.json file

ASP.NET Core Web Api using 6.0 With Entity FrameWork & Sql Procedure

"ConnectionStrings": {
    "Con": "Data Source=SERVER-8777;User ID=sa;Password=8777;Initial Catalog=SqlBankCore;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  }
SQL

Step 9

Configure Connection String in Program.cs file

using Microsoft.EntityFrameworkCore;
builder.Services.AddDbContext<DataBaseContext>
    (options => options.UseSqlServer(builder.Configuration.GetConnectionString("Con")));
C#

Step 9

Add interface folder under solution & add Interface for Account

using SqlBankApi7.Model;

namespace SqlBankApi7.Interface
{
    public interface IAccount
    {
        public List<Common> GetAccountDetails();
        public Common AddAccount(Account account);
        public void UpdateAccount(Account account);
        public Account DeleteAccount(Account account);
    }
}
C#

Step 10

Create model folder under solution & create class Account,

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SqlBankApi7.Model
{
    public class Account
    {
        [Key]
        public long AC_ID { get; set; }
        public string? AC_Name { get; set; }
        public string? AC_Number { get; set; }
        public bool AC_isactive { get; set; }
        [NotMapped]
        public string? Flag { get; set; }
    }
}
C#

Step 11

Add DatabaseContext folder under project solution & create Database context class,

using Microsoft.EntityFrameworkCore;
using SqlBankApi7.Model;
namespace SqlBankApi7.DataBaseContext
{
    public partial class DataBaseContext : DbContext
    {

        public DataBaseContext()
        {
        }
        public DataBaseContext(DbContextOptions<DataBaseContext> options)
            : base(options)
        {
        }
        public virtual DbSet<Account>? Accounts { get; set; }
        public virtual DbSet<User>? Users { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>(user =>
            {
                user.HasKey(u => u.UserID);
                user.ToTable("Tbl_User");
                user.Property(u => u.UserID).HasColumnName("UserID");
                user.Property(u => u.DisplayName).HasMaxLength(50).IsUnicode(false);
                user.Property(u => u.UserName).HasMaxLength(50).IsUnicode(false);
                user.Property(u => u.Email).HasMaxLength(50).IsUnicode(false);
                user.Property(u => u.Password).HasMaxLength(50).IsUnicode(false);
                user.Property(u => u.CreatedDate).IsUnicode(false);
            });
            modelBuilder.Entity<Account>(entity =>
            {
                entity.HasKey(e => e.AC_ID);
                entity.ToTable("Tbl_Account");
                entity.Property(e => e.AC_Name).HasMaxLength(100).IsUnicode(true);
                entity.Property(e => e.AC_Number).HasMaxLength(100).IsUnicode(true);
                entity.Property(e => e.AC_isactive).HasMaxLength(100).IsUnicode(true);
                OnModelCreatingPartial(modelBuilder);
            });
        }
        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}
C#

Step 12

We are using Repository Pattern for this core web API. Now create repository folder under solution & create Common class & AccountRepository.cs class

using SqlBankApi7.Model;
using System.ComponentModel.DataAnnotations.Schema;

namespace SqlBankApi7
{
    public class Common
    {
      public  List<Account>? Table { get; set; }
        [NotMapped]
        public string? Message { get; set; }
        [NotMapped]
        public int StatusCode { get; set; }
        [NotMapped]
        public string? Status { get; set; }
    }
}
C#

 

using SqlBankApi7.Interface;
using SqlBankApi7.Model;
using SqlBankApi7.DataBaseContext;
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.SqlClient;

namespace SqlBankApi7.Repository
{
    public class AccountRepository : IAccount
    {
        readonly DataBaseContext.DataBaseContext _dbContext = new();

        public AccountRepository(DataBaseContext.DataBaseContext dbContext)
        {
            _dbContext = dbContext;
        }

        public Common AddAccount(Account account)
        {
            Common cmm = new Common();
            cmm.Table = new List<Account>();
            List<Account> lstaccounts = new List<Account>();
            try
            {

                // string Proc_InsertAccount = "Exec Proc_InsertAccount @AC_Name = '" + account.AC_Name + "',@AC_Number= '" + account.AC_Number + "',@AC_Isactive='" + account.AC_isactive + "'";
                SqlParameter[] sqlParameters = new SqlParameter[6];
                sqlParameters[0] = new SqlParameter("@AC_ID", System.Data.SqlDbType.BigInt);
                sqlParameters[1] = new SqlParameter("@AC_Name", System.Data.SqlDbType.NVarChar);
                sqlParameters[2] = new SqlParameter("@AC_Number", System.Data.SqlDbType.NVarChar);
                sqlParameters[3] = new SqlParameter("@AC_Isactive", System.Data.SqlDbType.Bit);
                sqlParameters[4] = new SqlParameter("@Flag", System.Data.SqlDbType.VarChar);
                sqlParameters[5] = new SqlParameter("@AC_IDOutput", System.Data.SqlDbType.BigInt);
                sqlParameters[0].Value = account.AC_ID;
                sqlParameters[1].Value = account.AC_Name;
                sqlParameters[2].Value = account.AC_Number;
                sqlParameters[3].Value = account.AC_isactive;
                sqlParameters[4].Value = account.Flag;
                sqlParameters[5].Direction = System.Data.ParameterDirection.Output;
                int Status=   _dbContext.Database.ExecuteSqlRaw("Proc_InsertAccount @AC_ID, @, @, @AC_IDOutput output ", sqlParameters);
                _dbContext.SaveChanges();
                if (Status == 1)
                {
                    account.AC_ID =Convert.ToInt64(sqlParameters[5].Value);
                    lstaccounts.Add(account);
                    cmm.Table = lstaccounts;
                    cmm.Status = "Sucess";
                    cmm.StatusCode = 1;
                    cmm.Message = "Record Inserted Sucessfully...";
                }
                else
                {
                  //  lstaccounts.Add(account);
                    cmm.Table = null;
                    cmm.Status = "Un-Sucess";
                    cmm.StatusCode = 0;
                    cmm.Message = "Record Inserted Failed...?";
                }

                #region below COde for insert Data by using Entity framework
                _dbContext.Accounts.Add(account);
                _dbContext.SaveChanges();
                #endregion
            }
            catch (Exception ex)
            {
                cmm.Table = null;
                cmm.Status = "Un-Sucess";
                cmm.StatusCode = 0;
                cmm.Message = ex.Message;
             //   throw;
            }
            return cmm;
        }

        public Account DeleteAccount(Account account)
        {
            try
            {
                SqlParameter[] sqlParameters = new SqlParameter[5];
                sqlParameters[0] = new SqlParameter("@AC_ID", System.Data.SqlDbType.BigInt);
                sqlParameters[1] = new SqlParameter("@AC_Name", System.Data.SqlDbType.NVarChar);
                sqlParameters[2] = new SqlParameter("@AC_Number", System.Data.SqlDbType.NVarChar);
                sqlParameters[3] = new SqlParameter("@AC_Isactive", System.Data.SqlDbType.Bit);
                sqlParameters[4] = new SqlParameter("@Flag", System.Data.SqlDbType.VarChar);
                sqlParameters[0].Value = account.AC_ID;
                sqlParameters[1].Value = account.AC_Name;
                sqlParameters[2].Value = account.AC_Number;
                sqlParameters[3].Value = account.AC_isactive;
                sqlParameters[4].Value = account.Flag;
                _dbContext.Database.ExecuteSqlRaw("Proc_InsertAccount @AC_ID , @, @ ", sqlParameters);
                _dbContext.SaveChanges();

                #region Below code for update data by using Entityframework
                Account? acc = _dbContext.Accounts.Find(account.AC_ID);
                if (acc != null)
                {
                    _dbContext.Entry(account).State = EntityState.Modified;
                    _dbContext.SaveChanges();
                }
                #endregion
            }
            catch
            {

                throw;
            }
            //_dbContext.Accounts.Remove(account);
            //_dbContext.SaveChanges();
            return account;
        }

        public List<Common> GetAccountDetails()
        {
            Common Ac = new Common();
           List<Account> accountList = new List<Account>();
            List<Common> lstCom = new List<Common>();
            try
            {
                accountList = _dbContext.Accounts.FromSqlRaw("Proc_Account").ToList();
                if (accountList != null)
                {
                    if (accountList != null)
                    {
                        Ac.Table = accountList;
                        Ac.StatusCode = 1;
                        Ac.Message = "Record fetching sucessfully...";
                        Ac.Status = "Sucess";
                    }
                }
                else
                {
                  //  if (Ac.Table != null)
                    {
                        Ac.Table = null;
                        Ac.StatusCode = 1;
                        Ac.Message = "No Records found...?";
                        Ac.Status = "Fail";
                    }

                }
            }
            catch
            {
                throw;
            }
            lstCom.Add(Ac);
            return lstCom;
        }
        public void UpdateAccount(Account account)
        {
            try
            {
                SqlParameter[] sqlParameters = new SqlParameter[5];

                sqlParameters[0] = new SqlParameter("@AC_ID", System.Data.SqlDbType.BigInt);
                sqlParameters[1] = new SqlParameter("@AC_Name", System.Data.SqlDbType.NVarChar);
                sqlParameters[2] = new SqlParameter("@AC_Number", System.Data.SqlDbType.NVarChar);
                sqlParameters[3] = new SqlParameter("@AC_Isactive", System.Data.SqlDbType.Bit);
                sqlParameters[4] = new SqlParameter("@Flag", System.Data.SqlDbType.VarChar);
                sqlParameters[0].Value = account.AC_ID;
                sqlParameters[1].Value = account.AC_Name;
                sqlParameters[2].Value = account.AC_Number;
                sqlParameters[3].Value = account.AC_isactive;
                sqlParameters[4].Value = account.Flag;
                _dbContext.Database.ExecuteSqlRaw("Proc_InsertAccount @AC_ID , @, @ ", sqlParameters);
                _dbContext.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
    }
}
C#

Add Controller folder under solution & add controller class AccountController.cs

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlBankApi7.Interface;
using SqlBankApi7.Model;
namespace SqlBankApi7.Controllers
{
    [Authorize]

    [ApiController]

    public class AccountController : ControllerBase
    {
        private readonly IAccount _IAccount;
        public AccountController(IAccount IAccounts)
        {
            _IAccount = IAccounts;
        }
        [Route("api/GetAccountDetails")]
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Common>>> GetAccountDetails()
        {
            return await Task.FromResult(_IAccount.GetAccountDetails());
        }
        [Route("api/AddAccount")]
        [HttpPost]
        public Common AddAccount(Account account)
        {
         return   _IAccount.AddAccount(account);
        }
        [Route("api/UpdateAccount")]
        [HttpPut]
        public void UpdateAccount(Account account)
        {
            _IAccount.UpdateAccount(account);
        }
        [Route("api/DeleteEmployee")]
        [HttpDelete]
        public void DeleteEmployee(Account account)
        {
            _IAccount.DeleteAccount(account);
        }
    }
}
C#

Now run the application & check output.

ASP.NET Core Web Api using 6.0 With Entity FrameWork & Sql Procedure

ASP.NET Core Web Api using 6.0 With Entity FrameWork & Sql Procedure

    RAJESH GAMI - Blog

    Digital Signature Pad in Angular | RAJESH GAMI

      What is Signature Pad? Signature Pad could be a JavaScript library for drawing fancy signatures. It supports HTML5 canvas and uses variabl...