Adding source code for the article tracked under BAEL-3232. (#7657)

This commit is contained in:
Kumar Chandrakant 2019-08-28 10:25:04 +05:30 committed by Grzegorz Piwowarek
parent 0216c364b0
commit 9d825c429e
8 changed files with 232 additions and 0 deletions

26
java-blockchain/.gitignore vendored Normal file
View File

@ -0,0 +1,26 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

View File

@ -0,0 +1,6 @@
=========
## Basic Implementation of Blockchian in Java
### Relevant Articles:
- []()

40
java-blockchain/pom.xml Normal file
View File

@ -0,0 +1,40 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.blockchain</groupId>
<artifactId>java-blockchain</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-blockchain</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<build>
<finalName>java-blockchain</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,65 @@
package com.baeldung.blockchain;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Block {
private static Logger logger = Logger.getLogger(Block.class.getName());
private String hash;
private String previousHash;
private String data;
private long timeStamp;
private int nonce;
public Block(String data, String previousHash) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateBlockHash();
}
public String mineBlock(int prefix) {
String prefixString = new String(new char[prefix]).replace('\0', '0');
while (!hash.substring(0, prefix)
.equals(prefixString)) {
nonce++;
hash = calculateBlockHash();
}
return hash;
}
public String calculateBlockHash() {
String dataToHash = previousHash + Long.toString(timeStamp) + Integer.toString(nonce) + data;
MessageDigest digest = null;
byte[] bytes = null;
try {
digest = MessageDigest.getInstance("SHA-256");
bytes = digest.digest(dataToHash.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
logger.log(Level.SEVERE, ex.getMessage());
}
StringBuffer buffer = new StringBuffer();
for (byte b : bytes) {
buffer.append(String.format("%02x", b));
}
return buffer.toString();
}
public String getHash() {
return this.hash;
}
public String getPreviousHash() {
return this.previousHash;
}
public void setData(String data) {
this.data = data;
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,67 @@
package com.baeldung.blockchain;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class BlockchainUnitTest {
public static List<Block> blockchain = new ArrayList<Block>();
public static int prefix = 4;
public static String prefixString = new String(new char[prefix]).replace('\0', '0');
@BeforeClass
public static void setUp() {
Block genesisBlock = new Block("The is the Genesis Block.", "0");
genesisBlock.mineBlock(prefix);
blockchain.add(genesisBlock);
Block firstBlock = new Block("The is the First Block.", genesisBlock.getHash());
firstBlock.mineBlock(prefix);
blockchain.add(firstBlock);
}
@Test
public void givenBlockchain_whenNewBlockAdded_thenSuccess() {
Block newBlock = new Block("The is a New Block.", blockchain.get(blockchain.size() - 1)
.getHash());
newBlock.mineBlock(prefix);
assertTrue(newBlock.getHash()
.substring(0, prefix)
.equals(prefixString));
blockchain.add(newBlock);
}
@Test
public void givenBlockchain_whenValidated_thenSuccess() {
boolean flag = true;
for (int i = 0; i < blockchain.size(); i++) {
String previousHash = i == 0 ? "0"
: blockchain.get(i - 1)
.getHash();
flag = blockchain.get(i)
.getHash()
.equals(blockchain.get(i)
.calculateBlockHash())
&& previousHash.equals(blockchain.get(i)
.getPreviousHash())
&& blockchain.get(i)
.getHash()
.substring(0, prefix)
.equals(prefixString);
if (!flag)
break;
}
assertTrue(flag);
}
@AfterClass
public static void tearDown() {
blockchain.clear();
}
}

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -566,6 +566,7 @@
<module>oauth2-framework-impl</module>
<module>spring-boot-nashorn</module>
<module>java-blockchain</module>
</modules>
</profile>
@ -802,6 +803,7 @@
<module>spring-security-kerberos</module>
<module>spring-boot-nashorn</module>
<module>java-blockchain</module>
</modules>