给我一段java实现区块链的代码
时间: 2023-05-29 08:06:43 浏览: 108
以下是一个简单的Java实现区块链的代码:
```
import java.util.ArrayList;
import java.util.Date;
public class Block {
public String hash;
public 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 = calculateHash();
}
public String calculateHash() {
String calculatedHash = StringUtil.applySha256(
previousHash +
Long.toString(timeStamp) +
Integer.toString(nonce) +
data
);
return calculatedHash;
}
public void mineBlock(int difficulty) {
String target = new String(new char[difficulty]).replace('\0', '0');
while (!hash.substring(0, difficulty).equals(target)) {
nonce++;
hash = calculateHash();
}
System.out.println("Block Mined!!! : " + hash);
}
}
public class StringUtil {
public static String applySha256(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public class Blockchain {
private ArrayList<Block> blockchain = new ArrayList<Block>();
private int difficulty = 5;
public void addBlock(Block newBlock) {
newBlock.mineBlock(difficulty);
blockchain.add(newBlock);
}
public boolean isChainValid() {
Block currentBlock;
Block previousBlock;
String hashTarget = new String(new char[difficulty]).replace('\0', '0');
for (int i = 1; i < blockchain.size(); i++) {
currentBlock = blockchain.get(i);
previousBlock = blockchain.get(i - 1);
if (!currentBlock.hash.equals(currentBlock.calculateHash())) {
System.out.println("Current Hashes not equal");
return false;
}
if (!previousBlock.hash.equals(currentBlock.previousHash)) {
System.out.println("Previous Hashes not equal");
return false;
}
if (!currentBlock.hash.substring(0, difficulty).equals(hashTarget)) {
System.out.println("This block hasn't been mined");
return false;
}
}
return true;
}
}
public class Main {
public static Blockchain blockchain = new Blockchain();
public static void main(String[] args) {
Block genesisBlock = new Block("First Block", "0");
blockchain.addBlock(genesisBlock);
Block secondBlock = new Block("Second Block", genesisBlock.hash);
blockchain.addBlock(secondBlock);
Block thirdBlock = new Block("Third Block", secondBlock.hash);
blockchain.addBlock(thirdBlock);
System.out.println("Blockchain is valid: " + blockchain.isChainValid());
// 修改一个块的数据,看看区块链是否仍然有效
secondBlock.data = "Second Block modified";
System.out.println("Blockchain is valid: " + blockchain.isChainValid());
}
}
```
这段代码实现了一个简单的区块链,其中包含了区块的添加、挖矿、验证等功能。该代码中使用了SHA-256哈希算法来计算区块的哈希值。
阅读全文