Simple implementation of blockchain in Python
with the global hot discussion of the concept of "blockchain", the application of blockchain technology has been quietly added to the daily life scenes such as finance, logistics, credit reference, manufacturing and retail. Some experts have shown that the future blockchain will be closely related to people's lives, and the integration of blockchain technology and people's daily life is the general trend
the popularity of the blockchain market has triggered a large number of talents demand based on blockchain technical personnel, and the popularity of blockchain talents is rising at the speed of light. According to the "2018 blockchain high salary list" released by lagou.com, Tencent, Xiaomi, Suning, Jingdong and other domestic enterprise giants have released many high salary blockchain post demands, trying to explore blockchain related technologies and applications. It is also pointed out in the list that the demand for high salary jobs is mainly based on blockchain related technical jobs, among which Suning and Keda have been given the highest monthly salary of 100k
the huge market demand for technical talents will inevitably lead to the explosive emergence and growth of the whole blockchain training market. Most of the training modes can be divided into online training, traditional IT organization training, and offline short-term training camps, which mainly focus on high-end forms. However, in the process of the hot market evolution, there are also a variety of blockchain training chaos: lecturers' qualifications are watered down, and even the most basic names are not disclosed, the syllabus is opaque, and the teaching quality is shrinking, Unreasonable class arrangement and uneven training fees and so on
with the large-scale development of the whole blockchain training market, brother company ecation, together with Yin Cheng, a senior blockchain expert, and his Tsinghua Shuimu Weiming team, has set up a blockchain college. With its professional and powerful team of technical lecturers, detailed and comprehensive curriculum system, and a large number of authentic enterprise blockchain projects, it aims to deepen the blockchain teaching and training field, And train more professional technical talents for enterprises and society<
Yin Cheng, a senior blockchain technology expert, graated from Tsinghua University, is the dean of brother Lian blockchain college. He once served as Google Algorithm Engineer, the world's most valuable expert in the field of Microsoft blockchain, and the gold medal lecturer of Microsoft tech.ed conference. Proficient in C / C + +, python, go language, sicikit learn and tensorflow. With 15 years of programming experience and 5 years of teaching experience, senior software architect, Intel Software Technology expert, famous technology expert, with many years of working experience in the world's top it company Microsoft Google. He has many years of experience in software programming and lecturing, and has developed many procts in human-computer interaction, ecation, information security, advertising and blockchain system. He has deep experience in project management and R & D, has two AI invention patents, and has practical experience in developing e-money deployed to Microsoft Windows azure. Teaching explanation is in simple language, so that students can apply what they have learned
the first stage: blockchain instry and go programming for 5 weeks
the second stage: cryptography and consensus algorithm for 2 weeks
the third stage: Ethereum source code analysis and development for 3 weeks
the fourth stage: Super ledger and node.js for 2 weeks
the fifth stage: bitcoin & EOS for 4 weeks
the sixth stage: comprehensive actual combat of the project
from the characteristics of the language itself, go is a very efficient language, which highly supports concurrency. Go language itself pays more attention to distributed systems, and concurrency processing is relatively good, such as advertising and search, which are high concurrency servers
go language advantages:
excellent performance, can be directly compiled into machine code, does not rely on other libraries, go is extremely fast. Its performance is similar to Java or C + +
concurrency is supported at the language level, which is the biggest feature of go. It is born to support concurrency, and go is the concurrency supported in gene, which can make full use of multi-core and make it easy to use concurrency
the built-in runtime supports garbage collection, which is one of the features of dynamic language. Although GC is not perfect at present, it is enough to cope with most of the situations we can encounter, especially GC after go1.1
it's easy to learn. The authors of go language all have the gene of C, so go naturally has the gene of C. There are 25 go keywords, but the expressive ability is very strong. It almost supports most of the features you've seen in other languages: inheritance, overloading, object, etc
rich standard libraries, go has built a large number of libraries, especially the network library, which is also my favorite part< As like as two peas, br / > built-in powerful tools, Go language is built with many tools chain, the best should be gofmt tools, automatic formatting code, make team review become so simple, code format is exactly the same, it is very difficult to think differently.
cross platform compilation and fast compilation. Compared with the sluggish compilation speed of Java and C + +, the fast compilation time of go is a major efficiency advantage
disadvantages of go language:
package management: package management of go language is absolutely not perfect. By default, it has no way to make a specific version of the dependency library, nor can it create replicable builds. In contrast, python, node and Ruby all have better package management systems. However, with the right tools, the package management of go language can also perform well
lack of development framework: go language does not have a major framework, such as Ruby's rails framework, Python's Django framework or PHP's laravel. This is a heated discussion in the go language community, because many people think that we should not start with using frameworks. This is true in many cases, but if you just want to build a simple crud API, it's much easier to use Django / djrf, rails laravel, or Phoenix
exception handling: go language can help developers deal with compilation errors by simply returning errors (or call stack) through functions and expected calling codes. Although this method is effective, it is easy to lose the scope of the error, so it is difficult to provide meaningful error information to users. Error package can solve this problem by allowing us to add context and stack trace to return error
another problem is that we may forget to handle errors. Static analysis tools such as errcheck and megacheck can avoid these errors. Although these solutions are very effective, they may not be the right way.
features:
blockchain is an immutable and orderly chain record composed of block records. The main features are as follows:
1: decentralization
e to the use of Distributed Accounting and storage, there is no centralized hardware or management organization, the rights and obligations of any node are equal, and the data blocks in the system are jointly maintained by the nodes with maintenance function in the whole system. Thanks to the decentralization of blockchain, bitcoin also has the characteristics of decentralization
2: openness
the system is open, in addition to the private information of the parties to the transaction is encrypted, the data of the blockchain is open to all, and anyone can query the blockchain data and develop related applications through the open interface, so the information of the whole system is highly transparent
3: autonomy
blockchain adopts consensus based specifications and Protocols (such as a set of open and transparent algorithms) to enable all nodes in the whole system to exchange data freely and safely in a de trusted environment, so that the trust in "people" is changed into the trust in machines, and any human intervention does not work
4: information cannot be tampered with
once the information is verified and added to the blockchain, it will be stored permanently. Unless more than 51% of the nodes in the system can be controlled at the same time, the modification of the database on a single node is invalid, so the data stability and reliability of the blockchain are extremely high
5: anonymity
since the exchange between nodes follows a fixed algorithm, their data interaction does not need to be trusted (the program rules in the blockchain will judge whether the activity is effective by themselves), so the counterparties do not need to make the other party trust themselves by disclosing their identities, which is very helpful for credit accumulation
compared with the traditional distributed database, there are two main differences:
1: the traditional distributed database supports adding, deleting, checking and modifying, while the blockchain only supports searching and inserting, and blocks cannot be deleted or modified
2: the traditional distributed database is generally a master-slave structure: master and slaves structure. In order to ensure high availability, it is realized by standby master, while the blockchain is a decentralized database. There is no master-slave structure
blockchain and bitcoin:
when it comes to blockchain, most people talk about bitcoin. However, blockchain is not equal to bitcoin. It is now the era of blockchain 3.0, and bitcoin is only the proct of blockchain 1.0
the evolution mode of blockchain is:
& ᦇ 9642; Blockchain 1.0 digital currency; Blockchain 2.0 digital assets and smart contracts; Blockchain 3.0 - Implementation of distributed applications in various instries
classification of blockchain:
public blockchains
public blockchain means that any indivial or group in the world can send transactions, and transactions can be effectively confirmed by the blockchain, and anyone can participate in its consensus process. Public blockchain is the earliest and the most widely used blockchain. The virtual digital currencies of bitcoin series are all based on public blockchain. There is only one blockchain corresponding to this currency in the world
consortium blockchains
instry blockchains: multiple preselected nodes are designated as bookkeepers within a certain group, and the generation of each block is jointly determined by all preselected nodes (preselected nodes participate in the consensus process). Other access nodes can participate in transactions, but not the bookkeeping process (essentially, trusteeship bookkeeping), It just becomes distributed accounting, the number of preselected nodes, and how to determine the bookkeeper of each block to become the main risk point of the blockchain). Anyone else can conct limited query through the open API of the blockchain
private blockchain: it only uses the general ledger technology of blockchain for bookkeeping. It can be a company or an indivial, enjoying the write permission of the blockchain. This blockchain is not very different from other distributed storage schemes Dec2015) conservative giants (traditional finance) want to experiment with private blockchain, while the application of public chain, such as bitcoin, has been instrialized, and the application procts of private chain are still groping.
Can be
blockchain to achieve a simple description of the principle of
blockchain technology as a digital accounting technology, its core is to save the transaction data block, in the form of encryption, according to the order of time chain record. Blockchain itself is a public database. The system stores the new business data in a container called block, and adds the block to the chain composed of existing blocks. It's a bit like a snake. The more you eat, the longer the snake's body; In the application scenario of bitcoin, the data is a set of transfer transaction records. In the application scenario of bike sharing, these data can be the transaction records of car borrowing and returning
The simple implementation code ofblockchain
in the above code, the data structure stored in the core of blockchain is list, which can be accessed through
new_ New blocks generated by block () are constantly added to the end of the blockchain. The hash value of each block contains all the data information of the block. In the process of calculating the hash
value, the hash
value of the previous block needs to be referenced, so tamper proof is realized. The biggest value of blockchain database is this highly tamper proof trusted computing. This has been successfully demonstrated in our simple blockchain implementation. In commercial level blockchain applications, the process of creating new blocks is called smart contract, and blockchain is growing through smart contract
the following is the running result of the code, which is different at different times
running results
< img / >
is a computer language. Blockchain is a decentralized database protocol without a center. Most blockchains are developed with C + + (because of performance). There is no direct relationship between Python and blockchain, and few people use Python to develop blockchain.
and Python is an object-oriented interpretive computer programming language
it's better to learn together without conflict. I think it's Python because it's a language that can do a lot of things.
1 import hashlib as hasher
2 import datetime as date
3
4 # Define what a Snakecoin block is
5 class Block:
6 def __init__(self, index, timestamp, data, previous_hash):
7 self.index = index
8 self.timestamp = timestamp
9 self.data = data
10 self.previous_hash = previous_hash
11 self.hash = self.hash_block()
12
13 def hash_block(self):
14 sha = hasher.sha256()
15 sha.update(str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash))
16 return sha.hexdigest()
17
18 # Generate genesis block
19 def create_genesis_block():
20 # Manually construct a block with
21 # index zero and arbitrary previous hash
22 return Block(0, date.datetime.now(), "Genesis Block", "0")
23
24 # Generate all later blocks in the blockchain
25 def next_block(last_block):
26 this_index = last_block.index + 1
27 this_timestamp = date.datetime.now()
28 this_data = "Hey! I'm block " + str(this_index)
29 this_hash = last_block.hash
30 return Block(this_index, this_timestamp, this_data, this_hash)
31
32 # Create the blockchain and add the genesis block
33 blockchain = [create_genesis_block()]
34 previous_block = blockchain[0]
35
36 # How many blocks should we add to the chain
37 # after the genesis block
38 num_of_blocks_to_add = 20
39
40 # Add blocks to the chain
41 for i in range(0, num_of_blocks_to_add):
42 block_to_add = next_block(previous_block)
43 blockchain.append(block_to_add)
44 previous_block = block_to_add
45 # Tell everyone about it!
46 print "Block #{} has been added to the blockchain!".format(block_to_add.index)
47 print "Hash: {}\n".format(block_to_add.hash)
if you have project experience
machine learning, especially the popular deep learning, most of its tool frameworks provide Python interface. Python has a good reputation in the field of scientific computing. Its concise and clear syntax and rich computing tools are loved by developers in this field
long before deep learning and tensorflow became popular, there was scikit learn in Python, which can easily complete almost all machine learning models. It only takes a few lines of code to download from classic data sets to build models. With pandas, Matplotlib and other tools, it can be easily adjusted
deep learning frameworks such as tensorflow, pytorch, mxnet and keras greatly expand the possibility of machine learning. Using keras to write a deep learning network for handwritten numeral recognition only needs a few dozen lines of code, which can be implemented with the help of the bottom layer, and can easily call a large number of resources including GPU to complete the work
it is worth mentioning that no matter what framework, Python is only used as a front-end description language, and the actual calculation is implemented through the underlying C / C + +. Python can easily introce and use C / C + + projects and libraries, so as to realize the expansion of function and performance. In such large-scale computing, developers pay more attention to the logic itself, and liberate themselves from the complicated work such as memory allocation, which is an important reason why Python is widely used in the field of machine learning.