|
| 1 | +package com.baeldung.blockchain; |
| 2 | + |
| 3 | +import java.io.UnsupportedEncodingException; |
| 4 | +import java.security.MessageDigest; |
| 5 | +import java.security.NoSuchAlgorithmException; |
| 6 | +import java.util.Date; |
| 7 | +import java.util.logging.Level; |
| 8 | +import java.util.logging.Logger; |
| 9 | + |
| 10 | +public class Block { |
| 11 | + |
| 12 | + private static Logger logger = Logger.getLogger(Block.class.getName()); |
| 13 | + |
| 14 | + private String hash; |
| 15 | + private String previousHash; |
| 16 | + private String data; |
| 17 | + private long timeStamp; |
| 18 | + private int nonce; |
| 19 | + |
| 20 | + public Block(String data, String previousHash) { |
| 21 | + this.data = data; |
| 22 | + this.previousHash = previousHash; |
| 23 | + this.timeStamp = new Date().getTime(); |
| 24 | + this.hash = calculateBlockHash(); |
| 25 | + } |
| 26 | + |
| 27 | + public String mineBlock(int prefix) { |
| 28 | + String prefixString = new String(new char[prefix]).replace('\0', '0'); |
| 29 | + while (!hash.substring(0, prefix) |
| 30 | + .equals(prefixString)) { |
| 31 | + nonce++; |
| 32 | + hash = calculateBlockHash(); |
| 33 | + } |
| 34 | + return hash; |
| 35 | + } |
| 36 | + |
| 37 | + public String calculateBlockHash() { |
| 38 | + String dataToHash = previousHash + Long.toString(timeStamp) + Integer.toString(nonce) + data; |
| 39 | + MessageDigest digest = null; |
| 40 | + byte[] bytes = null; |
| 41 | + try { |
| 42 | + digest = MessageDigest.getInstance("SHA-256"); |
| 43 | + bytes = digest.digest(dataToHash.getBytes("UTF-8")); |
| 44 | + } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { |
| 45 | + logger.log(Level.SEVERE, ex.getMessage()); |
| 46 | + } |
| 47 | + StringBuffer buffer = new StringBuffer(); |
| 48 | + for (byte b : bytes) { |
| 49 | + buffer.append(String.format("%02x", b)); |
| 50 | + } |
| 51 | + return buffer.toString(); |
| 52 | + } |
| 53 | + |
| 54 | + public String getHash() { |
| 55 | + return this.hash; |
| 56 | + } |
| 57 | + |
| 58 | + public String getPreviousHash() { |
| 59 | + return this.previousHash; |
| 60 | + } |
| 61 | + |
| 62 | + public void setData(String data) { |
| 63 | + this.data = data; |
| 64 | + } |
| 65 | +} |
0 commit comments