OneCompiler

1 rd program

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class Block {
private int index;
private long timestamp;
private String previousHash;
private String hash;
private String data;
private int nonce;

// Constructor
public Block(int index, String previousHash, String data) {
    this.index = index;
    this.timestamp = new Date().getTime();
    this.previousHash = previousHash;
    this.data = data;
    this.nonce = 0;
    this.hash = calculateHash();
}

// Hash calculation
public String calculateHash() {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        String input = index + timestamp + previousHash + data + nonce;
        byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));
        
        StringBuilder hexString = new StringBuilder();
        for (byte hashByte : hashBytes) {
            String hex = Integer.toHexString(0xff & hashByte);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}

// Mining function
public void mineBlock(int difficulty) {
    String target = new String(new char[difficulty]).replace('\0', '0');
    while (!hash.startsWith(target)) {  // Fixes IndexOutOfBoundsException risk
        nonce++;
        hash = calculateHash();
    }
    System.out.println("Block mined: " + hash);
}

// Getters
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[]) throws Exception {
    Block b = new Block(1, "3a42c503953909637f78dd8c99b3b85ddde362415585afc11901bdefe8349102", "hai");
    b.mineBlock(1);
    
    // Printing results
    System.out.println("Index: " + b.getIndex());
    System.out.println("Timestamp: " + b.getTimestamp());
    System.out.println("Previous Hash: " + b.getPreviousHash());
    System.out.println("Current Hash: " + b.getHash());
    System.out.println("Data: " + b.getData());
}

}