【区块链】使用JAV简易A模拟创建区块链及挖矿
发布日期:2021-06-29 19:46:47
浏览次数:3
分类:技术文章
本文共 4515 字,大约阅读时间需要 15 分钟。
想法:
1.创建区块链。区块链是由一个个区块组成的链表,每个区块包含前一个区块的哈希和本身区块的哈希。每个区块还包含数据,创建事件,nonce等信息。 2.使用SHA256生成哈希值。 3.挖矿。找到哈希值为前diffcult位数0的nonce值。 代码:import java.util.Date;import java.util.ArrayList;import com.google.gson.GsonBuilder;import java.security.MessageDigest;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); } }}class Block { 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 Block(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 contents 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'); //Create a string with difficulty * "0" //System.out.println(target); while (!hash.substring(0, difficulty).equals(target)) { nonce++; hash = calculateHash(); } System.out.println("Block Mined!!! : " + hash); }}public class main{ public static int difficulty = 5; public static ArrayListblockchain = new ArrayList (); public static void main(String[] args) { //add our blocks to the blockchain ArrayList: blockchain.add(new Block("Hi im the first block", "0")); System.out.println("Trying to Mine block 1... "); blockchain.get(0).mineBlock(difficulty); blockchain.add(new Block("Yo im the second block", blockchain.get(blockchain.size() - 1).hash)); System.out.println("Trying to Mine block 2... "); blockchain.get(1).mineBlock(difficulty); blockchain.add(new Block("Hey im the third block", blockchain.get(blockchain.size() - 1).hash)); System.out.println("Trying to Mine block 3... "); blockchain.get(2).mineBlock(difficulty); System.out.println("\nBlockchain is Valid: " + isChainValid()); String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain); System.out.println("\nThe block chain: "); System.out.println(blockchainJson); } public static Boolean isChainValid() { Block currentBlock; Block 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; }}
转载地址:https://darkness.blog.csdn.net/article/details/115318603 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2024年04月19日 16时33分56秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【H.264/AVC 句法和语义详解】(九):图像参数集PPS句法和语义
2019-04-30
【H.264/AVC 句法和语义详解】(十):最简单的H264编解码器
2019-04-30
【H.264/AVC 句法和语义详解】(十一):Slice_Header的句法和语义
2019-04-30
【H.264/AVC 句法和语义详解】(十二):H264中的帧场编码模式详解
2019-04-30
【从零实现一个H.264码流解析器】(一):从码流中找到NALU
2019-04-30
PHP XML转数组
2019-04-30
PHP CURL请求
2019-04-30
关于那些加密解密的PHP方法--Star.hou
2019-04-30
elasticsearch PHP安装、使用
2019-04-30
Laravel命令行创建控制器、模型、脚本
2019-04-30
Python&NotePad++开发环境
2019-04-30
Paypal Webhook API创建
2019-04-30
laravel之中间件三步走--star.hou
2019-04-30
PHP Windows环境安装Solr扩展
2019-04-30
Paypal Express Checkout快速结账API心得--Star.Hou
2019-04-30
支付网关设计感悟(一)Star.Hou
2019-04-30
支付网关设计感悟(二)Star.Hou
2019-04-30
laravel文件上传excel - star.Hou
2019-04-30
Mysql复制数据库--star.Hou
2019-04-30