区块链是分布式数据存储、点对点传输、共识机制、加密算法等计算机技术的新型应用模式。所谓共识机制是区块链系统中实现不一样节点之间创建信任、获取权益的数学算法 。java
本系列教程旨在帮助你了解如何开发区块链技术。git
本章目标github
(我会假设你对面向对象编程有基本的了解)算法
值得注意的是,这里建立的区块链并非功能彻底的彻底适合应用与生产的区块链,相反只是为了帮助你更好的理解区块链的概念。编程
区块链就是一串或者是一系列区块的集合,相似于链表的概念,每一个区块都指向于后面一个区块,而后顺序的链接在一块儿。那么每一个区块中的内容是什么呢?在区块链中的每个区块都存放了不少颇有价值的信息,主要包括三个部分:本身的数字签名,上一个区块的数字签名,还有一切须要加密的数据(这些数据在比特币中就至关因而交易的信息,它是加密货币的本质)。每一个数字签名不但证实了本身是特有的一个区块,并且指向了前一个区块的来源,让全部的区块在链条中能够串起来,而数据就是一些特定的信息,你能够按照业务逻辑来保存业务数据。json
这里的hash指的就是数字签名小程序
因此每个区块不只包含前一个区块的hash值,同时包含自身的一个hash值,自身的hash
值是经过以前的hash
值和数据data
经过hash
计算出来的。若是前一个区块的数据一旦被篡改了,那么前一个区块的hash值也会一样发生变化(由于数据也被计算在内),这样也就致使了全部后续的区块中的hash
值。因此计算和比对hash值会让咱们检查到当前的区块链是不是有效的,也就避免了数据被恶意篡改的可能性,由于篡改数据就会改变hash值并破坏整个区块链。微信小程序
import java.util.Date;
public 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.
//Block Constructor.
public Block(String data,String previousHash ) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
}
}
复制代码
正如你能够看到咱们的基本块包含String hash
,它将保存咱们的数字签名。变量previoushash
保存前一个块的hash
和String data
来保存咱们的块数据数组
熟悉加密算法的朋友们,Java方式能够实现的加密方式有不少,例如BASE、MD、RSA、SHA等等,我在这里选用了SHA256
这种加密方式,SHA(Secure Hash Algorithm)安全散列算法,这种算法的特色是数据的少许更改会在Hash值中产生不可预知的大量更改,hash值用做表示大量数据的固定大小的惟一值,而SHA256算法的hash值大小为256位。之因此选用SHA256是由于它的大小正合适,一方面产生重复hash值的可能性很小,另外一方面在区块链实际应用过程当中,有可能会产生大量的区块,而使得信息量很大,那么256位的大小就比较恰当了。安全
下面我建立了一个StringUtil
方法来方便调用SHA256算法
import java.security.MessageDigest;
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);
}
}
}
复制代码
或许你彻底不理解上述代码的含义,可是你只要理解全部的输入调用此方法后均会生成一个独一无二的hash值(数字签名),而这个hash值在区块链中是很是重要的。
接下来让咱们在Block
类中应用 方法 applySha256 方法,其主要的目的就是计算hash值,咱们计算的hash值应该包括区块中全部咱们不但愿被恶意篡改的数据,在咱们上面所列的Block
类中就必定包括previousHash
,data
和timeStamp
,
public String calculateHash() {
String calculatedhash = StringUtil.applySha256(
previousHash +
Long.toString(timeStamp) +
data
);
return calculatedhash;
}
复制代码
而后把这个方法加入到Block
的构造函数中去
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.
}
复制代码
在主方法中让咱们建立一些区块,并把其hash值打印出来,来看看是否一切都在咱们的掌控中。
第一个块称为创世纪区块,由于它是头区块,因此咱们只需输入“0”做为前一个块的previous hash
。
public class NoobChain {
public static void main(String[] args) {
Block genesisBlock = new Block("Hi im the first block", "0");
System.out.println("Hash for block 1 : " + genesisBlock.hash);
Block secondBlock = new Block("Yo im the second block",genesisBlock.hash);
System.out.println("Hash for block 2 : " + secondBlock.hash);
Block thirdBlock = new Block("Hey im the third block",secondBlock.hash);
System.out.println("Hash for block 3 : " + thirdBlock.hash);
}
}
复制代码
打印:
Hash for block 1: f6d1bc5f7b0016eab53ec022db9a5d9e1873ee78513b1c666696e66777fe55fb
Hash for block 2: 6936612b3380660840f22ee6cb8b72ffc01dbca5369f305b92018321d883f4a3
Hash for block 3: f3e58f74b5adbd59a7a1fc68c97055d42e94d33f6c322d87b29ab20d3c959b8f
复制代码
每个区块都必需要有本身的数据签名即hash值,这个hash值依赖于自身的信息(data)和上一个区块的数字签名(previousHash),但这个还不是区块链,下面让咱们存储区块到数组中,这里我会引入gson包,目的是能够用json方式查看整个一条区块链结构。
import java.util.ArrayList;
import com.google.gson.GsonBuilder;
public class NoobChain {
public static ArrayList<Block> blockchain = new ArrayList<Block>();
public static void main(String[] args) {
//add our blocks to the blockchain ArrayList:
blockchain.add(new Block("Hi im the first block", "0"));
blockchain.add(new Block("Yo im the second block",blockchain.get(blockchain.size()-1).hash));
blockchain.add(new Block("Hey im the third block",blockchain.get(blockchain.size()-1).hash));
String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
System.out.println(blockchainJson);
}
}
复制代码
这样的输出结构就更相似于咱们所期待的区块链的样子。
在主方法中增长一个isChainValid()方法,目的是循环区块链中的全部区块而且比较hash值,这个方法用来检查hash值是不是于计算出来的hash值相等,同时previousHash值是否和前一个区块的hash值相等。或许你会产生以下的疑问,咱们就在一个主函数中建立区块链中的区块,因此不存在被修改的可能性,可是你要注意的是,区块链中的一个核心概念就是去中心化,每个区块多是在网络中的某一个节点中产生的,因此颇有可能某个节点把本身节点中的数据修改了,那么根据上述的理论数据改变会致使整个区块链的破裂,也就是区块链就无效了。
public static Boolean isChainValid() {
Block currentBlock;
Block previousBlock;
//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;
}
}
return true;
}
复制代码
任何区块链中区块的一丝一毫改变都会致使这个函数返回false,也就证实了区块链无效了。
在比特币网络中全部的网络节点都分享了它们各自的区块链,然而最长的有效区块链是被全网所统一认可的,若是有人恶意来篡改以前的数据,而后建立一条更长的区块链并全网发布呈如今网络中,咱们该怎么办呢?这就涉及到了区块链中另一个重要的概念工做量证实,这里就不得不说起一下hashcash,这个概念最先来自于Adam Back的一篇论文,主要应用于邮件过滤和比特币中防止双重支付。
这里咱们要求挖矿者作工做量证实,具体的方式是在区块中尝试不一样的参数值直到它的hash值是从一系列的0开始的。让咱们添加一个名为nonce
的int类型以包含在咱们的calculatehash()
方法中,以及须要的mineblock()
方法
import java.util.Date;
public 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"
while(!hash.substring( 0, difficulty).equals(target)) {
nonce ++;
hash = calculateHash();
}
System.out.println("Block Mined!!! : " + hash);
}
}
复制代码
mineBlock()方法中引入了一个int值称为difficulty难度,低的难度好比1和2,普通的电脑基本均可以立刻计算出来,个人建议是在4-6之间进行测试,普通电脑大概会花费3秒时间,在莱特币中难度大概围绕在442592左右,而在比特币中每一次挖矿都要求大概在10分钟左右,固然根据全部网络中的计算能力,难度也会不断的进行修改。
咱们在NoobChain
类 中增长difficulty
这个静态变量。
public static int difficulty = 5;
复制代码
这样咱们必须修改主方法中让建立每一个新区块时必须触发mineBlock()
方法,而isChainValid()
方法用来检查每一个区块的hash值是否正确,整个区块链是不是有效的。
import java.util.ArrayList;
import com.google.gson.GsonBuilder;
public class NoobChain {
public static ArrayList<Block> blockchain = new ArrayList<Block>();
public static int difficulty = 5;
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;
}
}
复制代码
打印:
Connected to the target VM, address: '127.0.0.1:61863', transport: 'socket'
Trying to Mine block 1...
Block Mined!!! : 0000016667d4240e9c30f53015310b0ec6ce99032d7e1d66d670afc509cab082
Trying to Mine block 2...
Block Mined!!! : 000002ea55735bea4cac7e358c7b0d8d81e8ca24021f5f85211bf54fd4ac795a
Trying to Mine block 3...
Block Mined!!! : 000000576987e5e9afbdf19b512b2b7d0c56db0e6ca49b3a7e638177f617994b
Blockchain is Valid: true
[
{
"hash": "0000016667d4240e9c30f53015310b0ec6ce99032d7e1d66d670afc509cab082",
"previousHash": "0",
"data": "first",
"timeStamp": 1520659506042,
"nonce": 618139
},
{
"hash": "000002ea55735bea4cac7e358c7b0d8d81e8ca24021f5f85211bf54fd4ac795a",
"previousHash": "0000016667d4240e9c30f53015310b0ec6ce99032d7e1d66d670afc509cab082",
"data": "second",
"timeStamp": 1520659508825,
"nonce": 1819877
},
{
"hash": "000000576987e5e9afbdf19b512b2b7d0c56db0e6ca49b3a7e638177f617994b",
"previousHash": "000002ea55735bea4cac7e358c7b0d8d81e8ca24021f5f85211bf54fd4ac795a",
"data": "third",
"timeStamp": 1520659515910,
"nonce": 1404341
}
]
复制代码
通过测试增长一个新的区块即挖矿必须花费必定时间,大概是3秒左右,你能够提升difficulty难度来看,它是如何影响数据难题所花费的时间的
若是有人在你的区块链系统中恶意篡改数据:
由于篡改的区块链将没法遇上长链和有效链,除非他们比你网络中全部的节点拥有更大的计算速度,多是将来的量子计算机或者是其余什么。
你的区块链:
原文连接:Creating Your First Blockchain with Java. Part 1.
从个人 github 中下载,github.com/longfeizhen…
🙂🙂🙂关注微信小程序java架构师历程 上下班的路上无聊吗?还在看小说、新闻吗?不知道怎样提升本身的技术吗?来吧这里有你须要的java架构文章,1.5w+的java工程师都在看,你还在等什么?