Monday, September 23, 2019

Calling Ethereum contract using Web3 Provider

For using Web Provider option we need to install Ganecha cli using npm command

npm install -g ganache-cli

once install run this command

ganache-cli

Image1

now choose the web provider as environment in remix IDE as shown below
Image2

and deploy the application and now you can perform operation of deposits and withdraw using same.

Wednesday, September 18, 2019

Accessing Ethereum files using Web Application

I am using Node and NPM and Visual studio as IDE and npm http-server. Make sure to install the same. To manipulate the value of our file on html we are using jQuery.
Consider this is our html file
'<html>
'
'<head>
' <meta charset="UTF-8">
' <title>Siddhu Ethererum Example</title>
'
'</head>
'
'<body>
' <input type="text" id="amount">
'
' <p id="balanceValue"></p>
' <button id="deposite">Deposite</button>
' <button id="withdraw">Withdraw</button>
' <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.36/dist/web3.min.js"></script>
' <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" crossorigin="anonymous"></script>
' <script>
' var contract;
'
'
' $(document).ready(
' function () {
' web3 = new Web3(web3.currentProvider);
'
' var address = "Myaddress";
' var abi = [{
' "constant": false,
' "inputs": [{
' "name": "amount",
' "type": "int256"
' }],
' "name": "depositeMyBalance",
' "outputs": [],
' "payable": false,
' "stateMutability": "nonpayable",
' "type": "function"
' },
' {
' "constant": false,
' "inputs": [{
' "name": "amount",
' "type": "int256"
' }],
' "name": "withdrawMyBalance",
' "outputs": [],
' "payable": false,
' "stateMutability": "nonpayable",
' "type": "function"
' },
' {
' "inputs": [],
' "payable": false,
' "stateMutability": "nonpayable",
' "type": "constructor"
' },
' {
' "constant": true,
' "inputs": [],
' "name": "getBalanceValue",
' "outputs": [{
' "name": "",
' "type": "int256"
' }],
' "payable": false,
' "stateMutability": "view",
' "type": "function"
' }
' ];
' contract = new web3.eth.Contract(abi, address);
' contract.methods.getBalanceValue().call().then(
' function (bal) {
' console.log("bal"+bal);
' document.getElementById
' $("#balanceValue").html(bal);
' })
' })
' //Deposite
' $('#deposite').click(function()
' {
' var amount = 0;
' amount = parseInt($('#amount').val());
' console.log("amount"+amount);
'
' // web3.eth.getAccounts().then(e => console.log("---------------"+e));
' web3.eth.getAccounts().then(function(accounts)
' {
' var acc = accounts[0];
' console.log("acc"+ acc);
' return contract.methods.depositeMyBalance(amount).send({from: acc});
' }).then (function (tx)
' {
' console.log(tx);
' }).catch(function(tx)
' {
' console.log(tx);
' })
' })
' //Withdraw
' $('#withdraw').click(function()
' {
' var amount = 0;
' amount = parseInt($('#amount').val());
' console.log("amount"+amount);
'
' // web3.eth.getAccounts().then(e => console.log("---------------"+e));
' web3.eth.getAccounts().then(function(accounts)
' {
' var acc = accounts[0];
' console.log("acc"+ acc);
' return contract.methods.withdrawMyBalance(amount).send({from: acc});
' }).then (function (tx)
' {
' console.log(tx);
' }).catch(function(tx)
' {
' console.log(tx);
' })
' })
' </script>
'
'</body>
'
'</html>

This is our SOL files
pragma solidity ^0.4.24;

//Main class that will be used to perform operation on our block.
contract MyBank
{
//This is variable used for storing our balanceValue
int balanceValue;

//build constructor

constructor() public
{
//initialise the variable
balanceValue = 1;
}

//As getBalance is not manupulating the value it is used to show the data on the screen and use view returns(int)
function getBalanceValue() public view returns(int)
{
//return the current value of balanceValue
return balanceValue;
}


function withdrawMyBalance(int amount) public
{
balanceValue = balanceValue - amount;

}

function depositeMyBalance(int amount) public
{

balanceValue = balanceValue + amount;
}

}

Note :- For newer version when you try to get the Accounts details please check the MetaMask plugin of chorme. For safety reason you have been asked explicitly approve the access.

Image1


Image2

Image3

Tuesday, September 17, 2019

How to create blockchain using Ethereum code

To get better idea of Block chain requesting you to please refer to the below given few of the important concepts.
https://shdhumale.wordpress.com/2019/09/16/block-chain-concepts/
Ethereum is Platform to develope/code blockchain concept. You can consider it as a JAVA platform. Like in JAVA we have JVM-Java Virtual Machine same way we have EVM (not electronic voting machine :) ) - Ethereum virtual machine which provide plate form for our code to execute. In JAVA we use java as a base language. For Ethereum we use Solidity language [https://solidity.readthedocs.io/en/v0.5.3/]. For JAVA we have IDE like Eclipse for Solidity we had Solidity IDE.
One of the best use of Ehereum along with soidity language and IDE is that we can use the free available crypography to use and test our Block chain ontheir live test environment.
Before going to implementation and live coding example on Ehereum to create block chain few of you might think in perious thread in this blog it was stated we also have Hyper ledger which provide you frame work [i.e. Iroha, Sawtooth, Fabric, Undy, Burrow] and tool [i.e. Hyperledger composer, hyperledger cello, hyperledger quilt and hyperledger explorere] to develop blockchain. Let me try to give you some brief difference between Hyperledger and Ethereum with respect to its implementation strategy, Crytocurrency, its Confidentiality, use of Conseus algorithum and its development Language.



Features List Hyperledger Technolgoy Ethereum Technology
Purpose B2B B2C
Confidentiality Confidential  Transparent
Mode of Peer Participation Private and Permissioned Network Public/Private and Permissionless Network
Consensus Algo used and which one  Pluggable Consensus Algorithm and  No mining required PoW Algorithm is used and  Consensus is reached by mining where in minner do this process of mininig i.e. adding the block in chain
Programming Language  GolangSolidity
Cryptocurrency No cryptocurrency Ether cryptocurrency


Now below going directly to Ethereum for creating block chain I would like to explain you hash algotirum with simple two JAVA class as given below:-
package com.siddhu;
import java.util.Arrays;
public class MyBlock {

private int privousBlockHash;
private String[] transections;
private int currentBlockHash;


public MyBlock(int privousBlockHash, String[] transections) {
super();
this.privousBlockHash = privousBlockHash;
this.transections = transections;

//we will generate hash digital code taking into consideration its content and its previous block hashcode.
Object[] contents = {Arrays.hashCode(transections) , privousBlockHash};
this.currentBlockHash = Arrays.hashCode(contents);
}
/**
* @return the privousBlockHash
*/
public int getPrivousBlockHash() {
return privousBlockHash;
}
/**
* @param privousBlockHash the privousBlockHash to set
*/
public void setPrivousBlockHash(int privousBlockHash) {
this.privousBlockHash = privousBlockHash;
}
/**
* @return the transections
*/
public String[] getTransections() {
return transections;
}
/**
* @param transections the transections to set
*/
public void setTransections(String[] transections) {
this.transections = transections;
}
/**
* @return the currentBlockHash
*/
public int getCurrentBlockHash() {
return currentBlockHash;
}
/**
* @param currentBlockHash the currentBlockHash to set
*/
public void setCurrentBlockHash(int currentBlockHash) {
this.currentBlockHash = currentBlockHash;
}


}
/**
*
*/
package com.siddhu;
import java.util.ArrayList;
/**
* @author Siddhartha
* In this simple example we will try to learn what is hash and how it work and fit perfectly for concept like blockchain.
* To be more clear we will have following thing in the block i.e. hash= digital signature, list of transections and Previous block hash code.
*/
public class SimpleHashExample {

ArrayList<MyBlock> myBlockChain = new ArrayList<MyBlock>();

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//Lets create our first Block i.e. who will not have any previous blog hash and term as Genesis Block
String[] myGenesisTransections = {"Sid transfer 10RS to ABC"};

MyBlock myGenesisBlock = new MyBlock(0, myGenesisTransections) ;

System.out.println("Hash code for Genesis Block is:"+ myGenesisBlock.getCurrentBlockHash());

String[] mySecondBlockTransection = {"ABC transfer 5Rs to XYZ"};

MyBlock mySeondcBlock = new MyBlock(myGenesisBlock.getCurrentBlockHash(), mySecondBlockTransection) ;

System.out.println("Hash code for Second Block is:"+ mySeondcBlock.getCurrentBlockHash());
}
}
If you see above for given input the output is
Hash code for Genesis Block is:-1568564568
Hash code for Second Block is:-2100868299
Image1Image2
Now if you change any value in Genesis or any second node valye its hash value will be chaged and this is the base how the block chain make sure the data is secure and is not hamper. For this we use SHAH512 or SHAH64 and MD5,6 algorithum.
Now having understanding of the base hash method lets start having our own simple example of Ethereum.
Following things are needed to do the intial set up
1- Set up MetaMask extension in google chorme from below given url.MetaMask is used to connect you to Ethereum and the Decentralized Web.
https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn?hl=en
2- Please follow below screen shots sequentially
Image3Image4Image5Image6Image7Image8Image9
Once we had done with all the setup of MetaMask we will this screen

Image10Image11
On click on view on Ether scan you will get below online screen
Image12

Now let say if we create an example in Ethereum for deposite and withdraw operation on our created blockchain to do this we need some Ether as an cryptocurrency. But if you see we have 0$. To perform above example in test environment we will required few of Ether. So as usual lets try to collect the free ether for our test environment.
1- Change your Main environment to Test as shown below

Image13

2- Now click on Deposite button of below image.

Image14

3- click on Get Ether button as shown below
Image15
4- Following site will be open now click on the below give left side Crypto Faucet option

Image16
5- If you read the text in the below given screen it wil inform you if we want Ether then we need to share our address on social media like twitter, Facebook etc.
Image17
6- Lets share our address to facebook as shown belwo I am using Twitter
i.e. https://twitter.com/SiddharathaD/status/1173863404575973378
Image18
Now paste the above link on the belwo screen
Image19
Now choose the option you want I choose 18.75 ethers/3 days and click Give me Ethers.
Image20Image21
And you will Ether is added to your account

Image22
Hurrey now we had Free Ether to use for our BlockChain concepts.
Now lets start to create our first Ethereum block or better to say our first Smart Contract. For this we need a IDE which use Ehthereum platform. For this we can use below site. This will provide
https://remix.ethereum.org/
Image23
Now please Activate all the required module as given below
- Compile
- Run
- Analysis
- Testing
- Debugger
- Search

Image24Image25
Now lets set the comipler we will use the old one for simpler side :)

Image26Image27
Here is the complete tocode

pragma solidity ^0.4.24;

//Main class that will be used to perform operation on our block.
contract MyBank
{
//This is variable used for storing our balanceValue
int balanceValue;

//build constructor

constructor() public
{
//initialise the variable
balanceValue = 1;
}

//As getBalance is not manupulating the value it is used to show the data on the screen and use view returns(int)
function getBalanceValue() public view returns(int)
{
//return the current value of balanceValue
return balanceValue;
}


function withdrawMyBalance(int amount) public
{
balanceValue = balanceValue - amount;

}

function depositeMyBalance(int amount) public
{

balanceValue = balanceValue + amount;
}

}
Image28
Now as we can see we dont have any compiler error we can run our first Smart Contract to do this click on this option

Image29
One belwo screen you will get three different option
Image30
JavaScript
Injected
Web3 Provided
JavaScript :- This will use your or client JAVA JRE and run java script on the same and will perform the operations.
We will also select our MyBank.sol file that need to be executed.
Now click on the Deploy button and you will find we get Deployed contract seen on the screen as shown below.

Image31
Lets play with this option and see how is working
A :- Click on getBalanceValue and we will see we get value as 1 which is initial values.
Image32

B:- Now lets add 20 by using rransact button
Image33
and now click on the getBalanceValue button and we will the value change to 21
Image34
c:- Same way execute the withdraw method and check if it working

Image35Image36
Now this testing of our Smart contract is done on solidity language IDE lets say we want to do it on our Browser
For this we need to choose Injected Web3 option and once we do it will ask your permission to connect. click on the connect button

Image37
Now click on deploy to deploy our MyBank.SOL on test network. It will again ask for confiration .. do it by clicking confirm button below.
Image38
See the url on which our MyBank.SOL get deployed click on it and then you will see the below screen
Image39Image40
Initial status will be pending as it will take some time for POW and then once it is sucecess we are good to do the transection.
Let see it
Now perform all your GetBalance and Deposite and withdraw operation and you will see the now for Withdraw and deposite it will ask for some GAS from you just confirm it and we are done.


Image41Image42

Monday, September 16, 2019

Block Chain concepts

1- Simple Blockchain with DATA+HASH+Previous Hash
Insimple work blockchain in a colloection of blocks containing data in form of Ladger arranged in a sequential manner with following attributes
1- Immutable :- Cannot be changed
2- Sequence is maintained by storing its own and previous block unique address. Hence the first block which did not have any previous block is termed as Genesis block i.e. PreviouBlock address=0;
3- In shot it can be terms as a system in which a record of transactions made in cryptocurrency are maintained across several computers that are linked in a peer-to-peer network.
2- CINA concept in internet.
Confidentiality: This can be expalined by taking simple word
Let say User A want to send message to User B using internet how we can make sure Message is not been read by User C on net. This is what confidentiality stand for. We need to make sure only User A and User B are the right candidate for reading this messages.
Integrity:-
Let say User A send message to User B how we can make sure the message is not been tempered in between. i.e. if User A send message "Hello USer B" to Uesr B then how we can make sure no thrid party User C had modified it to "Hello User B1".
Non repuditions:-
Let say User A send Message to User B and how we will make sure that the user A has only send this messsage and he will not be able to neglect his ownership on the same.
Authentication:-
During exchange between the messsage from User A and User B how we can make sure that message is properly authenticate from both parties.
3- Cryptography :- Symmentric and Asymmentric Solutions
Cryptography = Crypto means secret/hidden and graphy means To handle Confidentiality in the above network aspect we have Symmentric and Asymmentric crytography
Symmentric Key Crytography :-
User A --> Encrypt the message using his User A key --------------------------> USer B on receiving the message decrypt them using Using User A key.
Above scenario work perfectly right but assume if we had huge messsage to send different other user we have to maintain huge key.
Asymmentric Key Cryptography :- In this we have two key (1) Public Key = email id and (2) Private Key = password.
User A --> encrypt the message using his public key and send message to User B ----------------> User B decrypt the message using his Private key.
This issues solved our confidentiality concern on Network. But what about our other concern like Integrity, Non Repuditions and Authentications for that we will use below Asymmentric key cryptography.
User A encrypt the message using his Private Key + user B Public key and send message -----------------> User B decrypt the message first using his private key and then using User A public key.
4- BitCoin Example one complete flow
You might be thinking why BitCoin name is so much famous whenever we talk about BlockChain ... reason behind Bitcoin was the first to implement BlockChain in public mode for cryptography. Lets try to firs understand how they did it
Let say User A want to send money to the User B
User A --> Create a ledger i.e. Transection notes it may contains data like FROM:UserA , TO:UserB, Amount=10 Rs. etc ... information. This ledger is then encrypted using HASH algorithum (We will disscuss about different algorithm later HASH, MD etc). Then using Asymentric Key cryptography i.e. encrypt using privae key of sender + public key transection is send to the User B where in User B will decrypt the same using public key of Sender User A and his own private key. This way one complete transection is done.
In this case the process of claiming the do the work that involve solving of some mathematical problem so that we can be entitiled to encrypting the ledger using hash code and creating a block is called POW [Proof of work]. Person who do this is called Minner and process of adding the Block into the chain is called minning. FYI currently Bitcoin pay 12.5 point for this.
5- Nodes and its types.
Now lets go in details of Node for Block chain Cryptography. There are two main type of Nodes
1- Full Nodes :- On this full nodes your whole block chanin exist i.e. today bitcoin 130 GB and on this node we maitain and service new and old block. To do this we need huge CPU and GPU.
2- Partial Nodes :- such node i.e. even our mobiule we only use to do some transections.
6- Algorithem MD5 and SHA 512 
We talk above about the crytography hash algorithm. Important point to note HASH algorithm suggest what ever and how much data you give as input it will produce unique byte of string as an out put. To be more clear let say we use SHS512 algorithum as an input if we give all the character of encylopidea or simple string like "My name is siddharatha dhumale" as an output it will give simple string of 512 character. for SHAH64 algo we get string of 64 character. Additional we are sure that slight change in the data will definately change hash value. Further adding this hash code will be unique their is very very less chance that it may be same as other... In real scenario this is called hash collosion and we had another way to handle it. Will keep this part away from discussion as of now.
7- Markel Tree concept.
Now when we talk about the hash code it is good time to talk about the Market tree. Let say in one ledger we had 10 trasection do we need to have 10 hashcode or we can have single hash code for all this transection
h12345678
h1234 h5678
h12 h34 h56
h1 h2 h3 h4 h5 h6... h10
As shown in above structure we can store the final single hash code h12345678 as signed value. This process of getting unique hash code from multiple hash code is called Markel tree.
8- Disection of One single Block :- Timestamp, Version, Market Tree Root, POW [Difficulty Target, Nonce] and Previous Hash
Now lets go in details of what a single Bock contain. Basically it contains follwoing 5 items
1- Timestamp on which it is created.
2- Version
3- Markel Hash code
4- Two values from POW i.e. Difficulty Target and Nouce
5- Previous hash code.
9- Security i.e. 10 min example to add and update block
Biggest quesiton is how we can say that block are secure it may be possible that admin can change the data of the block ...agreed with you but issue will be as soon as any one change the data inside the blog its hash code will change ... rememeber one block hash code is also stored in second consecutive block as a PREVIOUS BLOCK hash code. so once original has code change then its consecutive chain get break. To make this valid user also need to reiterate all the consecutive cascade block and again recalculate their new has code as per this new values to main the chain again.
Now someone will say what's wrong in this process with the help of new super computer we can do this .. I agree with you but in BITCOIN to update or add new block in the chain it consume 10 min and huge POW. So consider if even though we have 10 blocks chain it will take approximately 100 min to change and in mean while new block will be added to the end ..and hence this will make such process next to impossible to do.

10- Consesus Algorithm
One of the important of Block chain in use of Consesus algotirhm. Let me give you in details what this means. Let say we have team of 5 people. Any decision which need to be taken will have to be approved by all 5 team member. Even if the single team memeber resist on the same the chain break. This is called taking consesus before acting. Remember ACID properties in EJB same is this :).
11- Type of Block Chain
There are three type of block chain
1- Public :- This type of block chain are public in nature means its data can be seen by all other and only few has write to modify it i.e. bitcoin.
2- Private :-This type of block chain are private in nature means its data can be seen by agreed and authenticated user only and only few among them has write to modify it. i.e. Banking Blockchain or corporate block chain etc.
3- Hybride :- This is amalgamation on both Public and Private block chain. Few of the block are private in nature and rest are public in nature.
Remember Public block are huge in size and as it is huge it will be difficult for any one to modify it.

12- HyperLedger
We had done enough of Bitcoin discussion till now. In current market you will be listening to new terms as HyperLedger.
Does hyperledge is new ledger, is it block chain, is it new type of block chain answe is NO
In simple word it open source collobrative effort to provide users with frame work and tool/ide to develop new blockchain. It is the owner ship of linux world.
13- Smart Contract
Simple word to define is the contract which is executed by the code which is written by us between the two party is called smart contract. I know you did understand what i means to say :) let me take example
Let say User A want to use a site ABC.com to get some item having many discount... concern here is we try to avoid using this ABC site due to its authentication issues might be possible it happen that ABC hier another company XYZ to send the product to my house. XYX give product to ABC but ABC did not send the product to me..how i can handle such scenario at run time. To do this i will have smart contract .i.e. if ABC deliver product to me then i will pay amount to XYZ. In this case i will be sure that at any given movement of time if the product did not reach my contract did not executed.
14- Etherium
Purpose is to have Platform for B2C businesses and generalized  applications and Confidentiality as Transparent and Mode of Peer Participation as Public/Private and Permissionless Network along with Consensus Mechanism as PoW Algorithm: Consensus is reached by mining and Programming Language asSmart Contracts written in Solidity and Cryptocurrency Built-in cryptocurrency called Ether
15- Disadvantage- CSR
- It is complex to understand
- It required huge resource to deal with CPU and GPU and mathemaical process to solve.
- It has 51% issues i.e. if a block chain has 51% false owner then it is wrong block chain.

Friday, September 13, 2019

Spring Boot Admin Server and Client

Create a spring boot application and following dependencise in pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Add following @EnableAdminServer in our main Server class
@SpringBootApplication
@EnableAdminServer
public class SiddhuSpringBootAdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(SiddhuSpringBootAdminServerApplication.class, args);
}
}
Add following lines in your admin configuration properties
server.port = 9090
spring.application.name = adminserver
Compile the server and run the application
java -jar C:\Latest_workspace-sts-3.9.6.RELEASE\siddhu-spring-boot-admin-server\target\siddhu-spring-boot-admin-server-0.0.1-SNAPSHOT.jar

Image1Image2Image3Image4
And hit url
http://localhost:9090/#/
Image5
Now lets create the spring boot application admin client. Create an spring boot application and following dependencise in pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
@SpringBootApplication
public class SiddhuSpringBootAdminClientApplication {
public static void main(String[] args) {
SpringApplication.run(SiddhuSpringBootAdminClientApplication.class, args);
}
}
Add following lines in your admin configuration properties
spring.boot.admin.url=http://localhost:9090/
Image6Image7Image8Image9

java -Dserver.port=8888 -jar C:\Latest_workspace-sts-3.9.6.RELEASE\siddhu-spring-boot-admin-client\target\siddhu-spring-boot-admin-client-0.0.1-SNAPSHOT.jar
Compile the server and run the application and hit url
http://localhost:9090/#/
Image10