区块链节点同步Java代码_如何实现一个自己的区块链。第二部分:从不同的节点同步区块链...
时间: 2023-12-10 19:38:57 浏览: 118
实现一个自己的区块链需要考虑到节点之间的同步问题,下面是Java代码实现节点之间同步区块链的示例:
1. Node类
首先定义一个Node类,表示一个区块链节点。该类包含节点的IP地址、端口号以及一个BlockChain对象。
```java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Node {
private String ip;
private int port;
private BlockChain blockChain;
public Node(String ip, int port, BlockChain blockChain) {
this.ip = ip;
this.port = port;
this.blockChain = blockChain;
}
public void sync() {
try {
Socket socket = new Socket(ip, port);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
// 发送本节点区块链的最后一个区块的哈希值
out.writeObject(blockChain.getLastBlockHash());
// 接收对方节点的区块链
BlockChain remoteBlockChain = (BlockChain) in.readObject();
// 合并本节点和对方节点的区块链
blockChain.merge(remoteBlockChain);
in.close();
out.close();
socket.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
2. BlockChain类
接下来定义一个BlockChain类,表示区块链。该类包含一系列区块、难度值以及一个方法用于合并两个区块链。
```java
import java.util.ArrayList;
import java.util.List;
public class BlockChain {
private int difficulty;
private List<Block> blocks;
public BlockChain(int difficulty) {
this.difficulty = difficulty;
this.blocks = new ArrayList<>();
blocks.add(new Block(0, "Genesis Block"));
}
public String getLastBlockHash() {
return blocks.get(blocks.size() - 1).getHash();
}
public void addBlock(Block block) {
block.mineBlock(difficulty);
blocks.add(block);
}
public void merge(BlockChain other) {
if (other.blocks.size() <= blocks.size()) {
return;
}
for (int i = blocks.size(); i < other.blocks.size(); i++) {
Block block = other.blocks.get(i);
if (block.isValid() && block.getPrevHash().equals(getLastBlockHash())) {
blocks.add(block);
} else {
break;
}
}
}
}
```
3. Block类
最后定义一个Block类,表示区块。该类包含区块的索引、时间戳、交易记录、前一个区块的哈希值以及一个Nonce值。
```java
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
public class Block implements Serializable {
private static final long serialVersionUID = 1L;
private int index;
private long timestamp;
private String data;
private String prevHash;
private String hash;
private int nonce;
public Block(int index, String data) {
this.index = index;
this.timestamp = new Date().getTime();
this.data = data;
this.prevHash = "";
this.hash = calculateHash();
this.nonce = 0;
}
public String getPrevHash() {
return prevHash;
}
public String getHash() {
return hash;
}
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: " + hash);
}
public boolean isValid() {
if (!hash.equals(calculateHash())) {
return false;
}
if (!prevHash.isEmpty() && !prevHash.equals(calculatePrevHash())) {
return false;
}
return true;
}
private String calculateHash() {
String data = index + timestamp + this.data + prevHash + nonce;
return sha256(data);
}
private String calculatePrevHash() {
String data = (index - 1) + timestamp + data + prevHash + nonce;
return sha256(data);
}
private String sha256(String data) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(data.getBytes());
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 (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
```
4. 示例
最后给出一个示例,构建两个节点,它们的IP地址和端口号分别为localhost:8000和localhost:8001。
```java
public class Main {
public static void main(String[] args) {
BlockChain blockChain1 = new BlockChain(4);
blockChain1.addBlock(new Block(1, "Block 1"));
blockChain1.addBlock(new Block(2, "Block 2"));
BlockChain blockChain2 = new BlockChain(4);
blockChain2.addBlock(new Block(1, "Block 1"));
Node node1 = new Node("localhost", 8000, blockChain1);
Node node2 = new Node("localhost", 8001, blockChain2);
node1.sync();
node2.sync();
System.out.println("Node 1: " + blockChain1.getLastBlockHash());
System.out.println("Node 2: " + blockChain2.getLastBlockHash());
}
}
```
在该示例中,节点1先向节点2发送自己区块链的最后一个区块的哈希值,节点2接收到后将自己的区块链发送给节点1,然后节点1将两个区块链合并,最终节点1和节点2的区块链都包含了两个区块。
阅读全文