1. Overview
1.概述
In this tutorial, we’ll learn the basic concepts of blockchain technology. We’ll also implement a basic application in Java that focuses on the concepts.
在本教程中,我们将学习区块链技术的基本概念。我们还将在Java中实现一个关注这些概念的基本应用。
Further, we’ll discuss some advanced concepts and practical applications of this technology.
此外,我们将讨论这项技术的一些先进概念和实际应用。
2. What Is Blockchain?
2.什么是区块链?
So, let’s first understand what exactly blockchain is…
因此,让我们首先了解区块链到底是什么…
Well, it traces its origin back to the whitepaper published by Satoshi Nakamoto on Bitcoin, back in 2008.
那么,它的起源可以追溯到2008年中本聪发表的关于比特币的白皮书。
Blockchain is a decentralized ledger of information. It consists of blocks of data connected through the use of cryptography. It belongs to a network of nodes connected over the public network. We’ll understand this better when we attempt to build a basic tutorial later on.
区块链是一个分散的信息分类账。它由通过使用密码学连接的数据块组成。它属于一个通过公共网络连接的节点网络。当我们以后尝试建立一个基本的教程时,我们会更好地理解这一点。
There are some important attributes that we must understand, so let’s go through them:
有一些重要的属性是我们必须了解的,所以我们来看看这些属性。
- Tamper-proof: First and foremost, data as part of a block is tamper-proof. Every block is referenced by a cryptographic digest, commonly known as a hash, making the block tamper-proof.
- Decentralized: The entire blockchain is completely decentralized across the network. This means that there is no master node, and every node in the network has the same copy.
- Transparent: Every node participating in the network validates and adds a new block to its chain through consensus with other nodes. Hence, every node has complete visibility of the data.
3. How Does Blockchain Work?
3.区块链是如何工作的?
Now, let’s understand how blockchain works.
现在,让我们了解一下区块链的工作原理。
The fundamental units of a blockchain are blocks. A single block can encapsulate several transactions or other valuable data:
区块链的基本单位是区块。一个区块可以囊括几个交易或其他有价值的数据。
3.1. Mining a Block
3.1.挖掘一个区块
We represent a block by a hash value. Generating the hash value of a block is called “mining” the block. Mining a block is typically computationally expensive to do as it serves as the “proof of work”.
我们用一个哈希值来表示一个区块。生成一个区块的哈希值被称为 “挖掘”区块。挖掘一个区块通常在计算上是昂贵的,因为它是 “工作证明”。
The hash of a block typically consists of the following data:
一个区块的哈希值通常由以下数据组成。
- Primarily, the hash of a block consists of the transactions it encapsulates
- The hash also consists of the timestamp of the block’s creation
- It also includes a nonce, an arbitrary number used in cryptography
- Finally, the hash of the current block also includes the hash of the previous block
Multiple nodes in the network can compete to mine the block at the same time. Apart from generating the hash, nodes also have to verify that the transactions being added in the block are legitimate. The first to mine a block wins the race!
网络中的多个节点可以同时竞争开采区块。除了生成哈希值,节点还必须验证区块中添加的交易是否合法。第一个挖出区块的人赢得比赛!
3.2. Adding a Block into Blockchain
3.2.在区块链中添加区块
While mining a block is computationally expensive, verifying that a block is legitimate is relatively much easier. All nodes in the network participate in verifying a newly mined block.
虽然开采一个区块的计算成本很高,但验证一个区块的合法性相对要容易得多。网络中的所有节点都参与验证一个新开采的区块。
Thus, a newly mined block is added into the blockchain on the consensus of the nodes.
因此,一个新开采的区块在节点的共识下被添加到区块链中。
Now, there are several consensus protocols available which we can use for verification. The nodes in the network use the same protocol to detect malicious branch of the chain. Hence, a malicious branch even if introduced will soon be rejected by the majority of the nodes.
现在,有几个可用的共识协议,我们可以用它来验证。网络中的节点使用相同的协议来检测链上的恶意分支。因此,一个恶意的分支即使被引入,也会很快被大多数的节点所拒绝。
4. Basic Blockchain in Java
4.Java中的基本区块链
Now we’ve got enough context to start building a basic application in Java.
现在我们已经有了足够的背景,可以开始用Java构建一个基本的应用程序。
Our simple example here will illustrate the basic concepts we just saw. A production-grade application entails a lot of considerations which are beyond the scope of this tutorial. We’ll, however, touch upon some advanced topics later on.
我们这里的简单例子将说明我们刚刚看到的基本概念。一个生产级的应用程序需要考虑很多问题,这超出了本教程的范围。然而,我们将在后面的内容中触及一些高级主题。
4.1. Implementing a Block
4.1.实现一个区块
Firstly, we need to define a simple POJO that will hold the data for our block:
首先,我们需要定义一个简单的POJO,它将保存我们区块的数据。
public class Block {
private String hash;
private String previousHash;
private String data;
private long timeStamp;
private int nonce;
public Block(String data, String previousHash, long timeStamp) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = timeStamp;
this.hash = calculateBlockHash();
}
// standard getters and setters
}
Let’s understand what we’ve packed here:
让我们了解一下我们在这里打包的东西。
- Hash of the previous block, an important part to build the chain
- The actual data, any information having value, like a contract
- The timestamp of the creation of this block
- A nonce, which is an arbitrary number used in cryptography
- Finally, the hash of this block, calculated based on other data
4.2. Calculating the Hash
4.2.计算哈希值
Now, how do we calculate the hash of a block? We’ve used a method calculateBlockHash but have not seen an implementation yet. Before we implement this method, it’s worth spending some time to understand what exactly is a hash.
现在,我们如何计算一个区块的哈希值?我们已经使用了一个方法calculateBlockHash,但还没有看到实现。在我们实现这个方法之前,值得花一些时间来理解到底什么是哈希值。
A hash is an output of something known as a hash function. A hash function maps input data of arbitrary size to output data of fixed size. The hash is quite sensitive to any change in the input data, however small that may be.
散列是一种被称为散列函数的东西的输出。一个哈希函数将任意大小的输入数据映射到固定大小的输出数据。哈希值对输入数据的任何变化都相当敏感,无论这种变化有多小。
Moreover, it’s impossible to get the input data back just from its hash. These properties make the hash function quite useful in cryptography.
此外,不可能仅从其哈希值中取回输入数据。这些特性使哈希函数在密码学中相当有用。
So, let’s see how we can generate the hash of our block in Java:
所以,让我们看看如何在Java中生成我们区块的哈希值。
public String calculateBlockHash() {
String dataToHash = previousHash
+ Long.toString(timeStamp)
+ Integer.toString(nonce)
+ data;
MessageDigest digest = null;
byte[] bytes = null;
try {
digest = MessageDigest.getInstance("SHA-256");
bytes = digest.digest(dataToHash.getBytes(UTF_8));
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
logger.log(Level.SEVERE, ex.getMessage());
}
StringBuffer buffer = new StringBuffer();
for (byte b : bytes) {
buffer.append(String.format("%02x", b));
}
return buffer.toString();
}
Quite a lot of things happening here, let’s understand them in detail:
这里发生了相当多的事情,让我们详细了解一下。
- First, we concatenate different parts of the block to generate a hash from
- Then, we get an instance of the SHA-256 hash function from MessageDigest
- Then, we generate the hash value of our input data, which is a byte array
- Finally, we transform the byte array into a hex string, a hash is typically represented as a 32-digit hex number
4.3. Have We Mined the Block Yet?
4.3.我们已经开采了区块吗?
Everything sounds simple and elegant so far, except for the fact that we’ve not mined the block yet. So what exactly entails mining a block, which has captured the fancy of developers for some time now!
到目前为止,一切听起来都很简单和优雅,除了我们还没有挖到区块的事实。那么,到底是什么需要开采一个区块,这已经吸引了一段时间的开发者的注意!?
Well, mining a block means solving a computationally complex task for the block. While calculating the hash of a block is somewhat trivial, finding the hash starting with five zeroes is not. Even more complicated would be to find a hash starting with ten zeroes, and we get a general idea.
那么,挖掘一个区块意味着为该区块解决一个计算上的复杂任务。虽然计算一个区块的哈希值有些微不足道,但找到从五个零开始的哈希值并不容易。更加复杂的是,要找到从十个零开始的哈希值,我们就有了一个大致的概念。
So, how exactly can we do this? Honestly, the solution is much less fancy! It’s with brute force that we attempt to achieve this goal. We make use of nonce here:
那么,我们究竟如何才能做到这一点?老实说,解决方案没有那么多花哨的东西!我们是用蛮力来实现这个目标的。我们在这里使用了nonce。
public String mineBlock(int prefix) {
String prefixString = new String(new char[prefix]).replace('\0', '0');
while (!hash.substring(0, prefix).equals(prefixString)) {
nonce++;
hash = calculateBlockHash();
}
return hash;
}
Let’s see what we trying to do here are:
让我们看看我们在这里要做的是什么。
- We start by defining the prefix we desire to find
- Then we check whether we’ve found the solution
- If not we increment the nonce and calculate the hash in a loop
- The loop goes on until we hit the jackpot
We’re starting with the default value of nonce here and incrementing it by one. But there are more sophisticated strategies to start and increment a nonce in real-world applications. Also, we’re not verifying our data here, which is typically an important part.
我们在这里从nonce的默认值开始,并以1为单位递增。但在现实世界的应用中,有更多的复杂策略来启动和增加nonce。另外,我们在这里没有验证我们的数据,这通常是一个重要的部分。
4.4. Let’s Run the Example
4.4.我们来运行这个例子
Now that we’ve our block defined along with its functions, we can use this to create a simple blockchain. We’ll store this in an ArrayList:
现在我们已经定义了我们的区块和它的功能,我们可以用它来创建一个简单的区块链。我们将把它存储在一个ArrayList中。
List<Block> blockchain = new ArrayList<>();
int prefix = 4;
String prefixString = new String(new char[prefix]).replace('\0', '0');
Additionally, we’ve defined a prefix of four, which effectively means that we want our hash to start with four zeroes.
此外,我们定义了一个四的前缀,这实际上意味着我们希望我们的哈希值以四个零开始。
Let’s see how can we add a block here:
让我们看看如何在这里添加一个块。
@Test
public void givenBlockchain_whenNewBlockAdded_thenSuccess() {
Block newBlock = new Block(
"The is a New Block.",
blockchain.get(blockchain.size() - 1).getHash(),
new Date().getTime());
newBlock.mineBlock(prefix);
assertTrue(newBlock.getHash().substring(0, prefix).equals(prefixString));
blockchain.add(newBlock);
}
4.5. Blockchain Verification
4.5.区块链验证
How can a node validate that a blockchain is valid? While this can be quite complicated, let’s think about a simple version:
一个节点如何验证一个区块链是有效的?虽然这可能相当复杂,但让我们想想一个简单的版本。
@Test
public void givenBlockchain_whenValidated_thenSuccess() {
boolean flag = true;
for (int i = 0; i < blockchain.size(); i++) {
String previousHash = i==0 ? "0" : blockchain.get(i - 1).getHash();
flag = blockchain.get(i).getHash().equals(blockchain.get(i).calculateBlockHash())
&& previousHash.equals(blockchain.get(i).getPreviousHash())
&& blockchain.get(i).getHash().substring(0, prefix).equals(prefixString);
if (!flag) break;
}
assertTrue(flag);
}
So, here we’re making three specific checks for every block:
因此,在这里,我们对每个区块都进行了三次具体的检查。
- The stored hash of the current block is actually what it calculates
- The hash of the previous block stored in the current block is the hash of the previous block
- The current block has been mined
5. Some Advanced Concepts
5.一些高级概念
While our basic example brings out the basic concepts of a blockchain, it’s certainly not complete. To put this technology into practical use, several other considerations need to be factored in.
虽然我们的基本例子带出了区块链的基本概念,但它肯定不是完整的。要将这项技术投入实际使用,还需要考虑其他几个因素。
While it’s not possible to detail all of them, let’s go through some of the important ones:
虽然不可能详细说明所有的问题,但让我们来看看其中一些重要的问题。
5.1. Transaction Verification
5.1.事务验证
Calculating the hash of a block and finding the desired hash is just one part of mining. A block consists of data, often in the form of multiple transactions. These must be verified before they can be made part of a block and mined.
计算一个区块的哈希值并找到所需的哈希值,只是挖矿的一个部分。一个区块由数据组成,通常以多个交易的形式存在。这些数据必须经过验证才能成为区块的一部分并被开采。
A typical implementation of blockchain sets a restriction on how much data can be part of a block. It also sets up rules on how a transaction can be verified. Multiple nodes in the network participate in the verification process.
一个典型的区块链的实现,对一个区块可以有多少数据设置了限制。它还为交易如何被验证设定了规则。网络中的多个节点参与了验证过程。
5.2. Alternate Consensus Protocol
5.2.备选的共识协议
We saw that consensus algorithm like “Proof of Work” is used to mine and validate a block. However, this is not the only consensus algorithm available for use.
我们看到,像 “工作证明 “这样的共识算法被用来挖掘和验证一个区块。然而,这并不是唯一可供使用的共识算法。
There are several other consensus algorithms to choose from, like Proof of Stake, Proof of Authority, and Proof of Weight. All of these have their pros and cons. Which one to use depends upon the type of application we intend to design.
还有其他几种共识算法可供选择,如股权证明、权力证明和重量证明。所有这些都有其优点和缺点。使用哪种算法取决于我们打算设计的应用程序的类型。
5.3. Mining Reward
5.3.采矿奖赏
A blockchain network typically consists of voluntary nodes. Now, why would anyone want to contribute to this complex process and keep it legit and growing?
一个区块链网络通常由自愿的节点组成。现在,为什么有人愿意为这个复杂的过程做出贡献,并保持它的合法性和增长?
This is because nodes are rewarded for verifying the transactions and mining a block. These rewards are typically in the form of coin associated with the application. But an application can decide the reward to be anything of value.
这是因为节点验证交易和挖掘区块会得到奖励。这些奖励通常是以与应用程序相关的硬币形式出现。但一个应用程序可以决定奖励是任何有价值的东西。
5.4. Node Types
5.4.节点类型
A blockchain completely relies on its network to operate. In theory, the network is completely decentralized, and every node is equal. However, in practice, a network consists of multiple types of nodes.
一个区块链完全依靠其网络来运作。在理论上,网络是完全去中心化的,每个节点都是平等的。然而,在实践中,一个网络由多种类型的节点组成。
While a full node has a complete list of transactions, a light node only has a partial list. Moreover, not all nodes participate in verification and validation.
虽然一个完整的节点有一个完整的交易列表,但一个轻型节点只有一个部分列表。此外,并不是所有的节点都参与核查和验证。
5.5. Secure Communication
5.5.安全通信
One of the hallmarks of blockchain technology is its openness and anonymity. But how does it provide security to transactions being carried within? This is based on cryptography and public key infrastructure.
区块链技术的标志之一是其开放性和匿名性。但它是如何为内部进行的交易提供安全保障的呢?这就是基于密码学和公钥基础设施的。
The initiator of a transaction uses their private key to secure it and attach it to the public key of the recipient. Nodes can use the public keys of the participants to verify transactions.
交易的发起人使用他们的私钥来保证交易的安全,并将其附加到收件人的公钥上。节点可以使用参与者的公钥来验证交易。
6. Practical Applications of Blockchain
6.区块链的实际应用
So, blockchain seems to be an exciting technology, but it also must prove useful. This technology has been around for some time now and – needless to say – it has proved to be disruptive in many domains.
因此,区块链似乎是一项令人兴奋的技术,但它也必须证明是有用的。这项技术已经存在了一段时间,而且–不用说–它已经证明在许多领域具有颠覆性。
Its application in many other areas is being actively pursued. Let’s understand the most popular applications:
它在许多其他领域的应用正在积极进行中。让我们了解一下最受欢迎的应用。
- Currency: This is by far the oldest and most widely known use of blockchain, thanks to the success of Bitcoin. They provide secure and frictionless money to people across the globe without any central authority or government intervention.
- Identity: Digital identity is fast becoming the norm in the present world. However, this is mired by security issues and tampering. Blockchain is inevitable in revolutionizing this area with completely secure and tamper-proof identities.
- Healthcare: Healthcare industry is loaded with data, mostly handled by central authorities. This decreases transparency, security, and efficiency in handling such data. Blockchain technology can provide a system without any third party to provide much-needed trust.
- Government: This is perhaps an area which is well open to disruption by the blockchain technology. Government is typically at the center of several citizen services which are often laden with inefficiencies and corruption. Blockchain can help establish much better government-citizen relations.
7. Tools of the Trade
7.事务的工具
While our basic implementation here is useful to elicit the concepts, it’s not practical to develop a product on blockchain from scratch. Thankfully, this space has matured now, and we do have some quite useful tools to start from.
虽然我们在这里的基本实现对引出这些概念是有用的,但从头开始在区块链上开发一个产品是不现实的。值得庆幸的是,这个领域现在已经成熟了,我们确实有一些相当有用的工具可以开始。
Let’s go through some of the popular tools to work within this space:
让我们来看看在这个空间内工作的一些流行工具。
- Solidity: Solidity is a statically-typed and object-oriented programming language designed for writing smart contracts. It can be used to write smart contracts on various blockchain platforms like Ethereum.
- Remix IDE: Remix is a powerful open-source tool to write smart contracts in Solidity. This enables the user to write smart contracts right from the browser.
- Truffle Suite: Truffle provides a bunch of tools to get a developer up and started in developing distributed apps. This includes Truffle, Ganache, and Drizzle.
- Ethlint/Solium: Solium allows developers to ensure that their smart contracts written on Solidity is free from style and security issues. Solium also helps in fixing these issues.
- Parity: Parity helps in setting up the development environment for smart contract on Etherium. It provides a fast and secure way to interact with the blockchain.
8. Conclusion
8.结语
To sum up, in this tutorial, we went through the basic concepts of blockchain technology. We understood how a network mine and add a new block in the blockchain. Further, we implemented the basic concepts in Java. We also discussed some of the advanced concepts related to this technology.
总而言之,在本教程中,我们经历了区块链技术的基本概念。我们了解了网络如何在区块链中挖掘和添加新的区块。此外,我们用Java实现了这些基本概念。我们还讨论了与该技术相关的一些高级概念。
Finally, we wrapped up with some practical applications of blockchain and as well as available tools.
最后,我们以区块链的一些实际应用和以及可用的工具做了总结。
As always, the code can be found over on GitHub.
一如既往,代码可以在GitHub上找到over。