区块链nonce的java实现过程,单机区块链实现

区块链就是一串或者是一系列区块的集合,类似于链表的概念,每个区块都指向于后面一个区块,然后顺序的连接在一起。在区块链中的每一个区块都存放了很多很有价值的信息,主要包括三个部分:自己的数字签名,上一个区块的数字签名,还有一切需要加密的数据(这些数据在比特币中就相当于是交易的信息,它是加密货币的本质)。每个数字签名不但证明了自己是特有的一个区块,而且指向了前一个区块的来源,让所有的区块在链条中可以串起来,而数据就是一些特定的信息,你可以按照业务逻辑来保存业务数据。

7a4b768d91842b1047be7e259b70be51.png

这里的hash指的就是数字签名

所以每一个区块不仅包含前一个区块的hash值,同时包含自身的一个hash值,自身的hash值是通过之前的hash值和数据data通过hash计算出来的。如果前一个区块的数据一旦被篡改了,那么前一个区块的hash值也会同样发生变化(因为数据也被计算在内),这样也就导致了所有后续的区块中的hash值。所以计算和比对hash值会让我们检查到当前的区块链是否是有效的,也就避免了数据被恶意篡改的可能性,因为篡改数据就会改变hash值并破坏整个区块链。

/*** 区块*/@ToString@Getterpublic classBlock {

//数字签名privateString hash;//上一个区块的数字签名privateString preHash;//保存的数据privateString data;//时间戳private longtimeStamp;//工作量证明private intnonce;

publicBlock(String data,String preHash) {

this.data= data;this.preHash= preHash;timeStamp= newDate().getTime();hash= calculateHash();}

/*** 计算数字签名*@return*/publicString calculateHash() {

returnStringUntil.applySha256(preHash+ timeStamp+ nonce+ data);}

/*** 挖矿*@paramdifficuity挖矿难度*/public voidmineBlock(intdifficuity) {

String target = newString(new char[difficuity]).replace('\0','0');while(!hash.substring(0,difficuity).equals(target)) {

nonce++;hash= calculateHash();}

System.out.println("Block Mind!!!: "+ hash);}

}

public classStringUntil {

/*** Sha256离散*@paraminput*@return*/public staticString 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 = newStringBuffer();// This will contain hash as hexidecimalfor(inti = 0;i < hash.length;i++) {

String hex = Integer.toHexString(0xff& hash[i]);if(hex.length() == 1) hexString.append('0');hexString.append(hex);}

returnhexString.toString();}

catch(Exception e) {

throw newRuntimeException(e);}

}

}

public classBlockChain {

public staticList blockChain= newArrayList<>();public static intdifficulty= 5;

/*** 判断整条区块链是否有效*@return*/public static booleanisChainValid() {

Block currentBlock;Block prevBlock;String hashTarget = newString(new char[difficulty]).replace('\0','0');

for(inti = 1;i < blockChain.size();i++) {

currentBlock = blockChain.get(i);prevBlock = blockChain.get(i - 1);if(!currentBlock.getHash().equals(currentBlock.calculateHash())) {

System.out.println("当前区块哈希值不匹配");return false;}

if(!prevBlock.getHash().equals(currentBlock.getPreHash())) {

System.out.println("前一个区块哈希值不匹配");return false;}

if(!currentBlock.getHash().substring(0,difficulty).equals(hashTarget)) {

System.out.println("当前区块有异常");return false;}

}

return true;}

public static voidmain(String[] args) {

//生成首区块Block genesisBlock = newBlock("first","0");blockChain.add(genesisBlock);//挖矿blockChain.get(0).mineBlock(difficulty);System.out.println(genesisBlock);//第二个区块Block secBlock = newBlock("second",genesisBlock.getHash());blockChain.add(secBlock);blockChain.get(1).mineBlock(difficulty);System.out.println(secBlock);//第三个区块Block thirdBlock = newBlock("third",secBlock.getHash());blockChain.add(thirdBlock);blockChain.get(2).mineBlock(difficulty);System.out.println(thirdBlock);System.out.println("区块链有效性: "+ isChainValid());System.out.println(JSONObject.toJSONString(blockChain));}

}

运行结果

Block Mind!!!: 000000dcabbe4bbeccbedc1efc25a886c598652e1efac0dfe1a3d74d9bc9f858

Block(hash=000000dcabbe4bbeccbedc1efc25a886c598652e1efac0dfe1a3d74d9bc9f858, preHash=0, data=first, timeStamp=1608653349150, nonce=1196438)

Block Mind!!!: 00000f6e06be2d09e9e8ba232d84ebe0de75b8e395feaa0f3ddb01377b55c72d

Block(hash=00000f6e06be2d09e9e8ba232d84ebe0de75b8e395feaa0f3ddb01377b55c72d, preHash=000000dcabbe4bbeccbedc1efc25a886c598652e1efac0dfe1a3d74d9bc9f858, data=second, timeStamp=1608653351114, nonce=1312709)

Block Mind!!!: 0000004bdf0b2af602460d79cdd247ac1b57fb651eb68ae68198b514de490569

Block(hash=0000004bdf0b2af602460d79cdd247ac1b57fb651eb68ae68198b514de490569, preHash=00000f6e06be2d09e9e8ba232d84ebe0de75b8e395feaa0f3ddb01377b55c72d, data=third, timeStamp=1608653353097, nonce=1552650)

区块链有效性: true

[{"data":"first","hash":"000000dcabbe4bbeccbedc1efc25a886c598652e1efac0dfe1a3d74d9bc9f858","nonce":1196438,"preHash":"0","timeStamp":1608653349150},{"data":"second","hash":"00000f6e06be2d09e9e8ba232d84ebe0de75b8e395feaa0f3ddb01377b55c72d","nonce":1312709,"preHash":"000000dcabbe4bbeccbedc1efc25a886c598652e1efac0dfe1a3d74d9bc9f858","timeStamp":1608653351114},{"data":"third","hash":"0000004bdf0b2af602460d79cdd247ac1b57fb651eb68ae68198b514de490569","nonce":1552650,"preHash":"00000f6e06be2d09e9e8ba232d84ebe0de75b8e395feaa0f3ddb01377b55c72d","timeStamp":1608653353097}]

以下是一个简单的Java实现区块链的代码: ``` import java.util.ArrayList; import java.util.Date; public class Block { public String hash; public String previousHash; private String data; // 我们的简单数据模拟为一个字符串 private long timeStamp; // 当前时间戳 private int nonce; public Block(String data, String previousHash) { this.data = data; this.previousHash = previousHash; this.timeStamp = new Date().getTime(); this.hash = calculateHash(); } public String calculateHash() { String calculatedHash = StringUtil.applySha256( previousHash + Long.toString(timeStamp) + Integer.toString(nonce) + data ); return calculatedHash; } 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); } } public class StringUtil { public static String applySha256(String input) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(input.getBytes("UTF-8")); 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 (Exception e) { throw new RuntimeException(e); } } } public class Blockchain { private ArrayList<Block> blockchain = new ArrayList<Block>(); private int difficulty = 5; public void addBlock(Block newBlock) { newBlock.mineBlock(difficulty); blockchain.add(newBlock); } public boolean isChainValid() { Block currentBlock; Block previousBlock; String hashTarget = new String(new char[difficulty]).replace('\0', '0'); for (int i = 1; i < blockchain.size(); i++) { currentBlock = blockchain.get(i); previousBlock = blockchain.get(i - 1); if (!currentBlock.hash.equals(currentBlock.calculateHash())) { System.out.println("Current Hashes not equal"); return false; } if (!previousBlock.hash.equals(currentBlock.previousHash)) { System.out.println("Previous Hashes not equal"); return false; } if (!currentBlock.hash.substring(0, difficulty).equals(hashTarget)) { System.out.println("This block hasn't been mined"); return false; } } return true; } } public class Main { public static Blockchain blockchain = new Blockchain(); public static void main(String[] args) { Block genesisBlock = new Block("First Block", "0"); blockchain.addBlock(genesisBlock); Block secondBlock = new Block("Second Block", genesisBlock.hash); blockchain.addBlock(secondBlock); Block thirdBlock = new Block("Third Block", secondBlock.hash); blockchain.addBlock(thirdBlock); System.out.println("Blockchain is valid: " + blockchain.isChainValid()); // 修改一个块的数据,看看区块链是否仍然有效 secondBlock.data = "Second Block modified"; System.out.println("Blockchain is valid: " + blockchain.isChainValid()); } } ``` 这段代码实现了一个简单的区块链,其中包含了区块的添加、挖矿、验证等功能。该代码中使用了SHA-256哈希算法来计算区块的哈希值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值