[Python] Ikiri high school students will explain blockchain to beginners in 10 minutes! !! !!

1. About this article

## 1-1. Introduction This article was impressed by my high school student [Udemy: An introduction to blockchain development from scratch starting with Python taught by an active Silicon Valley engineer](https://www.udemy.com/share/1021OSAkIbdVdQQXo=0). , I wrote it with the hope that everyone reading this article will take it. I finished this lesson in two days, so if you are already familiar with development, I think it is quite possible to understand and implement it in one day. I will also introduce articles that helped me to understand.

(I'm glad to cry if you like it)

1-2. What is explained in this article

In this article, we'll start with a brief introduction to BlockChain for you to understand. Next, I will explain the technical explanation of BlockChain </ font> and P2P network </ font>. And finally, we will consider what kind of application this technology called BlockChain can be applied to in the future.

I will explain using Bitcoin as an example, so I think it will lead to an understanding of Bitcoin.

Be sure to read them in order. I think it is difficult to understand even if you read it from the middle.

1-3. Target readers

--Those who are interested in BlockChain --Those who have studied BlockChain but don't understand --For those who are reading the article for the time being --Those who want to know more about popular virtual currencies

Anyway, I will explain from 1 for the above people.

1-4. Development environment

Python3.7(Anaconda)

PC: macOS Catalina version 10.15 (memory 8GB, Intel Core i5)

Development IDE: PyCharm

2. What is a blockchain?

I will explain about blockchain from now on.

2-1. Cryptocurrency and BlockChain

Aside from the technical story of BlockChain, I will first explain the position of BlockChain using cryptocurrencies as an example. First, consider the situation where you send money through an ordinary bank. Consider the situation where Mr. A sends 1000 yen to Mr. B below. スクリーンショット 2019-10-16 7.08.57.png Once through the bank, the bank thus approves the transfer and the transfer is complete. And the bank ledger (database) will keep records of various transactions as shown below. スクリーンショット 2019-10-16 7.16.34.png

However, there is a tacit understanding for remittances via this bank. It means that you ** trust the bank **. Everyone trusts that ** banks will not tamper with this transaction **, so you can send money through the bank. For example, if a bank sends 1000 yen but only 500 yen is rewritten without permission, this bank will not be trusted and no one will send money at this bank.

And in this case, the bank has two main responsibilities.

--Verify whether this transaction is legitimate --Record the data for this transaction

about it. It is impossible to verify whether this transaction is valid even if you try to send 10,000 yen from Mr. M who is not registered with this bank to Mr. A. Also, it is not a legitimate transaction to try to increase Mr. A's balance to 1000000 yen without permission. Banks are verifying this. Also, recording transaction data is as shown in the previous figure.

** BlockChain replaces these two roles. ** **

And in the blockchain, ** without setting up a central bank, all participants will verify that the transaction is correct **. This is the important part. Be sure to remember this.

So how do you replace it? I will explain while talking technically.

2-2. P2P and Server / Client

BlockChain is supported by a network called P2P. So what kind of network is P2P?

2-2.1 Server / Client network

First of all, the network we usually use is a network called Server / Client. The Server / Client network conducts transactions as follows.

serverclient.png

When the client side requests the server side to "give me data!", The server side returns the data accordingly.

For example, consider Twitter. The server is owned by Twitter, and the clients are our smartphones and personal computers. Open the Twiiter app and you will see the tweets of the person you follow first. This is because when the app is opened, the smartphone on the client side asks the Twitter server to "give me the tweets of the people you follow!", And the server responds with the data "This is the data". Is returned and flows to the timeline.

In this case, what if Twitter's server goes down? When you open the app, even if the client side requests it, you will not be able to return the corresponding data. In other words, we will not be able to receive the service as Twitter.

Next, what if the processing performance of Twitter's server is very low? When the app is opened, even if the client side requests it, the server side takes a tremendous amount of time to find the data. Then, we take a long time to use Twitter, and sometimes the server goes down, which makes us feel stressed.

In summary, the following are the drawbacks of Server / Client networks.

--If the server goes down, the network cannot be maintained and the service cannot be used. --If the processing performance of the server is low, it is not possible to provide services that are burdensome.

This is less reliable because you don't know when the server will go down.

P2P networks eliminate these two drawbacks.

2-2.2 P2P type network

P2P.png

The P2P network looks like the figure above. Let's explain in more detail.

First of all, P2P networks do not have the role of server or client as before. ** Conversely, every computer that participates in the network is both a server and a client. ** **

Second, each computer has its own data, and everyone manages that data. So, ** Even if one of these computers goes down, the network can be operated and maintained. ** Therefore, it is more reliable than Server / Client type network.

In addition, all the computers that participate in the network act as servers, so the more computers that participate in the network, the better the processing performance of the entire network. ** **

Therefore, the following are the advantages of P2P type networks, and they overcome the drawbacks of Server / Client type networks.

――Even if one computer goes down, the network can be operated and maintained. --Very high processing performance of the entire network

3. Detailed explanation

Here, we will explain BlockChain in detail.

ブロックチェーン.png

It's hard to understand even if it is said that the blockchain stores data as shown in the figure above. I will explain in detail. I will explain using Bitcoin as an example in an easy-to-understand manner.

First of all, what is a block?

A block is a ** certificate of transaction data **. For example, Mr. A sent 1 Bitcoin to Mr. B. However, as explained earlier, in order to send money, all participants must ** verify that the transaction is correct **. The certificate of verification is a block. However, this certificate cannot be easily tampered with. What happens if it is tampered with? A long time ago, Mr. A sent 1 Bitcoin to Mr. B, but five years later, Mr. A was in trouble with the money, so he decided not to send the money. I will. It would be difficult if you could do that (not really). Therefore, this certificate (block) is saved so that it cannot be tampered with. Let me explain how it works.

First, there are four pieces of information in the block. The four are ** previous hash value **, ** timestamp **, ** nonce **, and ** transaction **. I will explain each individually.

First is the time stamp. The time stamp is the time when the transaction is verified to be correct. This guarantees ** when ** that this transaction was approved as correct.

Next is the transaction. A transaction is the data of the actual transaction. [2-1](# 2-1. Cryptocurrency and BlockChain) is a bank balloon. This is transaction data.

Next is the previous hash value. We will develop more carefully from here. Now let's see what the actual block looks like. (This is a block, not a chain. A chain is a chain of blocks.)

ブロックの中身.png

Aside from the detailed contents, the light blue part is the nonce, the yellow-green part is the previous hash value, the purple part is the time stamp, and the pink part is the transaction. Since this is one block, there is such a block before this block (of course, each number etc. is different). The hash value of the entire previous block is ** the hash value of the previous block **. The reason for including the hash value of the previous block as the information of the next block is ** because it is not tampered with **. If you tamper with the previous block, the hash value of the hashed version of this block will change because the information in the "hash value of the previous block" contained in the next block will change. (See the following figure)

ブロック改ざん.png

In other words, if you tamper with one block, all subsequent blocks will change. As a result, it is no longer possible to ** rewrite (alter) only one block **.

Finally, I will explain about nonce. A nonce is a ** answer to a question **. So what is the problem? Earlier, I explained that the blockchain is verifying that the transaction is correct when everyone adds a new block. In bitcoin, the verification method is called ** Proof of Work ** (PoW). Nonce is PoW's answer. Proof of Work is just a verification method in bitcoin, and there are several other verification methods. For example, the currency Ripple uses ** Proof of Consensus **, and NEM coin uses ** Proof of Importance **. (For details, search for "Consensus algorithm list")

This Proof of Work uses what is called a nonce when verifying that this block is correct. First, at the time the deal is made (at the stage of trying to add a block), the nonce is not yet known. What we know is the transaction (the content of the transaction) and the hash value of the previous block. Therefore, we find a nonce whose calculation result derived using two known information (transaction and hash value of the previous block) and a nonce such as a variable that we do not yet know has a certain fixed value. (It feels like an equation. It's like looking for a nonce that gives transaction + prev_hash + nonce = Ans (Ans is a fixed answer). Strictly different, but sensuously the same, this calculation Since there is no inverse operation in the method, you just change the nonce value, and if it happens to match, that value will be the final correct nonce.) Proof of Work is the work of changing the nonce value and finding the correct nonce.

** Mining ** means issuing ** new currency in Bitcoin **, and the miner (minor) who succeeded in Proof of Work first will receive the issued coins.

4. Implementation of BlockChain

First, the implementation flow will be explained.

スクリーンショット 2019-12-11 23.44.45.png

This time, I will explain ①② in the above figure. Watch Udemy's video for API conversion of blockchain servers and construction of blockchain networks Click here for Udemy's video.

The creation of blockchain and wallet is also explained here for only about 20% of the total, so please watch the video.

First, create a blockchain class that will be a blueprint. Next, we will implement PoW, nonce and mining (this is Bitcoin only) that make up the blockchain. This is ①.

Next, create a wallet in ②. A wallet is a virtual currency wallet. That's all. Here, we will generate a blockchain address that identifies your personal wallet. Then you will learn about transaction signing and proof for trading cryptocurrencies.

4-1 Implementation of blockchain

4-1.1 Creating a blockchain class

Below is a rough blueprint for the blockchain.

Many of the upcoming ** sender_blockchain_address ** and ** recipient_blockchain_adress ** are senders and recipients. The variables that identify each.

If you have read the explanations so far, there is nothing particularly difficult, so I think you can understand it if you read it as a comment.

import hashlib
import json
import time
class BlockChain(object):

    def __init__(self, blockchain_address=None):
        self.transaction_pool = [] 	#Transactions that have not yet been authenticated
        self.chain = []	#Blockchain to store authenticated transactions
        self.create_block(0, self.hash({})) 
        self.blockchain_address = blockchain_address
        
    #Method to make a block
    def create_block(self, nonce, previous_hash):		 
        """
How to make a new block
        1.List of incomplete transactions(transaction_pool)Get block information from
        2.Add blocks to the blockchain
        3.Empty unfinished transactions
        """
        block = {
            'timestamp': time.time(), #Trading time
            'transactions': self.transaction_pool, #Transaction contents(Bring from a list of unapproved transactions)
            'nonce': nonce, #Nonce
            'previous_hash': previous_hash #Hash value of the previous block
        }
        self.chain.append(block) #Add to blockchain
        self.transaction_pool = [] #Empty the list of unapproved transactions
        return block
  
    #Method to find the hash value of the block
    def hash(self, block):			
        return hashlib.sha256(json.dumps(block).encode()).hexdigest() #Returns the hashed version in hexadecimal
      
    #Method to make a new transaction
    #Make a new deal here and the deal is create_Added to the blockchain with block
    def add_transaction(self, sender_blockchain_address,
                        recipient_blockchain_address, value,
                        sender_public_key=None):
        #Make the content of the transaction
        transaction = {
            'sender_blockchain_address': sender_blockchain_address, #Who sent
            'recipient_blockchain_address': recipient_blockchain_address, #Who received
            'value': float(value) #value(Amount of money)Some
        }
        #Add to unapproved transaction list
        self.transaction_pool.append(transaction)
        return True

4-1.2 Implementation of PoW, nonce, mining

As explained before, PoW (Proof of Work) uses the hash value and nonce of the transaction and the previous block, and changes the nonce until a certain character string is derived from the three to a fixed value. I will continue.

#Method to verify whether it is a fixed value
def valid_proof(self, transactions, previous_hash, nonce,):
        guess_block = {
            'transactions': transactions,
            'nonce': nonce,
            'previous_hash': previous_hash
        }
        guess_hash = self.hash(guess_block)
      	#Returns true if the previous 3 characters are 000, false if not
        return guess_hash[:3] == '0'*3

#A method that keeps changing the nonce value until it reaches a fixed value
def proof_of_work(self):
        transactions = self.transaction_pool.copy()
        previous_hash = self.hash(self.chain[-1])
        nonce = 0
        #Keep changing the nonce value until it reaches the fixed value
        while self.valid_proof(transactions, previous_hash, nonce) is False:
            nonce += 1
        return nonce

First, in the valid_proof method, using the ** transaction and the hash value and nonce of the previous block described earlier, it is verified whether a certain character string derived from those three becomes a fixed value **. I am. guess_block is the tentative block and guess_hash is its hash value. guess_hash is a string derived from three. ** Of course, since it is hashed, there is no inverse operation. ** **

guess_hash [: 3] means the first 3 characters of the guess_hash string. Therefore, this time, we will continue to change the nonce value from the front of guess_hash until the 3 characters become 000.

In the proof_of_work method, the nonce value is changed until the return value of the valid_proof method becomes true. The nonce starts from 0 and the nonce value is incremented by +1 until the answer is reached. The valid_proof method and the proof_of_work method are two and one.

Next, I will explain about minig. As explained earlier, mining is the act of ** issuing new currency in Bitcoin **. The condition for issuing the new currency is the person who succeeded in PoW.

#The currency that can be obtained as a mining reward is the sender(sender)Because there is no
 MINING_SENDER =  'THIS IS MINING SENDER' 
#Decide on mining rewards
 MINING_REWAES = 1
#Mining method
 def mining(self):
    	#The rewards obtained from mining are also transactions, so add them to the unapproved transaction list.
       	self.add_transaction(
            sender_blockchain_address=MINING_SENDER,
            recipient_blockchain_address=self.blockchain_address,
            value=MINING_REWARD)
        nonce = self.proof_of_work()
        previous_hash = self.hash(self.chain[-1]) #Hash the previous block
        #Create a block using the nonce and the hash value of the previous block
        self.create_block(nonce, previous_hash) 
        return True

As you can see in the program above, we are just sending MINING_REWAES to the PoW address. At this time, the remittance source is MINING_SENDER because there is no remittance source when issuing new currency in mining.

All that's left is to save the transaction as a block.

4-2. Creating a wallet

The wallet has nothing to do with the blockchain, it just acts as a ** wallet in cryptocurrencies **, so we will only discuss transaction signing and proof.

Now let's take a closer look at blockchain addresses. First, everyone involved in the blockchain has a ** public key ** and a ** private key **. The public and private keys are a mechanism for encryption (please gg for details). Since the individual is identified by this public key and private key, the identification that the virtual currency transaction was sent from whom to whom can be saved by this public key and private key string. However, the public key and private key strings are very long strings, and storing these long strings for every transaction would put a lot of pressure on the capacity of the blockchain as a database. So it would be nice if there was something like an address that could identify an individual with a shorter string. That is the blockchain address. This blockchain address is generated from the public and private keys. The mechanism is complicated and I don't understand it (almost copy and paste), so if you want to know how to generate a blockchain, please take a Udemy course.

4-2.1 Transaction signing and certification

Transaction signing and proof is a proof that when a transaction is sent from a wallet to the computers that make up P2P, it is ** really sent by that person **. What it means is that it is correct if Mr. A sends the information that "Mr. A sends 100 yen to Mr. B", but it is wrong if it is sent from Mr. C. It is a proof of that. To prove it, we will send ** A's public key **, ** transaction **, and ** Signature ** as a set. A Signature is a string generated from a private key and a transaction. Creating a Sinature and sending a public key, transaction, and signature is called a ** signature **. Then, receiving the public key, transaction, and signature and verifying that they are correct is called ** proof **.

class Transaction(object):

    def __init__(self, sender_private_key, sender_public_key,
                 sender_blockchain_address, recipient_blockchain_address,
                 value):
        self.sender_private_key = sender_private_key
        self.sender_public_key = sender_public_key
        self.sender_blockchain_address = sender_blockchain_address
        self.recipient_blockchain_address = recipient_blockchain_address
        self.value = value

    def generate_signature(self):
        sha256 = hashlib.sha256() #use sha256
        #Make a transaction
        transaction ={ 
            'sender_blockchain_address': self.sender_blockchain_address,
            'recipient_blockchain_address': self.recipient_blockchain_address,
            'value': float(self.value)
        }
        sha256.update(str(transaction).encode('utf-8'))
        message = sha256.digest()
        private_key = SigningKey.from_string(
            bytes().fromhex(self.sender_private_key), curve=NIST256p)
        private_key_sign = private_key.sign(message)
        signature= private_key_sign.hex()
        return signature

↑ Signature program


def verify_transaction_signature(
            self, sender_public_key, signature, transaction):
        sha256 = hashlib.sha256()
        sha256.update(str(transaction).encode('utf-8'))
        message = sha256.digest()
        signature_bytes = bytes().fromhex(signature)
        verifying_key = VerifyingKey.from_string(
            bytes().fromhex(sender_public_key), curve=NIST256p)
        verified_key = verifying_key.verify(signature_bytes, message)
        return verified_key

↑ Proof program

5. The future position of BlockChain

After learning blockchain, you will understand why you need this technology.

5-1. Advantages and disadvantages of blockchain

As anyone who has read the article so far will understand, let's check the advantages and disadvantages of blockchain again.

There was an article written in more detail, so I think you should read it. Click here for articles

The first advantage is that it is ** decentralized **. By joining your computer to the blockchain network, you don't have to concentrate your data and power in one place. Facebook has all the data, just like the concentration of power. Power is dispersed by managing the data together.

Next is to build a ** trusted network **. Since we are building a network with many computers, the maintenance rate and performance will be higher than building a network with one computer.

And it means that it cannot be tampered with **. That's because the block contains a string that hashes the previous block.

First of all, the disadvantage is that the power consumption on the user side is large. Since PoW keeps calculating, power consumption will increase. Therefore, in Bitcoin mining, it seems that there are not many new participants because the electricity cost of power consumption for mining is not worth the rewards received from mining.

You can also prevent them from duplicating anything. I think that the value of technology that cannot be duplicated will be created only in the age when anything can be duplicated by a computer.

5-2. Blockchain business example

I would like to introduce a business that I personally found interesting.

1.Bitcoin Well, it's a virtual currency that everyone knows. I will not explain in particular. Bitcoin.org

2.bPassport It is the one that manages personal information under development by Bitflyer. Recently, unauthorized buying and selling of personal information between companies has become a problem, so it is important for individuals to be able to firmly select which company to provide personal information to. https://crypto.watch.impress.co.jp/docs/event/1210425.html

3.Verisart veriart helps to distinguish between fake and genuine by storing the image data of the artwork on the blockchain. I found it very interesting that art and technology are connected. https://verisart.com

etc I found a cohesive link, so I will introduce it. https://innovation.mufg.jp/detail/id=322

6. Finally

References include books and articles that are not directly related to this article but have been very helpful in your studies.

6-1. Acknowledgments

I'm glad to cry if you like it to keep me motivated !!

6-2. References

The following documents have been very helpful and will be introduced.

Course content Understand how blockchain works. Learn the basic development of blockchain using Python Understand the authentication of blockchain transactions. You can create a hash mechanism that connects blockchains. Understand the consensus algorithm that derives the nonce in mining blockchain. Understand how blockchain decentralized consensus building consensus works. Understand the mechanism of sending and receiving virtual currency.

Recommended Posts