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
1 change: 1 addition & 0 deletions .classpath
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,6 @@
</attributes>
</classpathentry>
<classpathentry kind="lib" path="src/main/resources/tools.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# DiversTestsJava
Quelques tests de programmation en Java, des notes diverses,

* JDBC local (avec un peu de MySQL)
* OAuth
* Challenge CybserSec
* Java Swing : Full Screen, SpalshScreen (à revoir / préciser)
* Java reflect / réflexivité / introspection
* JDBC local (avec un peu de MySQL)
* OAuth
* Socket implementation
* HTTP use
* Challenge CybserSec (quelques notes)
* Java Swing : Full Screen, SpalshScreen (à revoir / préciser)
* Java reflect / réflexivité / introspection
* "blockchain"
16 changes: 16 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,21 @@
<artifactId>utilities</artifactId>
<version>0.0.2-SNAPSHOT</version>
</dependency>

<!-- 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>
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15to18 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>1.69</version>
</dependency>


</dependencies>
</project>
127 changes: 127 additions & 0 deletions src/main/java/NoobChainTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import static org.junit.jupiter.api.Assertions.*;

import java.security.Security;
import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import com.google.gson.GsonBuilder;

import gabywald.crypto.blockchain.Block;
import gabywald.crypto.blockchain.BlockChain;
import gabywald.crypto.blockchain.StringUtils;
import gabywald.crypto.blockchain.Transaction;
import gabywald.crypto.blockchain.Wallet;

/**
* Tests about BlockChain / NoobChain.
* @author Gabriel Chandesris (2021)
*/
class NoobChainTests {

/**
* Test : block.
*/
@Test
void testPart01() {
Block genesisBlock = new Block("Hi im the first block", "0");
Assertions.assertNotNull( genesisBlock );
System.out.println("Hash for block 1 : " + genesisBlock.getHash() );
Assertions.assertNotNull( genesisBlock.getHash() );

Block secondBlock = new Block("Yo im the second block", genesisBlock.getHash() );
Assertions.assertNotNull( secondBlock );
System.out.println("Hash for block 2 : " + secondBlock.getHash() );
Assertions.assertNotNull( secondBlock.getHash() );

Block thirdBlock = new Block("Hey im the third block", secondBlock.getHash() );
Assertions.assertNotNull( thirdBlock );
System.out.println("Hash for block 3 : " + thirdBlock.getHash() );
Assertions.assertNotNull( thirdBlock.getHash() );
}

/**
* Test : blockchain
*/
@Test
void testPart02() {
List<Block> blockchain = new ArrayList<Block>();
// Add our blocks to the blockchain List:
blockchain.add(new Block("Hi im the first block", "0"));
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 );
System.out.println(blockchainJson);
}

@Test
void testPart03() {
List<Block> blockchain = new ArrayList<Block>();
int difficulty = 3;
// Add our blocks to the blockchain List:
blockchain.add(new Block("Hi im the first block", "0"));
System.out.println("Trying to Mine block 1... ");
blockchain.get(0).mineBlock(difficulty);

blockchain.add(new Block("Yo im the second block", blockchain.get(blockchain.size()-1).getHash() ));
System.out.println("Trying to Mine block 2... ");
blockchain.get(1).mineBlock(difficulty);

blockchain.add(new Block("Hey im the third block", blockchain.get(blockchain.size()-1).getHash() ));
System.out.println("Trying to Mine block 3... ");
blockchain.get(2).mineBlock(difficulty);

Assertions.assertEquals(3, blockchain.size());

System.out.println("\nBlockchain is Valid: " + BlockChain.isChainValidV1( blockchain ));

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

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

Assertions.assertNotNull( blockchainJson );

System.out.println("\nThe block chain: ");
System.out.println(blockchainJson);
}

@Test
void testPart04() {
// Setup Bouncey castle as a Security Provider
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// Security.addProvider(new sun.security.provider.Sun());
// XXX NOTE see https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html
// Create the new wallets
Wallet walletA = new Wallet();
Wallet walletB = new Wallet();
Assertions.assertNotNull( walletA );
Assertions.assertNotNull( walletB );
// Test public and private keys
System.out.println("Private and public keys:");
System.out.println(StringUtils.getStringFromKey(walletA.privateKey));
System.out.println(StringUtils.getStringFromKey(walletA.publicKey));
Assertions.assertNotNull( walletA.privateKey );
Assertions.assertNotNull( walletA.publicKey );
Assertions.assertNotNull( walletB.privateKey );
Assertions.assertNotNull( walletB.publicKey );
//Create a test transaction from WalletA to walletB
Transaction transaction = new Transaction(walletA.publicKey, walletB.publicKey, 5, null);
Assertions.assertNotNull( transaction );
transaction.generateSignature(walletA.privateKey);
Assertions.assertNotNull( walletA.privateKey );
//Verify the signature works and verify it from the public key
System.out.println("Is signature verified");
System.out.println(transaction.verifySignature());
Assertions.assertTrue( transaction.verifySignature() );
}

@Test
void testPart05() {
fail("Not yet implemented");
}

}
123 changes: 123 additions & 0 deletions src/main/java/gabywald/crypto/blockchain/Block.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package gabywald.crypto.blockchain;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* 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 {

private String hash;
private String previousHash;
/** Our data will be a simple message. */
// private String data;
/** As number of milliseconds since 1/1/1970. */
private long timeStamp;
private int nonce;

private String merkleRoot;

private List<Transaction> transactions = new ArrayList<Transaction>();

/**
* Block Constructor.
* @param data
* @param previousHash
*/
public Block(String data, String previousHash ) {
// this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
// Making sure we do this after we set the other values.
this.hash = this.calculateHash();
}

/**
* Block Constructor.
* @param previousHash
*/
public Block(String previousHash ) {
this(null, previousHash);
}

/**
* Calculate new hash based on blocks contents
* @return (null if exception apply internally).
* @see StringUtils#applySha256(String)
*/
public String calculateHash() {
String calculatedhash = null;
try {
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;
}

/**
* Mining block
* @param difficulty
*/
public void mineBlock(int difficulty) {
this.merkleRoot = StringUtils.getMerkleRoot(this.transactions);
// Create a string with difficulty * "0"
String target = StringUtils.getDifficultyString(difficulty);
while ( (this.hash == null) || ( ! this.hash.substring( 0, difficulty ).equals(target)) ) {
this.nonce++;
this.hash = this.calculateHash();
// XXX NOTE if exception inside calculateHash : hash will be null !
}
System.out.println("Block Mined!!! : " + this.hash);
}

/**
* Add transactions to this block.
* @param transaction
* @param UTXOs
* @param minimumTransaction
* @return (boolean)
*/
public boolean addTransaction( final Transaction transaction,
final Map<String, TransactionOutput> UTXOs,
final float minimumTransaction) {
// Process transaction and check if valid, unless block is genesis block then ignore.
if (transaction == null) { return false; }
if (this.previousHash != "0") {
if (transaction.processTransaction(UTXOs, minimumTransaction) != true) {
System.out.println("Transaction failed to process. Discarded.");
return false;
}
}
this.transactions.add(transaction);
System.out.println("Transaction Successfully added to Block");
return true;
}

public String getHash()
{ return this.hash; }

public String getPreviousHash()
{ return this.previousHash; }

public String getMerkleRoot()
{ return this.merkleRoot; }

public List<Transaction> getTransactions()
{ return this.transactions; }


}
Loading