Speaking of football have to mention the money back brother!
In 2019, my cousin won the first European National League scoring Championship trophy! See how my cousin laughs!
In the recent European Cup, we can also see the block chain figure (although is the advertisement
1. European Cup and blockchain
On June 10, UEFA announced on its official website that Ant Chain, a subsidiary of Ant Group, has become the global partner of Euro 2020. Uefa and Ant Chain have signed a five-year cooperation agreement, saying they will jointly explore the application of technologies such as blockchain to accelerate the digital transformation of the football industry and provide better and richer watching experience for fans around the world.
“Football is a universal language, and blockchain is a ‘language of consensus’ to build trust between people, which is a good fit,” said Monday, who designed the trophy.
2. Introduction to blockchain
2.1 concept
In narrow sense,
Blockchain is a kind of distributed ledger that combines data blocks in chronological order to form a chain data structure, and is guaranteed by cryptography to be immutable and unforgerable.
broadly
Block chain technology is to use the chain to verify the data structure and data storage, the use of distributed node consensus algorithm to generate and update the data, the use of cryptography way to guarantee the safety of data transmission and access of the use of automated script code intelligent contracts to programming and operating data of a new kind of distributed infrastructure and computing paradigm
2.2 Basic Technology
2.2.1 Hash operations
Blockchain ledger data mainly through the parent block hash value formed chain structure to ensure imtamability.
Hash algorithm (hash algorithm)
Main function: generate a fixed length string from arbitrary length input through certain calculation, and the output string is called the hash value of the input.
Example: Find one on BaiduOnline Hash algorithm
There are a lot of hashing algorithms! Let’s use SHA-256 as an example!Go language code implementation: MD5
package main
import(
"fmt"
"crypto/md5"
"encoding/hex"
)
func main(a){
/ / method
data:=[]byte("hello world")
s:=fmt.Sprintf("%x",md5.Sum(data))
fmt.Println(s)
/ / method 2
h:=md5.New()
h.Write(data)
s= hex.EncodeToString(h.Sum(nil))
fmt.Println(s)
}
Copy the code
SHA-256
package main
import(
"fmt"
"github.com/nebulasio/go-nebulas/crypto/hash"
"encoding/hex"
"crypto/sha256"
)
func main(a){
// One method is output directly
data:=[]byte("hello world")
hash:=hash.Sha256(data)
fmt.Println(hex.EncodeToString(hash))
sha256.New()
// In method 2, output step by step
h:= sha256.New() // Create the sha256 algorithm
h.Write(data) // Use sha256 algorithm to encrypt parameter a to get 8 variables
hashTemp := h.Sum(nil)// Add the 8 variables to get the final hash
fmt.Println(hex.EncodeToString(hashTemp))
}
Copy the code
Features:
- Forward fast given data can be in
A very short
Quickly get the hash value in time of. - If the input is sensitive to minor changes in the input information, the regenerated hash value will also be the same as the original hash value
A far cry from
. - Reverse difficult
Can't
inA short time
In terms of the hash valueThe original
This feature is also the basis of hash algorithm security, and is therefore an important component of modern cryptography. - Strong resistance to collisions with different inputs
It is difficult to
Can produceThe same
Hash output of.
In addition:
-
The chain structure of the blockchain built by hashing is tamper-proof.
-
Through the Merkel tree constructed by hashing, the rapid detection of content changes is realized.
2.2.2 Digital Signature
Digital signature has important applications in information security, including identity authentication, data integrity, non-repudiation and anonymity. It is an important branch of absorption band cryptography. Signatures are part of public key cryptography.
Signature process:
The sender uses its private key to encrypt the message and obtains a hash value, which is the signature. The signature and information need to be sent to the receiver. The receiver uses the public key disclosed by the sender and the received information to verify the signature and retrograde. If the authentication is successful, the received information is complete and accurate; otherwise, the source of the message is incorrect.
The specific process of digital signature:
- Sender A calculates the digital digest of the original data through the hash algorithm, encrypts the digital digest using the private key in the asymmetric key pair, and the encrypted data is the digital signature.
- The digital signature is sent along with A’s original data to any party that verifies the signature.
Digital signature verification process:
- First, the verifier of the signature must hold the public key of sender A that is not converted into A key pair
- After receiving the digital signature and the original data of A, the public key is first used to decrypt the digital signature and get the original summary value.
- Then the digest value of the original data of A is calculated by the same hash algorithm, and then the digest value obtained by decryption is compared with the recalculated digest value, if the same, the signature passes.
2.2.3 P2P network
Peer to peer, p2p for short, peer to peer network. All nodes in a P2P network have equal status, and the network does not depend on one center.
2.2.4 Consensus algorithm
concept
Due to the high network delay in point-to-point network, the transaction sequence observed by each node cannot be exactly the same. So a blockchain system needs to set up a mechanism to agree on the sequence of transactions that will take place in a similar amount of time. The algorithm that agrees on the sequence of transactions in a time window is called the consensus mechanism.
- Consensus algorithm: A calculation algorithm in which nodes reach consensus according to consensus rules
- Consensus rules: Each blockchain has carefully designed rule-based protocols that use consensus algorithms to ensure that consensus rules are implemented correctly.
It is the law of life
There are mainly the following consensus algorithms:
- Proof of work PoW: Bitcoin BTC, Ethereum ETH, Ethereum Classic ETC
- PoS: ADA, Peercoin
- DPoS: EOS, Asch, Steem
- Byzantine fault tolerance BFT: Practical Byzantine fault tolerance PBFT, derived BFT
- RAFT algorithm: ETCD
Comparison of several algorithms
PoW | PoS | DPoS | Raft | PBFT | |
---|---|---|---|---|---|
scenario | The male chain | Public chain, alliance chain | Public chain, alliance chain | League chain | League chain |
decentralized | completely | completely | completely | Half neutralization | Half neutralization |
The node of charge to an account | Cut in | Cut in | Elect representatives | Choosing a Leader | Dynamic decision |
The response time | Ten minutes | 1 minute | 3 seconds | Second level | Second level |
Storage efficiency | All the books | All the books | All the books | All the books | Full ledger + partial ledger |
throughput | About 7 TPS | About 15 TPS | About 300TPS or higher | Thousands or even tens of thousands | About 10000TPS or higher |
Fault tolerance | 50% | 50% | 50% | 50% | 33% |
2.2.5 Smart Contract
Definition:
In simple terms, a smart contract is a computer program that automatically executes when certain conditions are met. Vending machines, for example, can be considered a smart contract system. The customer needs to select the item and complete it
Features:
- The if-then statement of a computer program
- It is automatically implemented when the treaty is reached
- Digital contracts
- The computing system automatically executes the terms
Features:
- Data transparency: The data on the blockchain is open and transparent to the participants, and the data processing is also open and transparent.
- Imtamable: All data on the blockchain itself is imtamable, as is the smart contract code on the blockchain and the data output generated by the operation.
- Permanent operation: There are often hundreds or even thousands of nodes supporting the blockchain network. The failure of some nodes does not cause the smart contract to stop, and its reliability is theoretically close to permanent operation.
Composition:
- Participant: A person or organization that participates in a digital asset transaction.
- Asset: Something, either concrete or abstract, that has a certain value and is acquired as part of a transaction.
- Transaction: The process in which participants query and transfer assets.
- Ledger: a database that records the ownership of assets and the facts of their transactions.
2.3 the characteristics of
2.3.1 Transparent trust
- Personal accounting ensures that everyone has access to complete information, thus realizing information transparency.
- The decision-making process between nodes is jointly participated, and the consensus ensures credibility
2.3.2 Tamper-proof traceability
Tamper-proof: Once a transaction has been network-wide verified and added to the blockchain, it is difficult to modify or erase.
Traceable: Means that any transaction that takes place on the blockchain is completely recorded, and we can trace all the historical transactions related to a given state on the blockchain.
2.3.3 Privacy security
Since any node in the blockchain system contains a complete block verification logic, no node needs to rely on other nodes to complete the confirmation process of transactions in the blockchain, that is, no additional trust is required for other nodes.
2.3.4 High system reliability
- Each node peer-to-peer maintains a ledger and participates in the consensus of the entire system, and if one node fails, the entire system will work
- The blockchain system supports Byzantine fault tolerance. Although the traditional distributed system also has high reliability, it can only tolerate the collapse of the nodes in the system or the problem of network partition. However, once the system is conquered or the information processing logic of the nodes is modified, the whole system will not work properly.
3. Simple code to implement blockchain
The fields required by the block of the blockchain
byte | field | instructions |
---|---|---|
4 | version | The block version number, which represents the validation rules that the block complies with |
32 | Parent header hash | The Merkle root hash of the previous block is also calculated using SHA256 |
32 | Merkle root | The hashes of Merkle roots traded in this block are also calculated using SHA256 |
4 | The time stamp | The approximate time of the block, a UNIX timestamp accurate to the second, must be strictly greater than the median of the first 11 blocks, and the entire node will reject any block with a timestamp longer than two hours |
4 | Difficult goals | The block workload proves that the difficulty target of the algorithm has been encoded using a specific algorithm |
4 | Nonce | In the future, we will find a random number that meets the difficulty goal. In order to solve the problem that 32 is not enough for the random number when the computing power is skyrocketing, we will change the timestamp and coinbase transaction information to expand the number of bits of the Nonce |
** Note: The ** block does not store the hash value. The node accepts the block and computes it independently and stores it locally.
3.1 Block related:
-
Defines the structure of a Block
Block header: 6 fields Block body: string representing data
A. Block header: 6 fields b. Block body: The string represents data */
/ / block
type Block struct {
Version int64 / / version
PerBlockHash []byte // The hash value of the previous block
Hash []byte // The hash value of the current block is used to simplify the code
MerKelRoot []byte // Meckelgen
TimeStamp int64 / / time
Bits int64 / / difficulty value
Nonce int64 / / random value
/ / block
Data []byte // Transaction information
}
Copy the code
- Provides a method to create blocks NewBlock(parameter)
Provides a method for creating blocks, NewBlock(parameter) */func NewBlock(data string ,prevBlockHash []byte) *Block {
var block Block
block = Block{
Version: 2,
PerBlockHash: prevBlockHash,
//Hash: []byte{}, // The block does not store the Hash value. The node accepts the block and calculates it independently and stores it locally.
MerKelRoot: []byte{},
TimeStamp: time.Now().Unix(),
Bits: targetBits,
Nonce: 0,
Data: []byte(data),
}
// block.sethash () // Fill the Hash
PoW:= NewProofOfWork(&block)
nonce , hash :=PoW.Run()
block.Nonce=nonce
block.Hash=hash
return &block
}
Copy the code
And don’t forget the Creation blocks
func NewGensisBlock(a) *Block{
return NewBlock("Genesis Block!"And []byte{})}Copy the code
- Define a work proved that the structure of the ProofOfWork block | target value
/* 3. Define a structure of ProofOfWork target value */
type ProofOfWork struct {
block *Block
target *big.Int / / the target
}
Copy the code
-
Provides a way to create PoW
NewProofOfWork (parameters)
/* 4. Provide a method to create PoW NewProofOfWork(parameter) */
const targetBits = 24
func NewProofOfWork(block *Block) *ProofOfWork { // Proof of work
target := big.NewInt(1) / / 000... 001
target.Lsh(target,uint(256-targetBits)) // Move 1 to the left //ox00000010000000.. 00
pow:=ProofOfWork{
block: block,
target: target,
}
return &pow
}
func (pow *ProofOfWork) PrepareData(nonce int64) []byte {
Func Join(s [][]byte, sep []byte) []byte
block := pow.block
tmp :=[][]byte{
IntToByte(block.Version),
block.PerBlockHash,
block.MerKelRoot,
IntToByte(block.TimeStamp),
IntToByte(block.Bits),
IntToByte(block.Nonce),
}
data:=bytes.Join(tmp,[]byte{}) // Then calculate the hash
return data
}
Copy the code
-
Provides a method to calculate the hash value
Run()
/* 5. Provide a method to calculate the hash value Run() */
func (pow *ProofOfWork)Run(a) (int64And []byte) {
//1
//2. Convert the hash value to big.int
var hash [32]byte
var nonce int64 = 0
var hashInt big.Int
fmt.Println("Start digging!)
fmt.Printf("Difficulty target hash: %x\n" ,pow.target.Bytes())
for nonce < math.MaxInt64 {
data:=pow.PrepareData(nonce)
hash = sha256.Sum256(data)
// Cmp compares x and y and returns:
//
// -1 if x < y
// 0 if x == y
// +1 if x > y
//
hashInt.SetBytes(hash[:])
if hashInt.Cmp(pow.target) == - 1 {
fmt.Printf("Found ,nonce :%d ,hash :%x \n",nonce,hash)
}else {
//fmt.Printf("Not Found ,current nonce :%d ,hash :%x \n",nonce,hash)
nonce++
}
}
return nonce,hash[:]
}
Copy the code
-
Provide a check function
IsValid()
/* 6. Provide a validation function IsValid() */
func (pow *ProofOfWork)IsValid(a) bool{
var hashInt big.Int
data := pow.PrepareData(pow.block.Nonce)
hash:=sha256.Sum256(data)
hashInt.SetBytes(hash[:])
return hashInt.Cmp(pow.target) == - 1 // If it is -1, it is found
}
Copy the code
3.2 Blockchain related
-
Define a BlockChain structure BlockChain
Block array
/* 1. Define a BlockChain structure BlockChain Block array */
type BlockChain struct {
blocks []*Block
}
Copy the code
-
Provides a method to create BlockChain()
NewBlockChain()
/* 2. Provide a way to create BlockChain() NewBlockChain() */
func NewBlockChain(a) *BlockChain {
block := NewGensisBlock()
return &BlockChain{blocks:[]*Block{block}} // Create a blockchain with only one element and initialize it
}
Copy the code
-
Provides a way to add blocks
AddBlock (parameters)
/* 3. Provide a method to add blocks AddBlock(parameter) */
func (bc *BlockChain)AddBlock(data string) {
PerBlockHash := bc.blocks[len(bc.blocks)- 1].Hash // The hash of this block is the hash of the previous block
block := NewBlock(data,PerBlockHash)
bc.blocks = append(bc.blocks,block)
}
Copy the code
A simple blockchain is implemented!
The last
Xiao Sheng Fan Yi, looking forward to your attention.