Skip to content

Instantly share code, notes, and snippets.

@ogajduse ogajduse/Block.java
Created Feb 13, 2019

Embed
What would you like to do?
Use gson-2.6.2 JAR
package cz.vutbr.feec.utko.mkri.blockchain;
import java.util.Random;
import cz.vutbr.feec.utko.mkri.blockchain.StringUtil;
public class Block {
public String hash; // digitální otisk bloku (hash)
public String previousHash; // hash předchozího bloku
String data; // data bloku (ve formě krátke zprávy)
private long time; // časové razítko
private int nonce;
public Block(String data,String previousHash ) {
this.data = data;
this.previousHash = previousHash;
this.time = new java.util.Date().getTime();
this.nonce = new Random().nextInt();
this.hash = calculateHash();
}
public String calculateHash() {
StringBuilder builder = new StringBuilder();
builder.append(this.data);
builder.append(this.previousHash);
builder.append(this.time);
builder.append(this.nonce);
return StringUtil.applySha256(builder.toString());
}
public void mineBlock(int difficulty) {
//Vytvori string s obtiznosti * "0"
String target = new String(new char[difficulty]).replace('\0', '0');
while(!this.hash.substring( 0, difficulty).equals(target)) {
this.nonce++;
this.hash = calculateHash();
}
System.out.println("Block vytezen!!! : " + hash);
}
}
package cz.vutbr.feec.utko.mkri.blockchain;
import java.util.ArrayList;
import java.util.Random;
import com.google.gson.GsonBuilder;
public class Blockchain {
public static ArrayList<Block> blockchain = new ArrayList<Block>();
public static int difficulty = 3;
public static String[] data = { "Ahoj, ja jsem prvni blok", "Ja jsem druhy.", "A ja treti" };
public static void main(String[] args) {
Block currentBlock = null;
for (int i = 0; i < data.length; i++) {
currentBlock = new Block(data[i], currentBlock == null ? "0" : currentBlock.hash);
blockchain.add(currentBlock);
System.out.println("Hash pro blok " + i + ": " + currentBlock.hash);
currentBlock.mineBlock(difficulty);
}
//blockchain.get(2).data = "hacker";
System.out.println("Is blockchain valid: " + isChainValid());
String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
System.out.println(blockchainJson);
}
public static Boolean isChainValid() {
Block currentBlock;
Block previousBlock;
String hashTarget = new String(new char[difficulty]).replace('\0', '0');
// projde cely blockchain a zkontroluje hashe
for (int i = 1; i < blockchain.size(); i++) {
currentBlock = blockchain.get(i);
previousBlock = blockchain.get(i - 1);
// porovna ulozeny hash a vypocitany hash
if (!currentBlock.hash.equals(currentBlock.calculateHash())) {
System.out.println("Hash tohoto bloku je odlisny");
return false;
}
// porovna predchozi hash se skutecnym predchozim hashem
if (!previousBlock.hash.equals(currentBlock.previousHash)) {
System.out.println("Hash predchoziho bloku je odlisny");
return false;
}
// zjisti zda byl vytvoren spravny hash
if (!currentBlock.hash.substring(0, difficulty).equals(hashTarget)) {
System.out.println("Tento blok nebyl vytezen");
return false;
}
}
return true;
}
}
package cz.vutbr.feec.utko.mkri.blockchain;
import java.security.MessageDigest;
public class StringUtil {
public static String applySha256(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// Aplikuje Sha256 na vstupní hodnotu
byte[] hash = digest.digest(input.getBytes("UTF-8"));
// Bude obsahovat hash jako hex číslo
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.