Skip to content

Commit 9d825c4

Browse files
kcacademicpivovarit
authored andcommitted
Adding source code for the article tracked under BAEL-3232. (eugenp#7657)
1 parent 0216c36 commit 9d825c4

8 files changed

Lines changed: 232 additions & 0 deletions

File tree

java-blockchain/.gitignore

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
*.class
2+
3+
0.*
4+
5+
#folders#
6+
/target
7+
/neoDb*
8+
/data
9+
/src/main/webapp/WEB-INF/classes
10+
*/META-INF/*
11+
.resourceCache
12+
13+
# Packaged files #
14+
*.jar
15+
*.war
16+
*.ear
17+
18+
# Files generated by integration tests
19+
*.txt
20+
backup-pom.xml
21+
/bin/
22+
/temp
23+
24+
#IntelliJ specific
25+
.idea/
26+
*.iml

java-blockchain/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
=========
2+
3+
## Basic Implementation of Blockchian in Java
4+
5+
### Relevant Articles:
6+
- []()

java-blockchain/pom.xml

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
<groupId>com.baeldung.blockchain</groupId>
6+
<artifactId>java-blockchain</artifactId>
7+
<version>0.1.0-SNAPSHOT</version>
8+
<name>java-blockchain</name>
9+
<packaging>jar</packaging>
10+
<parent>
11+
<groupId>com.baeldung</groupId>
12+
<artifactId>parent-java</artifactId>
13+
<version>0.0.1-SNAPSHOT</version>
14+
<relativePath>../parent-java</relativePath>
15+
</parent>
16+
<build>
17+
<finalName>java-blockchain</finalName>
18+
<resources>
19+
<resource>
20+
<directory>src/main/resources</directory>
21+
<filtering>true</filtering>
22+
</resource>
23+
</resources>
24+
<plugins>
25+
<plugin>
26+
<groupId>org.apache.maven.plugins</groupId>
27+
<artifactId>maven-compiler-plugin</artifactId>
28+
<version>${maven-compiler-plugin.version}</version>
29+
<configuration>
30+
<source>${maven.compiler.source}</source>
31+
<target>${maven.compiler.target}</target>
32+
</configuration>
33+
</plugin>
34+
</plugins>
35+
</build>
36+
<properties>
37+
<maven.compiler.source>1.8</maven.compiler.source>
38+
<maven.compiler.target>1.8</maven.compiler.target>
39+
</properties>
40+
</project>
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<configuration>
3+
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
4+
<encoder>
5+
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
6+
</pattern>
7+
</encoder>
8+
</appender>
9+
10+
<root level="INFO">
11+
<appender-ref ref="STDOUT" />
12+
</root>
13+
</configuration>
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.baeldung.blockchain;
2+
3+
import static org.junit.jupiter.api.Assertions.assertTrue;
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
import org.junit.AfterClass;
9+
import org.junit.BeforeClass;
10+
import org.junit.Test;
11+
12+
public class BlockchainUnitTest {
13+
14+
public static List<Block> blockchain = new ArrayList<Block>();
15+
public static int prefix = 4;
16+
public static String prefixString = new String(new char[prefix]).replace('\0', '0');
17+
18+
@BeforeClass
19+
public static void setUp() {
20+
Block genesisBlock = new Block("The is the Genesis Block.", "0");
21+
genesisBlock.mineBlock(prefix);
22+
blockchain.add(genesisBlock);
23+
Block firstBlock = new Block("The is the First Block.", genesisBlock.getHash());
24+
firstBlock.mineBlock(prefix);
25+
blockchain.add(firstBlock);
26+
}
27+
28+
@Test
29+
public void givenBlockchain_whenNewBlockAdded_thenSuccess() {
30+
Block newBlock = new Block("The is a New Block.", blockchain.get(blockchain.size() - 1)
31+
.getHash());
32+
newBlock.mineBlock(prefix);
33+
assertTrue(newBlock.getHash()
34+
.substring(0, prefix)
35+
.equals(prefixString));
36+
blockchain.add(newBlock);
37+
}
38+
39+
@Test
40+
public void givenBlockchain_whenValidated_thenSuccess() {
41+
boolean flag = true;
42+
for (int i = 0; i < blockchain.size(); i++) {
43+
String previousHash = i == 0 ? "0"
44+
: blockchain.get(i - 1)
45+
.getHash();
46+
flag = blockchain.get(i)
47+
.getHash()
48+
.equals(blockchain.get(i)
49+
.calculateBlockHash())
50+
&& previousHash.equals(blockchain.get(i)
51+
.getPreviousHash())
52+
&& blockchain.get(i)
53+
.getHash()
54+
.substring(0, prefix)
55+
.equals(prefixString);
56+
if (!flag)
57+
break;
58+
}
59+
assertTrue(flag);
60+
}
61+
62+
@AfterClass
63+
public static void tearDown() {
64+
blockchain.clear();
65+
}
66+
67+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
*.class
2+
3+
#folders#
4+
/target
5+
/neoDb*
6+
/data
7+
/src/main/webapp/WEB-INF/classes
8+
*/META-INF/*
9+
10+
# Packaged files #
11+
*.jar
12+
*.war
13+
*.ear

pom.xml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,7 @@
566566
<module>oauth2-framework-impl</module>
567567

568568
<module>spring-boot-nashorn</module>
569+
<module>java-blockchain</module>
569570
</modules>
570571

571572
</profile>
@@ -802,6 +803,7 @@
802803
<module>spring-security-kerberos</module>
803804

804805
<module>spring-boot-nashorn</module>
806+
<module>java-blockchain</module>
805807

806808
</modules>
807809

0 commit comments

Comments
 (0)