In the digital currency of the popular stalls, bitcoin, the currency of the value of the money is not trustworthy. Perhaps you are as curious as many people, want to approach it, but only because of the block chain technology behind, blocking the pace of the attempt to new areas. However, for programmers, want to really understand Bitcoin, understand the block chain, is not a problem, because they can play while learning, through a line of Pyhton code, can really understand the underlying secrets of digital currency. Can use such a forced way to learn the block chain, and only programmers.
preparatory work
This article requires readers to have a basic understanding of Python, read and write basic python, and need to have a basic understanding of HTTP requests.
We know that a block chain is an immutable, orderly chain of records made up of chunks, records can be transactions, files, or any data you want, and it is important that they are linked by a hash value (hashes).
If you are not very familiar with hashing, you can view this article Https://learncryptography.com/hash-functions/what-are-hash-functions
Environmental Preparedness
Environmental readiness to ensure that python3.6+, Pip, flask, requests have been installed
Installation method:
Pip Install flask==0.12.2 requests==2.18.4
You also need an HTTP client, such as a postman,curl or other client.
Reference source code (the original code in my translation, can not run, I fork a copy, fixed the error, and added a translator, thank star)
Start creating Blockchain
Create a new file blockchain.py, all the code in this article is written in this file, you can refer to the source code at any time.
Blockchain class
First, you create a blockchain class that creates two lists in the constructor, one for storing block chains, and one for storing transactions.
The following is the framework for the Blockchain class:
Class Blockchain (object):
def __init__ (self):
Self.chain = []
Self.current_transactions = []
def new_block (self):
# Creates a new block and adds it to the chain
Pass
def new_transaction (self):
# Adds A new transaction to the list of transactions
Pass
@staticmethod
def hash (block):
# Hashes a block
Pass
@property
def last_block (self):
# Returns The last blocks in the chain
Pass
The blockchain class is used to manage the chain, it can store transactions, add new blocks, and so on, let's further refine these methods.
Block Structure
Each chunk contains attributes: Index, UNIX timestamp (timestamp), transaction list (transactions), work proof (explained later), and hash value of the previous block.
The following is the structure of a block:
Block = {
' Index ': 1,
' Timestamp ': 1506057125.900785,
' Transactions ': [
{
' Sender ': "8527147fe1f5426f9dd545de4b27ee00",
' Recipient ': "a77f5cdfa2934df3954a5c7c7da5df1f",
' Amount ': 5,
}
],
' Proof ': 324984774000,
' Previous_hash ': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}
Here, the concept of the block chain is clear, each new block contains the hash of the previous block, which is the key point, it protects the block chain is not denatured. If an attacker destroys one of the previous blocks, then the hash of all the blocks that follow will become incorrect. Do not understand the words, slowly digested, can refer to {% Post_link WHATBC block chain technical principle%}
Join Trade
Next we need to add a deal to refine the New_transaction method
Class Blockchain (object):
...
def new_transaction (self, sender, recipient, amount):
"""
Generate new transaction information and information will be added to the next block to be dug
:p Aram Sender: <str> address of the sender
:p Aram Recipient: <str> address of the recipient
:p Aram Amount: <int> Amount
: return: <int> The index of the "block" hold this transaction
"""
Self.current_transactions.append ({
' Sender ': sender,
' Recipient ': Recipient,
' Amount ': Amount,
})
Return self.last_block[' index '] + 1
Method adds a transaction to the list and returns the index of the chunk to which the record will be added (the next block to be mined), which is useful when the user submits the transaction.
Create a new block
When blockchain is instantiated, we need to construct a creation block (the first block without the front block) and add a work proof to it.
Each block needs to go through the work of proof, commonly known as mining, will continue to explain later.
To construct the Genesis block, we also need to refine the New_block (), new_transaction () and hash () methods:
Import Hashlib
Import JSON
From time Import time
Class Blockchain (object):
def __init__ (self):
Self.current_transactions = []
Self.chain = []
# Create The Genesis block
Self.new_block (previous_hash=1, proof=100)
def new_block (self, Proof, Previous_hash=none):
"""
Generate a new block
:p Aram Proof: <int> The proof given by the proof of Work algorithm
:p Aram Previous_hash: (Optional) <str> Hash of previous block
: return: <dict> New block
"""
Block = {
' Index ': Len (self.chain) + 1,
' Timestamp ': Time (),
' Transactions ': Self.current_transactions,
' Proof ': proof,
' Previous_hash ': Previous_hash or Self.hash (Self.chain[-1]),
}
# Reset The current list of transactions
Self.current_transactions = []
Self.chain.append (Block)
return block
def new_transaction (self, sender, recipient, amount):
"""
Generate new transaction information and information will be added to the next block to be dug
:p Aram Sender: <str> address of the sender
:p Aram Recipient: <str> address of the recipient
:p Aram Amount: <int> Amount
: return: <int> The index of the "block" hold this transaction
"""
Self.current_transactions.append ({
' Sender ': sender,