Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,8 @@

<!-- For cryptocurrencies tests and tutorials -->
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
<!-- <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId>
<version>2.8.8</version> </dependency> -->
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15to18 -->
<dependency>
<groupId>org.bouncycastle</groupId>
Expand Down
42 changes: 33 additions & 9 deletions src/main/java/gabywald/crypto/blockchain/Block.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@
import java.util.List;
import java.util.Map;

import gabywald.global.json.JSONException;
import gabywald.global.json.JSONValue;
import gabywald.global.json.JSONifiable;

/**
* Block of BlockChain.
* <br/><a href="https://medium.com/programmers-blockchain/create-simple-blockchain-java-tutorial-from-scratch-6eeed3cb03fa">https://medium.com/programmers-blockchain/create-simple-blockchain-java-tutorial-from-scratch-6eeed3cb03fa</a>
* <br/><a href="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/CryptoKass/NoobChain-Tutorial-Part-1">https://github.com/CryptoKass/NoobChain-Tutorial-Part-1</a>
* @author Gabriel Chandesris (2021)
*/
public class Block {
public class Block extends JSONifiable {

private String hash;
private String previousHash;
Expand Down Expand Up @@ -52,19 +56,12 @@ public Block(String previousHash ) {
* @see StringUtils#applySha256(String)
*/
public String calculateHash() {
String calculatedhash = null;
try {
calculatedhash = StringUtils.applySha256(
String calculatedhash = StringUtils.applySha256(
previousHash +
Long.toString(timeStamp) +
Integer.toString(nonce) +
merkleRoot
);
} catch (BlockchainException e) {
// e.printStackTrace();
System.out.println( e.getMessage() );
calculatedhash = null;
}
return calculatedhash;
}

Expand Down Expand Up @@ -120,4 +117,31 @@ public List<Transaction> getTransactions()
{ return this.transactions; }


@Override
protected void setKeyValues() {
this.put("hash", JSONValue.instanciate( this.hash.toString() ) );
this.put("previousHash", JSONValue.instanciate( this.previousHash.toString() ) );
this.put("timeStamp", JSONValue.instanciate( this.timeStamp ) );
this.put("nonce", JSONValue.instanciate( this.nonce ) );
this.put("transactions", JSONifiable.generateArray( this.transactions ) );
}

@Override
protected <T extends JSONifiable> T reloadFrom(String json)
throws JSONException {
return null;
}

@Override
public String toString() {
StringBuilder sbToReturn = new StringBuilder();
sbToReturn.append("hash").append(": ").append( this.hash.toString() ).append("\n");
sbToReturn.append("previousHash").append(": ").append( this.previousHash.toString() ).append("\n");
sbToReturn.append("timeStamp").append(": ").append( this.timeStamp ).append("\n");
sbToReturn.append("transactions").append(": \n");
for (Transaction transaction : this.transactions) {
sbToReturn.append("\t transaction").append(": ").append( transaction.toString() ).append("\n");
}
return sbToReturn.toString();
}
}
3 changes: 2 additions & 1 deletion src/main/java/gabywald/crypto/blockchain/BlockChain.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*
* @author Gabriel Chandesris (2021)
*/
public abstract class BlockChain {
public class BlockChain {

/**
* Build a list of Blocks.
Expand Down Expand Up @@ -141,4 +141,5 @@ public static boolean addBlock(final List<Block> blockchain, final Block newBloc
newBlock.mineBlock(difficulty);
return blockchain.add(newBlock);
}

}
23 changes: 15 additions & 8 deletions src/main/java/gabywald/crypto/blockchain/NoobChainTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import com.google.gson.GsonBuilder;
// import com.google.gson.GsonBuilder;

import gabywald.global.json.JSONifiable;

/**
* Tests about BlockChain / NoobChain.
Expand Down Expand Up @@ -48,9 +50,13 @@ void testPart02() {
blockchain.add(new Block("Yo im the second block", blockchain.get(blockchain.size()-1).getHash() ));
blockchain.add(new Block("Hey im the third block", blockchain.get(blockchain.size()-1).getHash() ));
Assertions.assertEquals(3, blockchain.size());
String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
Assertions.assertNotNull( blockchainJson );

String blockchainJson = JSONifiable.generateArray( blockchain ).toString();
// String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
System.out.println("\nThe block chain: ");
System.out.println(blockchainJson);

// for (Block block : blockchain) { System.out.println( block ); }
}

@Test
Expand All @@ -76,12 +82,12 @@ void testPart03() {

Assertions.assertTrue( BlockChain.isChainValidV1( blockchain ) );

String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);

Assertions.assertNotNull( blockchainJson );

String blockchainJson = JSONifiable.generateArray( blockchain ).toString();
// String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
System.out.println("\nThe block chain: ");
System.out.println(blockchainJson);

// for (Block block : blockchain) { System.out.println( block ); }
}

@Test
Expand Down Expand Up @@ -188,8 +194,9 @@ void testPart05() {

Block block3 = new Block(block2.getHash() );
System.out.println("\nWalletB is Attempting to send funds (20) to WalletA...");
boolean bBlock3AddTransactionResult = block3.addTransaction( walletB.sendFunds( walletA.getPublicKey(), 20, mapUTXOs),
boolean bBlock3AddTransactionResult = block3.addTransaction( walletB.sendFunds( walletA.getPublicKey(), 20f, mapUTXOs),
mapUTXOs, minimumTransaction);

Assertions.assertTrue( bBlock3AddTransactionResult );
System.out.println("\nWalletA's balance is: " + walletA.getBalance( mapUTXOs ));
System.out.println("WalletB's balance is: " + walletB.getBalance( mapUTXOs ));
Expand Down
18 changes: 7 additions & 11 deletions src/main/java/gabywald/crypto/blockchain/StringUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,10 @@ public abstract class StringUtils {
* Applies Sha256 to a string and returns the result.
* @param input
* @return (String)
* @throws BlockchainException
* TODO upgrade / improve this method (applySha256) to return null value if any exception inside !
*/
public static String applySha256(String input)
throws BlockchainException {
public static String applySha256(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// Applies sha256 to our input,
byte[] hash = digest.digest(input.getBytes("UTF-8"));
// This will contain hash as hexidecimal
Expand All @@ -49,7 +46,8 @@ public static String applySha256(String input)
return hexString.toString();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
System.out.println( "StringUtils: " + e.getClass().getName() + ": " + e.getMessage() );
throw new BlockchainException("StringUtils: " + e.getClass().getName() +": " + e.getMessage());
// throw new BlockchainException("StringUtils: " + e.getClass().getName() +": " + e.getMessage());
return null;
}
}

Expand Down Expand Up @@ -140,11 +138,9 @@ public static String getMerkleRoot(List<Transaction> transactions) {
while (count > 1) {
treeLayer = new ArrayList<String>();
for (int i = 1 ; i < previousTreeLayer.size() ; i++) {
try {
treeLayer.add(StringUtils.applySha256(previousTreeLayer.get(i-1) + previousTreeLayer.get(i)));
} catch (BlockchainException e) {
System.out.println( e.getMessage() );
}
String calculedHash = StringUtils.applySha256(previousTreeLayer.get(i-1) + previousTreeLayer.get(i));
if (calculedHash != null)
{ treeLayer.add( calculedHash ); }
}
count = treeLayer.size();
previousTreeLayer = treeLayer;
Expand Down
51 changes: 37 additions & 14 deletions src/main/java/gabywald/crypto/blockchain/Transaction.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@

import java.util.List;
import java.util.Map;

import gabywald.global.json.JSONException;
import gabywald.global.json.JSONValue;
import gabywald.global.json.JSONifiable;

import java.util.ArrayList;
import java.util.Base64;

Expand All @@ -16,7 +21,7 @@
* <br/><a href="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/CryptoKass/NoobChain-Tutorial-Part-2">https://github.com/CryptoKass/NoobChain-Tutorial-Part-2</a>
* @author Gabriel Chandesris (2021)
*/
public class Transaction {
public class Transaction extends JSONifiable {
/** This is also the hash of the transaction. */
private String transactionId;
/** senders address/public key. */
Expand Down Expand Up @@ -48,17 +53,11 @@ public Transaction(PublicKey from, PublicKey to, float value, List<TransactionI
private String calculateHash() {
// Increase the sequence to avoid 2 identical transactions having the same hash
Transaction.sequence++;
try {
return StringUtils.applySha256(
StringUtils.getStringFromKey(this.sender) +
StringUtils.getStringFromKey(this.recipient) +
Float.toString(value) + Transaction.sequence
);
} catch (BlockchainException e) {
// e.printStackTrace();
System.out.println( e.getMessage() );
return null;
}
return StringUtils.applySha256(
StringUtils.getStringFromKey(this.sender) +
StringUtils.getStringFromKey(this.recipient) +
Float.toString(value) + Transaction.sequence
);
}

/**
Expand Down Expand Up @@ -212,8 +211,6 @@ public float getOutputsValue() {
return total;
}



public void setTransactionId(String transactionId)
{ this.transactionId = transactionId; }

Expand All @@ -235,4 +232,30 @@ public List<TransactionOutput> getOutputs()
public List<TransactionInput> getInputs()
{ return this.inputs; }

@Override
protected void setKeyValues() {
this.put("transactionId", JSONValue.instanciate( this.transactionId.toString() ) );
this.put("sender", JSONValue.instanciate( this.sender.toString() ) );
this.put("recipient", JSONValue.instanciate( this.recipient.toString() ) );
this.put("value", JSONValue.instanciate( this.value ) );
// this.put("signature", JSONValue.instanciate( this.signature ) );
// this.put("sequence", JSONValue.instanciate( this.sequence ) );
}

@Override
protected <T extends JSONifiable> T reloadFrom(String json)
throws JSONException {
return null;
}

@Override
public String toString() {
StringBuilder sbToReturn = new StringBuilder();
sbToReturn.append("transactionId").append(": ").append( this.transactionId.toString() ).append("\n");
sbToReturn.append("sender").append(": ").append( this.sender.toString() ).append("\n");
sbToReturn.append("recipient").append(": ").append( this.recipient ).append("\n");
sbToReturn.append("value").append(": ").append( this.value ).append("\n");
return sbToReturn.toString();
}

}
12 changes: 3 additions & 9 deletions src/main/java/gabywald/crypto/blockchain/TransactionOutput.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,9 @@ public TransactionOutput(PublicKey reciepient, float value, String parentTransac
this.recipient = reciepient;
this.value = value;
this.parentTransactionId = parentTransactionId;
try {
this.id = StringUtils.applySha256(StringUtils.getStringFromKey(reciepient)
+ Float.toString(value) + parentTransactionId);
// TODO check alternatives for here when exception occurs !! (builder ?) : see StringUtils.applySha256 comment !
} catch (BlockchainException e) {
// e.printStackTrace();
System.out.println(e.getMessage());
this.id = null;
}

this.id = StringUtils.applySha256(StringUtils.getStringFromKey(reciepient)
+ Float.toString(value) + parentTransactionId);
}

/**
Expand Down