"Programmers will see" How to create a chunk chain from 0 in Python?

Source: Internet
Author: User

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.


Author | Daniel van Flymen, New York block chain engineer

Translator | Chongli Niuwa Software CTO


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 = []< c3/> def new_block (self):
 # Creates a new block and adds it to the chain
 pass
 def New_trans   Action (self):
 # Adds A new transaction to the ' List of transactions pass
 @staticmethod
 def hash (block):
 # Hashes a blocks
 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 ': ' 2cf24dba5fb0a30e26e83b2ac5b9 e29e1b161e5c1fa7425e73043362938b9824 "
}


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, 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 a        Ram Amount: <int> Amount: Return: <int> The index of the "block" that would
 hold this transaction
 "" "
 self.current_transactions.append ({
 ' sender ': sender,
 ' recipient ': RE Cipient,
 ' 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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.