62 lines
1.8 KiB
Java
62 lines
1.8 KiB
Java
package tech.nevets.nevcoin;
|
|
|
|
import tech.nevets.nevcoin.transactions.Transaction;
|
|
import tech.nevets.nevcoin.util.StringUtil;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.Date;
|
|
|
|
public class Block {
|
|
|
|
public String hash;
|
|
public String previousHash;
|
|
public String merkleRoot;
|
|
public ArrayList<Transaction> transactions = new ArrayList<Transaction>();
|
|
//private String data;
|
|
private long timeStamp;
|
|
private int nonce;
|
|
|
|
public Block(String previousHash) {
|
|
//this.data = data;
|
|
this.previousHash = previousHash;
|
|
this.timeStamp = new Date().getTime();
|
|
this.hash = calculateHash();
|
|
}
|
|
|
|
public String calculateHash() {
|
|
String calculatedHash = StringUtil.applySha256(
|
|
previousHash
|
|
+ Long.toString(timeStamp)
|
|
+ Integer.toString(nonce)
|
|
+ merkleRoot
|
|
//+ data
|
|
);
|
|
return calculatedHash;
|
|
}
|
|
|
|
public void mineBlock(int difficulty) {
|
|
merkleRoot = StringUtil.getMerkleRoot(transactions);
|
|
String target = StringUtil.getDifficultyString(difficulty);
|
|
|
|
while (!hash.substring(0, difficulty).equals(target)) {
|
|
nonce ++;
|
|
hash = calculateHash();
|
|
}
|
|
System.out.println("Block mined: " + hash);
|
|
}
|
|
|
|
public boolean addTransaction(Transaction transaction) {
|
|
if (transaction == null) return false;
|
|
if (!"0".equals(previousHash)) {
|
|
if (transaction.processTransaction() != true) {
|
|
System.out.println("Transaction failed to process. Discarded.");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
transactions.add(transaction);
|
|
System.out.println("Transaction Successfully added to Block");
|
|
return true;
|
|
}
|
|
}
|