ET-IV LAB 2024-25 1
EXPRIMENT NUMBER-4
AIM: Create a Block of Blockchain using Java Language.
Objective:
Blocks are files stored by a blockchain, where transaction data are permanently recorded.
A block records some or all of the most recent transactions not yet validated by the network.
Once the data are validated, the block is closed.
Then, a new block is created for new transactions to be entered into and validated.
Requirements:
Any Text Editor
Jdk Updated Version
Theory:
Blocks are data structures within the blockchain database, where transaction data in a
crypto currency blockchain are permanently recorded. A block records some or all of the most
recent transactions not yet validated by the network. Once the data are validated, the block is
closed. Then, a new block is created for new transactions to be entered into and validated.
Blocks are created when miners or block validators successfully validate the encrypted information
in the blockheader, which prompts the creation of a new block.
SOURCE CODE:
import [Link];
import [Link]; import [Link];
public class Block {
private int index;
private long timestamp;
private String previousHash;
private String hash;
private String data;
private int nonce;
public Block(int index, String previousHash, String data) {
[Link] = index;
JCOET, YAVATMAL
ET-IV LAB 2024-25 2
[Link] = new Date().getTime();
[Link] = previousHash;
[Link] = data;
[Link] = 0;
[Link] = calculateHash();
}
public String calculateHash() {
try {
MessageDigest digest = [Link]("SHA-256");
String input = index + timestamp + previousHash + data + nonce;
byte[] hashBytes = [Link]([Link]());
StringBuilder hexString = new StringBuilder();
for (byte hashByte : hashBytes) {
String hex = [Link](0xff &hashByte);
if ([Link]() == 1) {
[Link]('0');
}
[Link](hex);
}
return [Link]();
}
catch (NoSuchAlgorithmException e) {
[Link]();
}
return null;
}
public void mineBlock(int difficulty) {
String target = new String(new char[difficulty]).replace('\0', '0');
while (.equals(target)) {
nonce++;
hash = calculateHash();
JCOET, YAVATMAL
ET-IV LAB 2024-25 3
}
[Link]("Block mined: " + hash);
}
public int getIndex() {
return index;
}
public long getTimestamp() {
return timestamp;
}
public String getPreviousHash() {
return previousHash;
}
public String getHash() {
return hash;
}
public String getData() {
return data;
}
public static void main(String args[]){
Block b=new
Block(1,"3a42c503953909637f78dd8c99b3b85ddde362415585afc11901bdefe8349102","jcoet");
[Link]();
[Link](1);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}}
JCOET, YAVATMAL