Blockchain related technologies, concepts and some key issues in the process of technology implementation Smart Contracts and Blockchains

Author: Zen and the Art of Computer Programming

1 Introduction

At the end of 2017, blockchain has become one of the topics of greatest concern to many investors and technicians. With the increasing complexity of the real world, the popularity of digital currencies, and the proliferation of IoT devices, the cryptocurrency market is becoming increasingly active. Because blockchain has the characteristics of decentralization, non-tampering, transparency, and high concurrency, it has been widely used in the financial field, especially in poor areas such as African countries and Latin America. As of April 2019, more than 400 million people around the world have joined the cryptocurrency market. With the development of blockchain technology, the scale of the encrypted digital currency market will continue to expand, and it will become a true decentralized financial platform in the future. Therefore, this article will elaborate on blockchain-related technologies, concepts, and some key issues in the technology implementation process.

2.Basic concepts and terminology

1. Blockchain (Blockchain)
Blockchain is a distributed database that saves all transaction data, and each node verifies, records and executes transactions according to the same rules. Every transaction on the blockchain is reliable and cannot be tampered with, and no party can cancel or modify the data on the chain. Blockchain can be thought of as a decentralized ledger that stores digital information and is used to ensure the validity, authorization, and fairness of transactions. The blockchain consists of a linear chain, and each block (Block) refers to the previous block. Blockchain usually consists of multiple nodes (peers) communicating through a P2P network. These nodes copy, verify, confirm, and track information with each other.
Why is blockchain needed?
Traditional business systems often have the following flaws:

  1. Dispersion: There are no shared resources among various participants, resulting in the inability to share information, resulting in information asymmetry;
  2. Traceability: Since all parties cannot see all transaction records, the transaction cannot be comprehensive and lacks public transparency;
  3. High cost: Purchasing goods and services requires a third-party payment institution, and the payment price is high.

Based on the above reasons, blockchain emerged, which solves these problems and has the following advantages:

  1. Dispersion: Record all the data in the system together so that any party can view the complete record;
  2. Traceability: Everyone can query the history of the entire transaction to ensure openness and transparency of the transaction;
  3. Low cost: Using blockchain can reduce transaction fees and operating costs, thereby improving efficiency.

2. Cryptocurrency
Cryptocurrency is a digital asset based on blockchain. Cryptocurrency refers to a virtual currency that can create, send, receive and store encrypted information on a computer network. It is essentially a programmed digital coin or encrypted digital currency that can be freely transferred and traded in a decentralized network. Cryptocurrency solves the shortcomings of physical currency (such as gold) - there is no central authority, it can provide higher liquidity, larger B volume, and can be used as a payment, stored value tool, or as a legal currency. There are currently many cryptocurrencies used to pay and trade digital assets, such as Bitcoin, Litecoin, Ethereum, etc.

3. Smart contract
Smart contract is an agreement that uses computer programming capabilities to automatically execute the terms of a transaction contract. It allows users to automatically execute obligations in contracts on the digital currency network and automatically fulfill agreements. Its basic characteristics include: non-repudiation, transparency, independent effectiveness, and high efficiency. The operation of smart contracts relies on a consensus mechanism to ensure that all participants can reach an agreement with their consent. Smart contracts typically take the form of software, but may also be deployed cryptographically, such as in contract programming languages.
4. Alliance chain
(Permissioned blockchain) is a blockchain under shared management. The nodes on the chain only have limited permissions and cannot be added or deleted at will. However, they can still join it as a public participant to build a decentralized network. ized network. The purpose of the alliance chain is to realize multi-party control of on-chain services in different fields, so that there is a need for data exchange and collaboration between participants. The alliance chain can be applied to the needs of different scenarios, such as supply chain management, game economy, contract management, medical and health care, and electronic certificate storage.

5. Sidechain
Sidechain is a solution for entrusting assets to another public chain. It is mainly used to solve the performance bottleneck of a single public chain. The assets of the side chain are traded through the Internet, making full use of the global network and underlying technical capabilities of the public chain. Sidechains usually support different asset types, including DB, crypto assets, trading assets, bonds, etc. The side chain and the main chain are in two different blockchains, realizing the interoperability of assets and value. There are two models of side chains, one is directly connected to the main chain, and the other is a model that operates independently.

6. Privacy protection
The privacy risks caused by storing personal data on the blockchain have always been a pressing issue. Traditional storage methods often have problems such as information leakage, data exposure, and freezing risks. Privacy protection on the blockchain mainly includes methods such as anonymity, zero-knowledge proof, smart contracts, and linkability. Anonymity mechanisms can prevent users’ true identities from being recorded, zero-knowledge proofs can hide key information, smart contracts can automatically audit and execute contracts, and linkability can enable personal data sharing between different institutions.

7. Incentive mechanism:
When issuing a new currency or providing a certain service on the blockchain, the incentive mechanism must also be considered. The incentive mechanism can encourage participants to continue to maintain the platform, promote good interaction in the community, and increase the popularity of the platform. At present, many blockchain projects have adopted incentive mechanisms, such as the Ethereum block reward mechanism, the NEM million-level community reward plan, etc.

3. Core algorithm principles and specific operation steps

1. Consensus algorithm
The consensus algorithm of the blockchain determines the workflow of the entire blockchain. There are two consensus algorithms: proof-of-work and proof-of-stake. Proof-of-work is proof of work, which requires a lot of computing power to generate new blocks, and is a computationally intensive algorithm; proof-of-stake is proof of equity, and you only need to hold a certain number of coins to participate in the consensus. It is an algorithm that is unbearable for devices with smaller network capacity and less computing power.
B's consensus algorithm is proof-of-work, which uses proof-of-work (POW) and consumes a lot of computing power to verify transactions. The initial total supply of B is 21 million, and the number of B produced is halved every four years. According to the current computing power requirements, the generation time of a new block is about 10 minutes, and miners need to calculate a number that meets the difficulty requirements to obtain the corresponding coins.

Ethereum's consensus algorithm is proof-of-stake, which uses proof of stake (POS). You only need to hold a certain number of coins to participate in the consensus. The initial total amount of Ethereum is the number of Ethereum coins. Among the founding nodes of Ethereum, 90% of the coins are held by nodes that have been held for more than 10 years. 1% more coins are issued every year and are halved every 12 months. The generation time of new blocks is approximately 3 seconds. Compared with B, Ethereum's consensus is faster and more secure.

In addition, the consensus mechanism of Ethereum has a feature that the account balance can be withdrawn. If a hacker attack occurs at an address, you can redeem your coins by destroying the account. This mechanism ensures the decentralization and security of the platform.

In addition, there are some other consensus algorithms, such as Delegated Proof of Stake (DPoS), Delegated Proof of Authority (DPoA), etc.

2. The PoW algorithm used by mining algorithm
B is a typical Proof of Work algorithm. In the algorithm, miners calculate complex hash operations to find a nonce that meets the conditions, and this value becomes the identifier of the next block. The size of the nonce is related to the number of transactions contained in the block. That is, the greater the transaction volume, the more difficult it is to find the nonce.

The PoS algorithm used by Ethereum is a Proof of Stake algorithm. In the algorithm, users can only entrust their coins to some nodes, which have voting rights when blocks are generated. Finally, the node with the most votes will generate a new block.

In addition to the above two consensus algorithms, there are also some hybrid consensus algorithms, such as the Tendermint/BFT consensus algorithm. Tendermint provides a Byzantine fault-tolerant consensus mechanism, and BFT uses the Byzantine Fault Tolerance (Byzantine Fault Tolerance) algorithm for fault tolerance.

3. Account model
The account model on the blockchain is different from the account models in other distributed networks. The account model in traditional distributed networks is centralized, with network service providers or administrators controlling accounts, and other nodes in the network can access these accounts. The account model of the blockchain is decentralized, and anyone can create an account and access their own assets. An account on the blockchain mainly consists of two parts: address and balance. The address is the unique identifier of the account and is used to identify and pay for the assets in the account; the balance represents the number of coins owned by the account.

In Ethereum, the account address consists of 20 bytes and is used to save the user's public key. The public key is used to identify the account. This process is implemented through the elliptic curve encryption algorithm. The user's private key is used to sign transactions to prevent transactions from being forged. The balance of the account is stored on the Ethereum blockchain, and users can perform transfers, payments, pledges and other operations by sending transactions. In addition, Ethereum also provides ERC20 Token technology, allowing users to customize their own Token DB.

4. Transaction model
There are two main types of transaction models in blockchain: UTXO model and account model. The UTXO model is the simplest transaction model and also the current mainstream transaction model. In the UTXO model, all inputs and outputs of a transaction are represented as UTXO. The user first selects the UTXO he wants to spend, then generates a new UTXO as the output of the transaction, and then transfers the money to the original input address to complete a transaction.

Ethereum's account model is similar to that of other mainstream blockchains, but Ethereum's transaction model is more complex. Ethereum's transaction model includes two types: status and message. The state transition function is used to describe the status changes of the account, and the message is used to describe the transaction. There are two main types of state transition functions: state dependence functions and state migration functions. The state-dependent function takes information from the account's input UTXO and then computes the new state in the output UTXO. The state migration function generates a state tree based on the input UTXO and output UTXO of the transaction to represent the account's state transition relationship. Ethereum's state transition adopts an account model, and users can perform transfers, payments, pledges and other operations by sending transactions. Messages are used to encode transaction behavior and are sent to the network as part of the transaction. Messages can contain information in any format, including text, binary data, pictures, video, audio, etc.

When a user wants to initiate a transaction, he or she needs to determine the Gas limit to be used. Gas represents the amount of computing resources used to execute transactions, and users need to pay a certain fee to maintain the normal operation of the platform. Gas prices are adjusted according to the actual situation of the network to ensure that transactions are completed quickly.

5. Smart Contract
Smart Contract is an agreement that uses computer programming capabilities to automatically execute the terms of a transaction contract. The basic characteristics of smart contracts include: non-repudiation, transparency, autonomous effectiveness, and high efficiency. The operation of smart contracts relies on a consensus mechanism to ensure that all participants can reach an agreement with their consent. Smart contracts typically take the form of software, but may also be deployed cryptographically, such as in contract programming languages.

6. Sidechain
Sidechain is a solution for entrusting assets to another public chain. It is mainly used to solve the performance bottleneck of a single public chain. The assets of the side chain are traded through the Internet, making full use of the global network and underlying technical capabilities of the public chain. Sidechains usually support different asset types, including DB, crypto assets, trading assets, bonds, etc. The side chain and the main chain are in two different blockchains, realizing the interoperability of assets and value.

4. Specific code examples and explanations

This section will provide specific code examples and explanations of key issues in the above technologies, concepts, algorithms and operational steps.
1. Contract development language
The main development languages ​​for smart contracts include Solidity, Vyper, Lisp, etc. Solidity is one of the most popular languages ​​and is compatible with Ethereum.
2.Solidity sample code

pragma solidity ^0.4.22;

// @title A simple example contract
contract Example {
uint public count = 0;

function increase() public returns (uint) {
count++;
return count;
}
}

The example code above defines a Examplecontract named and a countvariable named . increase()The function increments countand returns the new one count.
3. Constructor
In Solidity, a contract can set a constructor, which will be automatically called when the contract is deployed. The constructor of a contract can only have one entry parameter, msg.sender, which represents the publisher of the contract. For example, when initializing a contract, you can use the constructor to set the initial value.

pragma solidity ^0.4.22;

// @title A simple example contract
contract Example {
uint public count = 0;

constructor() public{

}

function increase() public returns (uint) {
count++;
return count;
}
}

In the above example code, the constructor is empty, that is, no parameters are passed in. Assume that when deploying the contract, countthe initial value that needs to be set is 10. The constructor can be modified as follows:

pragma solidity ^0.4.22;

// @title A simple example contract
contract Example {
uint public count = 10;

constructor() public{}

function increase() public returns (uint) {
count++;
return count;
}
}

In this way, countthe initial value of the contract is 10.
4. Events
Smart contracts can use events to track state changes of the contract. Events can help developers track the status changes of the contract and the data attached when the event is triggered. For example, when increase()a function is called, an event can be triggered Increased.

pragma solidity ^0.4.22;

// @title A simple example contract
contract Example {
uint public count = 0;

event Increased(address indexed _from, address indexed _to, uint value);

constructor() public {}

function increase() public returns (uint) {
count++;
emit Increased(msg.sender, address(this), count);
return count;
}
}

In the sample code above, an Increasedevent named is introduced. When calling increase(), the contract will trigger Increasedthe event with three parameters. The first parameter _fromis the triggering party of the event, the second parameter _tois the address of the current contract, and the third parameter valueis countthe new value of .
5. Transaction transfer
There are two types of transactions that can be carried out in smart contracts: ordinary transfers and internal transfers. Ordinary transfers are generally used for transfers between users, while internal transfers are used for transfers between contracts.

Ordinary transfer:
You can use the transfer() or send() method to transfer funds. transfer() and send() are both methods for transferring money. The difference between them is that send() can only be used when the transfer amount is less than or equal to the transfer account balance, while transfer() is not restricted.

pragma solidity ^0.4.22;

// @title A simple example contract
contract Example {
mapping(address => uint) balances;
address owner;

constructor() public {
owner = msg.sender;
}

function deposit() public payable {
require(msg.value > 0);

balances[msg.sender] += msg.value;
}

function withdraw(uint amount) public {
require(balances[msg.sender] >= amount);

balances[msg.sender] -= amount;
msg.sender.transfer(amount);
}

}

In the above sample code, a balancesmapping table named is introduced to record the user's balance. Set in the constructor ownerto the address of the contract publisher.

Users can deposit ETH to the contract through the deposit() method. The code of the deposit() method is as follows:

function deposit() public payable {
require(msg.value > 0);

balances[msg.sender] += msg.value;
}

The deposit() method determines whether the user has sent ETH. If so, it updates balancesthe user's balance in the table. Users can call the withdraw() method to get back the ETH they sent. The code for the withdraw() method is as follows:

function withdraw(uint amount) public {
require(balances[msg.sender] >= amount);

balances[msg.sender] -= amount;
msg.sender.transfer(amount);
}

The withdraw() method determines whether the user's balance is sufficient to withdraw the specified amount. If it is sufficient, balancesthe user's balance in the table is updated and transferred to the user.
6. DB contract
Smart contract can also be used as DB and can be used to replace ERC20 Token. ERC20 Token is the default DB standard issued by Ethereum. It includes two methods: transfer() and approve(), which are used to handle DB transfer and authorization.

pragma solidity ^0.4.22;

// @title An example token contract
contract MyToken is ERC20Interface {
string public constant symbol = "MY";
string public constant name = "MyToken";
uint8 public constant decimals = 18;

mapping(address => uint) public balances;
mapping(address => mapping(address => uint)) public allowed;

constructor() public {
totalSupply_ = 1000 * (10**uint256(decimals));
balances[msg.sender] = totalSupply_;
}

/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to!= address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);

balances[_from] -= _value;
balances[_to] += _value;
allowed[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}

/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of sender
* @param _spender address The address which will spend the funds.
* @param _value uint256 The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}

/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) view public returns (uint remaining) {
return allowed[_owner][_spender];
}
}

interface ERC20Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner) external view returns (uint256 balance);
function transfer(address to, uint256 tokens) external returns (bool success);
function transferFrom(address from, address to, uint256 tokens) external returns (bool success);
function approve(address spender, uint256 tokens) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256 remaining);

event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed owner, address indexed spender, uint256 tokens);
}

In the above sample code, a MyTokenDB contract named is defined, inherits the ERC20 Interface, and implements two methods: transferFrom() and approve(). Set the initial total amount of DB in the constructor and grant all DB to the publisher.

The transferFrom() method is used for DB transfer, and the approve() method is used for DB authorization. The allowance() method is used to query authorization.
7. Private deployment
For security reasons, smart contracts are usually not deployed directly on the public network. Smart contracts are usually compiled by developers, published to the IPFS (InterPlanetary File System) or Swarm (InterPlanetary File System) platform, and then deployed to the blockchain by one or more nodes.

Sometimes, in order to facilitate debugging or to save resources, developers will choose to deploy the contract to the local blockchain environment. This type of deployment is called privatized deployment.

pragma solidity ^0.4.22;

// @title A simple example contract
contract Example {
bool private initialized;
uint private counter = 0;

modifier notInitialized {
require(!initialized);
_;
}

constructor() public {
initialized = false;
}

function initialize() public notInitialized {
initialized = true;
counter = 10;
}

function getCounter() public view returns (uint) {
return counter;
}
}

In the above example code, a notInitializeddecorator named is introduced to check whether the contract has been initialized. In the constructor of the contract, the initialization flag is set to false, using notInitializedthe decorator, initialize()the method can be called only when the contract has not been initialized. The contract's counterproperties are initialized to 10.

Through privatized deployment, developers can easily test contract logic and data structures without publishing to the public network and without affecting the contract deployment of other users.

5. Future development directions and challenges

1. Side chain
At present, side chain technology has gradually matured and is being applied in different fields. For example, the Horizen project is an open source solution that uses side chains to achieve cross-chain data sharing. Sidechain technology can be further extended to other blockchains, such as Polkadot, Cosmos, Zilliqa, Kusama, etc.

However, enterprise-level sidechain networks may encounter some challenges, such as scalability, privacy protection, supervision, cross-chain standards, etc. For emerging application scenarios, smart contracts and side chains may also encounter new challenges. For example, how to make side chains support more assets and how to connect smart contracts to different blockchains?
2. Public chain and alliance chain
Currently, more and more companies are adopting public chains to build their own decentralized applications. Compared with alliance chains, public chains have better compatibility, performance, and scalability, and may achieve greater economies of scale in the future. However, the difference between the public chain and the alliance chain is that the public chain can be used arbitrarily, while the alliance chain is limited to specific business areas.

In the development process of blockchain, the balance between public chain and alliance chain will also be very important. As the public chain grows, the economic model on the blockchain will evolve into a completely decentralized organizational structure. As the alliance chain grows, the business models on the blockchain will be subdivided into smaller, more specialized teams, thus forming a flexible and healthy ecosystem.
3. Edge computing and blockchain
The combination of IoT, blockchain and edge computing is changing the entire way of edge computing. The application of blockchain allows the authenticity of computing data to be confirmed, which can then serve as the basis for trust. In addition, edge computing cloud computing resources can also become an economic incentive mechanism to encourage edge computing nodes to participate in the blockchain consensus and obtain rewards. The emerging technology of edge computing also brings new opportunities. For example, through machine learning, edge computing nodes can be built on private data to build predictive models to provide data support for smart manufacturing.

6.Appendix: Frequently Asked Questions

1. What is the difference between blockchain and cryptocurrency?
Blockchain and cryptocurrency are not the same thing. Blockchain is a distributed database used to record, store and verify digital information. The stored content is stored in an encrypted manner and belongs to a public distributed ledger. Any party can view all records. The blockchain consensus algorithm ensures data security, non-tamperability, authenticity and credibility. Blockchain is different from distributed databases in that it does not store static data, but records transactions that occur on the chain, and all records cannot be changed.

Cryptocurrency is a digital currency that allows for the transfer of value in a trustless environment, solving the insecurity issues of traditional currencies. Cryptocurrency enables value to flow in the digital world through mechanisms such as digital signatures, decentralized accounting, and proof of work. Cryptocurrencies store keys through digital currency wallets and users can access their cryptocurrencies. Cryptocurrencies can realize functions such as payments, transactions, and financial derivatives.

2. How to evaluate the growth rate of digital currency?
The growth rate of digital currencies is showing exponential growth. The past few years have seen explosive growth in both the volume and value of digital currency transactions globally. An investment researcher predicts that by 2022, the global digital currency transaction volume will exceed 100ZB, and the value will exceed 1ZB.

3. Why does the scale of digital currency transactions maintain rapid growth?
The biggest problem with digital currencies is volatility. The price volatility of digital currencies is too high. The reason is that people are generally familiar with payment services such as Alipay and WeChat Pay, so they think these payment services are very safe. However, the payment method of digital currency is very new and unique. This allows the transaction scale of digital currencies to maintain rapid growth.

Guess you like

Origin blog.csdn.net/universsky2015/article/details/132095037