您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

简易区块链demo

区块链原理就不加赘述,网上百度都是一堆,贴一下代码方便以后查看

public class Block {
    //哈希值
    private String hash;
    //前一节点哈希
    private String previousHash;
    //数据
    private String data;
    //时间戳
    private long timeStamp;
    //随机数
    private int nonce;

    public Block(String data, String previousHash, long timeStamp) {
        this.data = data;
        this.previousHash = previousHash;
        this.timeStamp = timeStamp;
    }

    public String getHash() {
        return hash;
    }

    public void setHash(String hash) {
        this.hash = hash;
    }

    public String getPreviousHash() {
        return previousHash;
    }

    public void setPreviousHash(String previousHash) {
        this.previousHash = previousHash;
    }

    public String getData() {
        return data;
    }

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

    public long getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(long timeStamp) {
        this.timeStamp = timeStamp;
    }

    public int getNonce() {
        return nonce;
    }

    public void setNonce(int nonce) {
        this.nonce = nonce;
    }
    
    @Override
    public String toString() {
        return "Block{" +
                "hash='" + hash + '\'' +
                ", previousHash='" + previousHash + '\'' +
                ", data='" + data + '\'' +
                ", timeStamp=" + timeStamp +
                ", nonce=" + nonce +
                '}';
    }
}
public class HashUtils {
    public String calculateBlockHash(Block block) {
        //把块不同部位连接起来
        String dataToHash = block.getPreviousHash()
                + Long.toString(block.getTimeStamp())
                + Integer.toString(block.getNonce())
                + block.getData();
        MessageDigest digest = null;
        byte[] bytes = null;
        try {
            //获取哈希实例
            digest = MessageDigest.getInstance("SHA-256");
            //生成哈希值
            bytes = digest.digest(dataToHash.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
            System.out.println(Level.SEVERE + ":::" + ex.getMessage());
        }
        //转换为字符串
        StringBuffer buffer = new StringBuffer();
        for (byte b : bytes) {
            buffer.append(String.format("%02x", b));
        }
        return buffer.toString();
    }

    public String mineBlock(Block block , int prefix) {
        String hash = block.getHash();
        //验证哈希是否有效
        String prefixString = new String(new char[prefix]).replace('\0', '0');
        while (!hash.substring(0, prefix).equals(prefixString)) {
            block.setNonce(block.getNonce() + 1);
            hash = calculateBlockHash(block);
        }
        System.out.println(block.getNonce());
        System.out.println("挖出:" + hash + ",随机数:" + block.getNonce());
        return hash;
    }
}
public class Test {
    static List<Block> blockchain = new ArrayList<>();
    static int PREFIX = 5;

    private static void doBlock(int i){
        String prefixString = new String(new char[PREFIX]).replace('\0', '0');

        HashUtils hashUtils = new HashUtils();

        String previousHash = null;
        if (blockchain.size() == 0){
            previousHash = "0";
        }else{
            previousHash = blockchain.get(blockchain.size() - 1).getHash();
        }

        Block newBlock = new Block(
                "耗子币" + i,
                previousHash ,
                new Date().getTime());
        newBlock.setNonce(0);
        newBlock.setHash("12345");

        newBlock.setHash(hashUtils.mineBlock(newBlock , PREFIX));
        if(newBlock.getHash().substring(0, PREFIX).equals(prefixString)){
            blockchain.add(newBlock);
        }
    }

    private static void vaild(){
        HashUtils hashUtils = new HashUtils();
        String prefixString = new String(new char[PREFIX]).replace('\0', '0');
        boolean flag = true;
        for (int i = 0; i < blockchain.size(); i++) {
            Block block = blockchain.get(i);
            String previousHash = i == 0 ? "0" : blockchain.get(i - 1).getHash();

            flag = block.getHash().equals(hashUtils.calculateBlockHash(block))
                    && previousHash.equals(block.getPreviousHash())
                    && block.getHash().substring(0, PREFIX).equals(prefixString);
            if (!flag){
                System.out.println("校验失败");
                break;
            }else {
                System.out.println("节点" +block.toString()+ "成功");
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("start:" + new Date());
        for (int i = 0 ; i < 5 ; i ++){
            doBlock(i + 1);
        }
        vaild();

        System.out.println("end:" + new Date());
    }
}

 


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进