千家信息网

java 实例理解区块链的概念

发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,区块链的核心是去中心化的存储,传统的数据库解决方案,包括关系型数据库,非关系型数据库,都是属于中心化的存储方式。去中心化的存储,就是数据没有中心,并且每个数据节点都包含了上一个数据节点的信息。
千家信息网最后更新 2026年11月03日java 实例理解区块链的概念
   区块链的核心是去中心化的存储,传统的数据库解决方案,包括关系型数据库,非关系型数据库,都是属于中心化的存储方式。去中心化的存储,就是数据没有中心,并且每个数据节点都包含了上一个数据节点的信息。         通过一个实例来理解区块链的数据存储形式:

package com.weihua.blockchains.blackchain;

import java.util.Date;

public class BlockMan {

public String hash;public String previousHash; private String data; //our data will be a simple message.private long timeStamp; //as number of milliseconds since 1/1/1970.private int nonce;//Block Constructor.  public BlockMan(String data,String previousHash ) {    this.data = data;    this.previousHash = previousHash;    this.timeStamp = new Date().getTime();    this.hash = calculateHash(); //Making sure we do this after we set the other values.}//Calculate new hash based on blocks contentspublic String calculateHash() {    String calculatedhash = StringUtil.applySha256(             previousHash +            Long.toString(timeStamp) +            Integer.toString(nonce) +             data             );    return calculatedhash;}//Increases nonce value until hash target is reached.public void mineBlock(int difficulty) {    String target = StringUtil.getDificultyString(difficulty); //Create a string with difficulty * "0"     while(!hash.substring( 0, difficulty).equals(target)) {        nonce ++;        hash = calculateHash();    }    System.out.println("Block Mined!!! : " + hash);}

}

package com.weihua.blockchains.blackchain;
import java.security.MessageDigest;

import com.google.gson.GsonBuilder;

public class StringUtil {

//Applies Sha256 to a string and returns the result. public static String applySha256(String input){    try {        MessageDigest digest = MessageDigest.getInstance("SHA-256");        //Applies sha256 to our input,         byte[] hash = digest.digest(input.getBytes("UTF-8"));        StringBuffer hexString = new StringBuffer(); // This will contain hash as hexidecimal        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);    }}//Short hand helper to turn Object into a json stringpublic static String getJson(Object o) {    return new GsonBuilder().setPrettyPrinting().create().toJson(o);}//Returns difficulty string target, to compare to hash. eg difficulty of 5 will return "00000"  public static String getDificultyString(int difficulty) {    return new String(new char[difficulty]).replace('\0', '0');}

}

package com.weihua.blockchains.blackchain;
import java.util.ArrayList;

public class TestBlockChain {

public static ArrayList blockchain = new ArrayList();public static int difficulty = 5;public static void main(String[] args) {        //add our blocks to the blockchain ArrayList:    System.out.println("Trying to Mine block 1... ");    addBlock(new BlockMan("Hi im the first block", "0"));    System.out.println("Trying to Mine block 2... ");    addBlock(new BlockMan("Yo im the second block",blockchain.get(blockchain.size()-1).hash));    System.out.println("Trying to Mine block 3... ");    addBlock(new BlockMan("Hey im the third block",blockchain.get(blockchain.size()-1).hash));      System.out.println("\nBlockchain is Valid: " + isChainValid());    String blockchainJson = StringUtil.getJson(blockchain);    System.out.println("\nThe block chain: ");    System.out.println(blockchainJson);}public static Boolean isChainValid() {    BlockMan currentBlock;     BlockMan previousBlock;    String hashTarget = new String(new char[difficulty]).replace('\0', '0');    //loop through blockchain to check hashes:    for(int i=1; i < blockchain.size(); i++) {        currentBlock = blockchain.get(i);        previousBlock = blockchain.get(i-1);        //compare registered hash and calculated hash:        if(!currentBlock.hash.equals(currentBlock.calculateHash()) ){            System.out.println("Current Hashes not equal");                     return false;        }        //compare previous hash and registered previous hash        if(!previousBlock.hash.equals(currentBlock.previousHash) ) {            System.out.println("Previous Hashes not equal");            return false;        }        //check if hash is solved        if(!currentBlock.hash.substring( 0, difficulty).equals(hashTarget)) {            System.out.println("This block hasn't been mined");            return false;        }    }    return true;}public static void addBlock(BlockMan newBlock) {    newBlock.mineBlock(difficulty);    blockchain.add(newBlock);}

}

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0

com.weihua.blockchainsblackchain0.0.1-SNAPSHOTjarblackchainhttp://maven.apache.org    UTF-8            junit        junit        3.8.1        test                com.google.code.gson        gson        2.1    

运行起来看下输出:
Trying to Mine block 1...
Block Mined!!! : 000005b9947556fa4b14d24349728a58418c1517f8073d10a37ba3daf0ceee9c
Trying to Mine block 2...
Block Mined!!! : 00000015d3f53bd8545a3a9586aaef26abe26d78fce2da6584aac025c60c21e3
Trying to Mine block 3...
Block Mined!!! : 000000d224711a1e308e98c317cc7c900c7f4196d585266262b54e42288da65b

Blockchain is Valid: true

The block chain:
[
{
"hash": "000005b9947556fa4b14d24349728a58418c1517f8073d10a37ba3daf0ceee9c",
"previousHash": "0",
"data": "Hi im the first block",
"timeStamp": 1557928459188,
"nonce": 347042
},
{
"hash": "00000015d3f53bd8545a3a9586aaef26abe26d78fce2da6584aac025c60c21e3",
"previousHash": "000005b9947556fa4b14d24349728a58418c1517f8073d10a37ba3daf0ceee9c",
"data": "Yo im the second block",
"timeStamp": 1557928460017,
"nonce": 1394831
},
{
"hash": "000000d224711a1e308e98c317cc7c900c7f4196d585266262b54e42288da65b",
"previousHash": "00000015d3f53bd8545a3a9586aaef26abe26d78fce2da6584aac025c60c21e3",
"data": "Hey im the third block",
"timeStamp": 1557928462949,
"nonce": 81919
}
]

数据 存储 数据库 中心化 区块 节点 UTF-8 实例 传统 信息 就是 形式 方式 方案 核心 解决方案 输出 运行 概念 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 咖啡豆 科技赋能下的互联网金融 科技互联网项目 科技企业和互联网企业 中国 科技 互联网 为想互联网科技 易通互联网络科技有限公司 奔汉互联网科技 人人互联网科技是培训 无锡溥仪互联网科技有限公司 呼和浩特新华互联网科技学院 乌鲁木齐新华智原互联网科技学校 工业互联网山东科技大学 沐思想互联网科技有限公司 伍佰万互联网科技怎么赚钱 互联网科技包装股份有限公司上市 世界互联网科技成果奖 互联网科技平台产品运营 版纳互联网科技选哪家 长沙渺峰互联网科技有限公司 天津市摩尔互联网科技 互联网科技公司税收优惠 美国互联网科技巨头监管 互联网中国科技 重庆互联网络科技 滨湖区互联网智能科技产品供应 南山科技园互联网公司有哪些 哈尔滨屹滨互联网科技有限公司 互联网科技包装股份有限公司上市 郑州欣桑互联网科技有限公司
0