三分鐘搭建一個簡易的區塊鏈原型

區塊鏈是一種去中心化、不可篡改的分布式賬本。

了解區塊鏈的構成以及基本的原理對于初學者非常重要。本文將使用Java語言搭建最簡單的區塊鏈原型。

區塊

建立Block類?,具有以下屬性:

    private String mTimestamp;
    private String mPrevBlockHash;
    private String mHash;
    private String mData;

  • mTimestamp 時間戳,表示當前區塊創建時的時間
  • mPrevBlockHash前一塊?區塊的hash
  • mData 當前區塊所保存的信息
  • mHash 當前區塊的?hash(當前區塊??所有信息拼接后產生的hash)

在初始化區塊時需要前一塊區塊?preHash和當前區塊的data

 public Block(String data, String prehash) {
        this.mData = data;
        this.mPrevBlockHash = prehash;
        this.setHash();
    }

   private void setHash() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設置日期格式
        mTimestamp = df.format(new Date());
        String headers = mTimestamp + mPrevBlockHash + mData;
        mHash = block.SHA(headers, "SHA-256");

    }

Hash

在Java中如何?計算SHA-256值呢?

public static String SHA(final String strText, final String strType) {
        // 返回值
        String strResult = null;
        // 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
                // SHA 加密開始
                // 創建加密對象 并傳入加密類型
                MessageDigest messageDigest = MessageDigest.getInstance(strType);
                // 傳入要加密的字符串
                messageDigest.update(strText.getBytes());
                // 得到 byte 類型結果
                byte byteBuffer[] = messageDigest.digest();

                // 將 byte 轉換爲 string
                StringBuffer strHexString = new StringBuffer();
                // 遍歷 byte buffer
                for (int i = 0; i < byteBuffer.length; i++) {
                    String hex = Integer.toHexString(0xff & byteBuffer[i]);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                // 得到返回結果
                strResult = strHexString.toString();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return strResult;
    }

我們使用以及寫好的方法具體的原理就請大家自行搜索學習了。

區塊鏈

區塊鏈是由區塊與區塊‘連接’而成的,如何將區塊連接起來呢?

建立一個Blockchain類
我們需要一個專門存放若干區塊的載體List

    public  static List<Block> blockChain;

添加一個新的區塊

  public static void addBlock(String data) {
        Block preBlock = blockChain.get(blockChain.size() - 1);
        Block newBlock = new Block(data, preBlock.getmHash());
        blockChain.add(newBlock);
    }

將前一區塊的hash取出,創建新的區塊并加入到List中

創建創世塊

private block newGenesisBlock() {
        return new block("Genesis", "0");
    }

創建區塊鏈

 public void newBlockchain() {
        blockChain = new ArrayList<block>();
        blockChain.add(this.newGenesisBlock());
    }

編寫測試類

public class Main {
    public static void main(String[] args) {
        BlockChain.newBlockchain();
        BlockChain.addBlock("tom");
        BlockChain.addBlock("jack");
        BlockChain.addBlock("jerry");


        for (int i = 0; i < BlockChain.blockChain.size(); i++) {
            Block b = BlockChain.blockChain.get(i);
            System.out.println("|-----------------------------------|");
            System.out.println("區塊編號:" + i);
            System.out.println("時間:" + b.getmTimestamp());
            System.out.println("數據:" + b.getmData());
            System.out.println("父Hash:" + b.getmPrevBlockHash());
            System.out.println("Hash:" + b.getmHash());

        }
        System.out.print("|-----------------------------------|");


    }
}



運行結果:

|-----------------------------------|
區塊編號:0
時間:2017-10-25 23:26:55
數據:Genesis
父Hash:0
Hash:7a708fe6c9c1038b313a83cc2deeea40f270ea7e6fb2ff0dfd981ef6f2e8ff2a
|-----------------------------------|
區塊編號:1
時間:2017-10-25 23:26:55
數據:tom
父Hash:7a708fe6c9c1038b313a83cc2deeea40f270ea7e6fb2ff0dfd981ef6f2e8ff2a
Hash:481abd2e8797fbe4ef0eaf02aaf4952d4d68366cab9204a60c6f635c61b88ce6
|-----------------------------------|
區塊編號:2
時間:2017-10-25 23:26:55
數據:jack
父Hash:481abd2e8797fbe4ef0eaf02aaf4952d4d68366cab9204a60c6f635c61b88ce6
Hash:bab85541ab30bec07c765b23d55c69522b09b9d3ab1aed0a7ebbee258f123a61
|-----------------------------------|
區塊編號:3
時間:2017-10-25 23:26:55
數據:jerry
父Hash:bab85541ab30bec07c765b23d55c69522b09b9d3ab1aed0a7ebbee258f123a61
Hash:4dc6075449d753c3101e8d08aaee731cf9bea48d7c2fa24195ebb58ad4a988d7
|-----------------------------------|

不到三分鐘一個最簡單的區塊鏈原型就搭建好了。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容