The simplest block chain implementation, less than 50 lines of code! (a) __ block chain

Source: Internet
Author: User
Tags python list
What is a block chain (blockchain).
An electronic bookkeeping book, which is recorded in the order of the currency and other cryptographic currencies, in public and by date.

In general, it is a public database in which new data is stored in a container called a block, and attached to a "immutable" chain (that is, a block chain) with previously attached data on the chain. The "immutable" here refers to the fact that once the data is attached to the chain, the following is not changeable. So plainly, block chain is a special history can not change the linked list of data structure just.

In the case of Bitcoin and other cryptographic currencies, this data refers to a set of transaction data. In other cases, of course, this data can be of any data type.

Block-chain technology has led to the development of new "all-electronic" currencies, such as Bitcoin and the Wright coins, which are not issued and managed by a centralized authority. At the same time, the block chain also brought about a revolution in distributed computing, with the advent of Ethernet technology and the emergence of concepts such as intelligent contracts (smart contracts).

This article will implement a simple block chain of only 50 lines of code, called Snakecoin.

First, we define the block, in a block, storing a timestamp and an (optional) index. To ensure the integrity of the entire block chain, each block has a hash value that marks its identity, like the Wright Dollar, where the hash value of each chunk is generated by a cryptographic algorithm based on the Block's index, timestamp, data, and the hash value of the previous block. Chunks of data can be anything you want.

Import Hashlib as Hasher

class block:
  def __init__ (self, index, timestamp, data, Previous_hash):
    self.index = Index
    Self.timestamp = timestamp
    self.data = data
    Self.previous_hash = Previous_hash
    Self.hash = Self.hash_block ()
  
  def hash_block (self):
    sha = hasher.sha256 ()
    sha.update (str (self.index) + 
               str ( Self.timestamp) + 
               str (self.data) + 
               str (self.previous_hash)) return
    sha.hexdigest ()

That's great. We have our own block structure, but we need to create a block chain. We need to start attaching the blocks to the actual chain. As mentioned above, each block needs the information of the front block, then the question is: How does the first block in the block chain come from? Well, the first block, or the Genesis block, is a special block that, in many cases, is added by hand or by a single logic.

Here we create a function that simply returns a Genesis block for simplicity. The index of this block is 0, and its data values and previous hash parameters are arbitrarily specified.

Import datetime as Date

def create_genesis_block ():
  # Manually construct a block with
  # index zero and Arbitra Ry previous hash return blocks
  (0, Date.datetime.now (), "Genesis block", "0")
Now that we can create a Genesis block, we need a function to generate the next block in the block chain, which takes the first block in the chain as a parameter, creates the data for the new block, and returns a block with the appropriate data. When the new chunk hashes from the information in the preceding block, the integrity of the block chain is enhanced with the addition of new blocks. If we do not do so, it is easy for the outside world to replace the blocks in our chain with their new block, so as to "tamper with history".

This hash chain acts as a cryptographic evidence and ensures that once a chunk is added to the block chain, it cannot be replaced or modified.

def next_block (last_block):
  this_index = last_block.index + 1
  this_timestamp = Date.datetime.now ()
  This_ data = "hey! I ' m block ' + str (this_index)
  This_hash = Last_block.hash return block
  (This_index, This_timestamp, This_data, This_hash)
That's the main job, and now we can create our block chain. In our case, the block chain itself is a simple python list. The first element of the list is the Genesis block, and of course we need to continue adding blocks. Because Snakecoin is a minimalist block chain, there are only 20 new blocks that we can fix in a for loop.

# Create The blockchain and add the Genesis block
blockchain = [Create_genesis_block ()]
Previous_block = Blockchai N[0]

# How many blocks should we add to the chain
# after the Genesis block
num_of_blocks_to_add =

# Ad D blocks to the chain
for I in range (0, Num_of_blocks_to_add):
  block_to_add = Next_block (previous_block)
  Blockchain.append (block_to_add)
  previous_block = Block_to_add
  # tell everyone about it!
  Print "Block #{} has been added to the blockchain!". Format (Block_to_add.index)
  
Let's test the current results:

Get. Our block chain is running. If you want to see more information on the console, you can change the code a little bit and print out the timestamp or data for each block.

This is all the functionality that Snakecoin can offer, and if you want to extend snakecoin to the size of the block chain in the actual production environment, you need to add functionality like the server layer, track changes to the chain on multiple machines, plus a work proof algorithm (proof-of-work algorithm) to limit the number of blocks added within a given time period.

If you want to get a closer look, you can read the original Bitcoin white paper: Https://bitcoin.org/bitcoin.pdf. Good luck, happy hacking!.

Original link: https://medium.com/crypto-currently/lets-build-the-tiniest-blockchain-e70965a248b

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.