Friday, 18 January 2019

Blockchain Technology – A Study


    
Introduction :
Blockchain is a new technology where data is shared securely over a distributed network. It is a virtual database shared across networks. Blockchain contains a growing chain of records called blocks, data that are linked by cryptography. Each block contains cryptographic hash of previous block, a timestamp of creation, amd transacted data.Let us see the further discussions.

Decentralizarion:
The decentralized nature of blockchain technology means that it doesn’t rely on a central point of control. A lack of a single authority makes the system fairer and considerably more secure. The way in which data is recorded onto a blockchain epitomizes its most revolutionary quality: its value of decentralization. Rather than relying on a central authority to securely transact with other users, blockchain utilizes innovative consensus protocols across a network of nodes, to validate transactions and record data in a manner that is incorruptible. As a blockchain is a ledger of information it is extremely important that the information being stored is honest and accurate.

Why Decentralization ?
No single point of failure: Crashes and failures are the single biggest problem with any centralized network. A single failure can cause service disruption and potentially cause millions in losses. It might seem like redundancy can solve such problems, but incidents like the 2016 failure at Amazon Web Services that led to many major sites being inaccessible, prove otherwise.

Scalability advantage: Decentralized networks are made up of independent nodes. When the load on a network increases, the supply can easily increase as well. These nodes can simply be home computers with an internet connection. The owners of the computers are adequately compensated, receiving digital currency for their contribution.

Democratic decision making: Most centralized systems have a single authority that controls all the power and makes all the decisions. There are dozens of examples of how bad decision making by a central authority can be bad for users and make the entire system crumble. For example, a social media company that has total control over its users’ data.
Decentralized systems powered by the blockchain are the next logical step in the evolution of the internet. They are more robust, cheaper, scalable and give the power to the user base rather than to the monopolizing service providers.Security methods include usage of Public Key Cryptography. Consensus algorithms in blockchain are used to maintain data consistency in distributed network.



Distributed Ledger :
            The distributed ledger database is spread across several nodes (devices) on a peer-to-peer network, where each replicates and saves an identical copy of the ledger and updates itself independently. The primary advantage is the lack of central authority. When a ledger update happens, each node constructs the new transaction, and then the nodes vote by consensus algorithm on which copy is correct. Once a consensus has been determined, all the other nodes update themselves with the new, correct copy of the ledger. Security is accomplished through cryptographic keys and signatures.

Database vs Blockchain :
A user (client) with permissions associated with their account can change entries that are stored on a centralized server. By changing the ‘master copy’, whenever a user accesses a database using their computer, they will get the updated version of the database entry. Control of the database remains with administrators, allowing for access and permissions to be maintained be a central authority.
This is not at all the same as with a blockchain. For a blockchain database, each participant maintains, calculates and updates new entries into the database. All nodes work together to ensure they are all coming to the same conclusions, providing in-built security for the network.
  Blockchain Architecture :
A blockchain is a database that is shared across a network of computers. Once a record has been added to the chain it is very difficult to change.To ensure all the copies of the database are the same, the network makes constant checks. Blockchains have been used to underpin cyber-currencies like bitcoin, but many other possible uses are emerging.     
  Blocks: 
          Blocks contain pieces of valid transactions that are hashed and encoded into Merkle Tree. Each block contains cryptographic hash of prior block in the chain, linking the two. The link is iterative and hence determines the integrity of previous block.The chain is irreversible and immutable. Blocks are chained together, preventing any block from being altered or a block being inserted between two existing blocks. Blocks not included in chain are orphan blocks.

  Block Time:
The block time is the average time it takes for the network to generate one extra block in the blockchain. Some blockchains create a new block as frequently as every five seconds.[ By the time of block completion, the included data becomes verifiable. In cryptocurrency, this is practically when the transaction takes place, so a shorter block time means faster transactions. The block time for Ethereum is set to between 14 and 15 seconds, while for bitcoin it is 10 minutes
  The design aspects of blockchain contains ,
1.      The Blockchain platform itself
2.      The role of Nodes in constituting the overall blockchain & the Node discovery process
3.      Transactions that make up the blocks running in the Nodes
4.      Security implementation that generates the Blocks
5.      The process of adding newer blocks to the Chain
Main components of a Block are,
   Block Header(version):  indicates which set of block validation rules to follow
   TimeStamp                  :  current time as seconds in universal time since January 1, 1970.
    Nonce, nBits                :  an 4-byte field, which usually starts with 0 & increases for every  calculation/target threshold of a valid block hash. (Transaction Counter)
   Merkle tree root hash   : the hash value of all the transactions in the block.
   Parent Block Hash        : a 256-bit hash value that points to the previous block.



 Digital Signature :
Digital Signatures are used as a symbol of confidentiality and data protection. It uses a Publiv-Private Key Cryptography. The private key is confidential and kept secret to sign the transactions. The two phases involved are signing and verification. In signing phase, the sender encrypts data with his private key and sends the encrypted result + original doc. In verification phase, receiver validates the value with sender’s public key to check if tapered or not. The algorithm used for digital signatures are Elliptical Curve Digital Signatur Algorithm(ECDSA). Using digital signatures, the proof of work for each node/transaction can be recorded. In blockchain the records on a blockchain are secured through cryptography. Network participants have their own private keys that are assigned to the transactions they make and act as a personal digital signature. If a record is altered, the signature will become invalid and the peer network will know right away that something has happened. Early notification is crucial to preventing further damage.

What makes Blockchain so secured ?
            What makes this system theoretically tamperproof is two things: a cryptographic fingerprint unique to each block, and a “consensus protocol,” the process by which the nodes in the network agree on a shared history. The fingerprint, called a hash, takes a lot of computing time and energy to generate initially. It thus serves as proof that the miner who added the block to the blockchain did the computational work to earn a bitcoin reward (for this reason, Bitcoin is said to use a “proof-of-work” protocol). It also serves as a kind of seal, since altering the block would require generating a new hash. Verifying whether or not the hash matches its block, however, is easy, and once the nodes have done so they update their respective copies of the blockchain with the new block. This is the consensus protocol.
The final security element is that the hashes also serve as the links in the blockchain: each block includes the previous block’s unique hash. So if you want to change an entry in the ledger retroactively, you have to calculate a new hash not only for the block it’s in but also for every subsequent block. And you have to do this faster than the other nodes can add new blocks to the chain. So unless you have computers that are more powerful than the rest of the nodes combined (and even then, success isn’t guaranteed), any blocks you add will conflict with existing ones, and the other nodes will automatically reject your alterations. This is what makes the blockchain tamperproof, or “immutable.”


Sunday, 28 January 2018

Cryptocurrency -A study

CryptoCurrency – A study

Cryptocurrency in general a reference to all decentralized digital currencies.It uses crptography for coin creation and online transactions.They are open source and available publicly with a transaction ledger to record the transactions.
In other words, Cryptocurrency is a virtual money over the internet.
The decentralized nature of cryptocurrencies prevents any single authority, such as a central bank or government, from ultimate control. By maintaining a public ledger, known as a blockchain, cryptocurrencies provide transparency, which is essential for building trust between untrusted parties. With the core software open sourced,anybody can view, submit bug fixes, or submit updates, which in turn helps improve the system.All Bitcoin transactions are stored publicly and permanently on the network, which means anyone can see the balance and transactions of any Bitcoin address. However, the identity of the user behind an address remains unknown until information is revealed during a purchase or in other circumstances.
crypcurr
In cryptocurrency, the term “token” describes a digital asset. It refers to the fact that cryptos are both value tokens / currency tokens (they represent value, but aren’t themselves of any inherent value) and they use strings of data called tokens (tokenization is a type of encryption).

How It works ??

As Bitcoin was the original open source cryptocurrency, most others are built using the same core technologies, such as keys, wallets, miners, and decentralized peer­to­peer networks. Ownership of cryptocurrencies requires a pair of keys (one public and one private), each a unique string of numbers and letters. It relies on the power of the internet to guarantee its value and confirm transactions. Users on a network verify every transaction, and those transactions then become a matter of public record. This prevents the same digital currency or coin from being spent twice by the same person.A public key functions as an “address”, to which other users send units of the cryptocurrency. A private key is kept confidential and allows a user to claim ownership of the associated cryptocurrency units. Wallets store the cryptographic keys that are used to access a currencies.

Mining of Coins(Currencies)

The currency creation (coins) in cryptocurrencies involves a process called as mining. The traders(miners) use a mathematical cryptographic algorithm to be solved to obtain certain amount of bitcoins in exchange.

Risks in Cryptocurrency 

As with all currencies, cryptocurrencies come with risks. The more prominent risks come from theft, fraud, volatility, technical failures, lack of government support, regulatory uncertainty, competition from other currencies, and level of adoption. Many of these risks could result in one or more cryptocurrencies losing all value. For cryptocurrencies, theft most often occurs online from either an insider, an individual who works at or has physical access to the company, or an outside individual, who
gains unauthorized access to the company’s or individual’s systems online through a hack. In both cases, control of the cryptocurrency is transferred away from the owner. There have been two main targets for theft: exchanges and users. Over the last five years, many cryptocurrency exchanges have been hacked resulting in theft and the loss of cryptocurrency.
For further queries in cryptocurrency link with me @ Codes for Life !!
Thank You !!
– Sanjaydeep G

Friday, 19 January 2018

BlockChain - The Beginning

Blockchain—a kind of distributed ledger technology—has been described in the popular press as the next big thing. It is a data structure of cryptographically linked “blocks” of transactions that are virtually impossible to change or remove without being detected. Therein lies its strength.

Blockchain technology is the technology that allows users to maintain  a ledger having all transactions data and update them to maintain integrity when a new transmission occurs. It is a structured list that saves data in the form of a distributed database which is designed to make an arbitrarily manipulating it difficult since the network participants save and verify blockchain. 

An important part of blockchain is security related to the personal  key used in encryption. An attacker carries out various attempts to access a user’s person key stored in user’s computer or any device inorder to hack the bitcoin. The integrity of transactions can be verified through the public key based encryption of the hash value of transmission data.  

All transactions are logged and made available in a public ledger, helping ensure their authenticity and preventing fraud. Each time a transaction takes place, such as sender sending data to cloud storage or   receiver , the details of that deal including its source destination, timestamp, are added for refrence as a block . 

The validity of the transactions within the cryptographically protected block is then cheked and confirmed by the collective computing power of miners within the network.  


Blockchain works on the basis of elliptic curve digital signature algorithm. Since blockchain is a publicly available ledger. On an individual basis, these miners are computers which are configured to utilize their GPU and/or CPU cycles to solve complex mathematical problems, passing the block's data through a hashing algorithm until a solution is found. 

Once solved, the block and all of its respective transactions have been verified as legitimate. Rewards (bitcoin, in this example) are then divvied up among the computer or computers that contributed to the successful hash. 
The property of decentralization is the advantage of blockchaining the user data.

The records inside the chain aren’t stored in a single location and it is immutable by any single party. Implementation of blockchain technologycan create a verifiable record of any data.  

CodesForLife!!

Sunday, 25 June 2017

Encryption and Decryption

Hi friends,
the code for life we discuss here is,

SQUARE ENCRYPT

A secret code encrypts a message by putting it in an array and reading down the columns (blanks are replaced by asterisks and full stops are added to fill up the array).

Write a program that encrypts an input string. (For extra marks write a program that decrypts a given string using the rules outlined above.)

LETS*G
O*TO*T HE*SAN DWICH* SHOP*T ODAY..

 Input:         “Lets go to the sandwich shop today”
Output:      “Lohdsoe*ewhdtt*ioasoscpy**ah*.gtn*t.”

CODE:

package sanjay;
import java.util.*;
public class encrypt {
   public static void main(String args[])
   {
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter a string : ");
       String s1=sc.nextLine();
       int length=s1.length();
       String s2[]=new String[100];         //to store as a char array
       for(int z=0;z<s2.length;z++)
       {
           s2[z]="";                        //2nd array s 1st position
       }
       int count=0;
        int j=0;
       for(int i=0;i<s1.length();i++)
       {
               if(s1.charAt(i)==' ')           //if space then
               {
                   String str="*";            //assign *
                   s2[j]=s2[j]+str;           //to link wid next word
                   count++;
               }
               else
               {
                   s2[j]=s2[j]+s1.charAt(i);    //1&2nd arrays 1st pos +
                   count++;
               }
               if(count!=6&&i==s1.length()-1)
               {
                   for(int x=count;x<6;x++)
                   {
                       s2[j]=s2[j]+".";         //to fill blanks wid .
                   }
               }
               if(count==6)
               {
                   j++;
                   count=0;
               }
        }
       for(int k=0;k<6;k++)
       {
           for(int y=0;y<=j;y++)
           {
                System.out.print(s2[y].charAt(k));
           }
       }
   }

}

Rotating a NXN Mratrix

Hello friends !!
Today's code for life is,
Imagine a square pattern divided into smaller squares as shown below. As you can  see seven of the smaller squares are filled in. If this is rotated clockwise by 90 degrees and placed on top of the original pattern then more squares are filled in.

The total number of filled in squares is now 13. Continuing in this way you can again rotate and add the original pattern to the combination giving 19 black squares and one more rotation + addition gives 25 black squares.


You must write a program that will read in a square pattern and output the original number of black squares and the number that result from each rotation.

Input:

-  an integer N on a single line
-  the next N lines consist of the NxN square,
(where 1 represents a black square and 0 represents a white square)

Output:

-      four lines containing the number of black squares before each rotation



CODE:

package sanjay😊;
import java.util.*;
public class matrixrotate {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the matrix size: ");
        int arr[][]=new int[100][100];          //2d matrix array
        int i,j,k,m,l;
         int old_arr[][]=new int[100][100];     //initial array
          int add_arr[][]=new int[100][100];    // after rotatong to add new array
         int no_rotation=0;
         int rotation;
        int n = input.nextInt();
        System.out.println("Enter the matrix elements as 1 and 0: ");
        for( i=0;i<n;i++)
        {
            for( j=0;j<n;j++)
            {
                arr[i][j]=input.nextInt();
            }
        }
         System.out.println("The Entered matrix is:");
        for(i=0;i<n;i++)
        {
             for( j=0;j<n;j++)
            {
            if(arr[i][j]>0)
            {
                no_rotation++;
            }
            }
             System.out.println("");
        }
        for( k=1;k<5;k++)
        {
            rotation=0;
             System.out.println("Rotation:"+k);
            for ( i = 0; i < n / 2; i++)
            {
            for ( j = i; j < n - i - 1; j++)
            {
            int temp= arr[i][j];
            arr[i][j] = arr[n - j - 1][i];
            arr[n - j - 1][i] = arr[n - i - 1][n - j - 1];
            arr[n - i - 1][n - j - 1] = arr[j][n - i - 1];
            arr[j][n - i - 1] = temp;
            }
            }
            for(m=0;m<n;m++)
            {
                for(l=0;l<n;l++)
                {
                                add_arr[m][l]=old_arr[m][l]+arr[m][l];
                                  if(add_arr[m][l]>0)
                                  {
                                      rotation++;
                                  }
                                  arr[m][l]=add_arr[m][l];
                                  old_arr[m][l]=add_arr[m][l];
                }
             }
            System.out.println("Rotation values grater than 1:"+rotation);
            }  
      }
}

Saturday, 24 June 2017

Assigning Wifi password for a new user !

Hello friends,
In today's problem we discuss about assigning a password for a hotel wifi conection based on the inputs by the user based on certain criteria !!

Conditions:

  • Length of password is to be 5 characters
  • 1st char- summation of room number(till it becomes a single digit)
  • 2nd char- 1st char of lastname (if no last name,then first name)
  • 3rd char- summation of mobile number(1 digit)
  • 4th char- random mo generated system
  • 5th char- if person is from locality then no of chars in 1stname ,if it is odd then add 1,else
  • print the last index of firstname

CODE:

package sanjay;
import java.util.*;
public class wifiassign {
static  String password="";
static int sum_of_digits(long num)
{
long sum=0;
long rem=0;
while(num>0)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
return (int)sum;
}
static int no_of_digits(long num)
{
int nod=0;
while(num>0)
{
num=num/10;
nod++;
}
return nod;
}
static int getRandomNumberInRange(int min, int max) {

if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String first_name="";
String middle_name="";
String last_name="";
long phno=0;
int room_no=0;
String area="";
String name="";
System.out.println("Enter the name : ");
name=sc.nextLine();
System.out.println("Enter the area(Rural/Urban) : ");
area=sc.nextLine();
System.out.println("Enter the mobile number : ");
phno=sc.nextLong();
System.out.println("Enter the room number : ");
room_no=sc.nextInt();
String names[]=name.split(" ");
int char1=sum_of_digits(room_no);
int dig1=no_of_digits(char1);
while(dig1>1)
{
char1=sum_of_digits(char1);
dig1=no_of_digits(char1);
}
password=password+char1;
password=password+names[1].charAt(0);
int char3=sum_of_digits(phno);
//System.out.println(char3);
int dig3=no_of_digits(char3);
while(dig3>1)
{
char3=sum_of_digits(char3);
dig3=no_of_digits(char3);
}
password=password+char3;
int char4=getRandomNumberInRange(0,9);
password=password+char4;
int char5=0;
int dig5=0,len=0;
if(area.equalsIgnoreCase("Rural"))
{
len=names[0].length();
if(len%2==0)
{
char5=len;
dig5=no_of_digits(char5);
while(dig5>1)
{
char5=sum_of_digits(len);
dig5=no_of_digits(char5);
}
}
else
{
char5=len+1;
dig5=no_of_digits(char5);
while(dig5>1)
{
char5=sum_of_digits(len);
dig5=no_of_digits(char5);
}
}

}
if(area.equalsIgnoreCase("Urban"))
{
len=names[0].length();
char5=len;
dig5=no_of_digits(char5);
while(dig5>1)
{
char5=sum_of_digits(len);
dig5=no_of_digits(char5);
}
}
password=password+char5;
System.out.println("Password is : "+password);
}
}

BlockChain Company Infographic

Hello All,      This post talks about the impact of blockchain technology in various standards and industrial uses. Kindly do read to know i...