区块链-JAVA简单实现

1、 定义块

public class Block {
    /**
     * 当前块索引
     */
    private int index;
    private long timestamp;
    private String preBlockHash;
    private String currentHash;
    private String data;
    private int nonce;

    public Block(){

    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public String getPreBlockHash() {
        return preBlockHash;
    }

    public void setPreBlockHash(String preBlockHash) {
        this.preBlockHash = preBlockHash;
    }

    public String getCurrentHash() {
        return currentHash;
    }

    public void setCurrentHash(String currentHash) {
        this.currentHash = currentHash;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public int getNonce() {
        return nonce;
    }

    public void setNonce(int nonce) {
        this.nonce = nonce;
    }
}

2、 定义区块链(使用List数据结构)

public class BlockChain {

    private List<Block> blocks;

    public BlockChain(){
        blocks = new ArrayList();
    }

    public List<Block> getBlocks() {
        return blocks;
    }

    public void setBlocks(List<Block> blocks) {
        this.blocks = blocks;
    }
}

3、 定义块操作接口及实现类

//接口
public interface BlockService {

    /**
     * 生成创世块
     * @return
     */
    Block geneGenesisBlock();

    /**
     * 根据前一块生成后一块
     * @param newData 当前块内容
     * @return
     */
    Block geneNextBlock(String newData);

    /**
     * 工作量证明
     * @param block
     * @return
     */
    String geneBlockHash(Block block);
}
//接口实现类
public class BlockServiceImpl implements BlockService {

    private BlockChain blockChain;
    private final int DIFFICULTY = 2;

    public BlockServiceImpl(BlockChain blockChain){
        this.blockChain = blockChain;
    }


    public Block geneGenesisBlock() {
        Block block = new Block();
        block.setIndex(-1);
        block.setTimestamp(System.currentTimeMillis());
        block.setData("gene genesis block");
        block.setCurrentHash(geneBlockHash(block));
        block.setPreBlockHash("");
        return block;
    }

    public Block geneNextBlock(String newData) {
        Block preBlock = blockChain.getBlocks().get(blockChain.getBlocks().size()-1);
        Block newBlock = new Block();
        newBlock.setIndex(preBlock.getIndex()+1);
        newBlock.setTimestamp(System.currentTimeMillis());
        newBlock.setData(newData);
        newBlock.setPreBlockHash(preBlock.getCurrentHash());
        newBlock.setCurrentHash(geneBlockHash(newBlock));
        return newBlock;
    }

    public String geneBlockHash(Block block){
        String target = new String(new char[DIFFICULTY]).replace('\0', '0');
        int i=0;
        boolean flag =true;
        String hash="";
        while(flag){
            hash = HashUtil.getSHA2HexValue(block.getIndex()+block.getTimestamp()+block.getData()+block.getPreBlockHash()+i);
            if (!hash.substring( 0, DIFFICULTY).equals(target)){
                i++;
                System.out.println(hash);
            }else{
                flag =false;
            }
        }
        return hash;
    }
}

4、 区块链操作接口及实现类

//接口
public interface BlockChainService {

    /**
     * 区块链增加区块
     * @param block
     */
    void appendBlock(Block block);
}
//实现类
public class BlockChainServiceImpl implements BlockChainService {

    private BlockChain blockChain;

    public BlockChainServiceImpl(BlockChain blockChain){
        this.blockChain = blockChain;
    }

    /**
     * 追加块
     * @param block
     *
     * TODO 校验块是否是有效的
     */
    public void appendBlock(Block block) {
        blockChain.getBlocks().add(block);
    }
}

5、 测试

public class BlockTest {

    public static void main(String[] args){

        Gson gson = new Gson();

        //初始区块链
        BlockChain blockChain =new BlockChain();

        BlockChainServiceImpl blockChainServiceImpl=new BlockChainServiceImpl(blockChain);
        BlockServiceImpl blockService = new BlockServiceImpl(blockChain);

        //初始化创世快
        Block genesisBlock = blockService.geneGenesisBlock();

        blockChainServiceImpl.appendBlock(genesisBlock);
        blockChainServiceImpl.appendBlock(blockService.geneNextBlock("test"));
        blockChainServiceImpl.appendBlock(blockService.geneNextBlock("test1"));

        System.out.println(gson.toJson(blockChain));

        for (Block block : blockChain.getBlocks()){
            System.out.println("index: "+block.getIndex());
            System.out.println("timestamp: "+block.getTimestamp());
            System.out.println("preBlockHash: "+block.getPreBlockHash());
            System.out.println("currentHash: "+block.getCurrentHash());
            System.out.println("data: "+block.getData());
            System.out.println();
        }

    }
}

猜你喜欢

转载自blog.csdn.net/u014271612/article/details/81479959