第2課

Building the Structure of the Blockchain

In this lesson, we will focus on building the structure of blockchain. We will define the necessary functions and methods to create and manage blocks, add blocks to the blockchain, and validate the integrity of the chain.

2.1 Creating the Blockchain Class

  1. Open the blockchain.py file in your code editor.

  2. Define a Blockchain class: This class will represent blockchain and hold the necessary methods to manage blocks and the chain itself.

    Python
    pythonCopy code
    class Blockchain:
     def __init__(self):
         self.chain = []
    

    This code defines a Blockchain class with an empty list called chain to store the blocks.

2.2 Adding Blocks to Blockchain

  1. Implement the add_block method: This method will be used to add blocks to the blockchain. It will take a block object as a parameter and append it to the chain.

    Python
    pythonCopy code
    class Blockchain:
     def __init__(self):
         self.chain = []
    
     def add_block(self, block):
         self.chain.append(block)
    

    This code adds the add_block method to the Blockchain class.

  2. Test adding blocks to the blockchain: In the main part of your code, after the class definition, create a new instance of the Blockchain class. Then, create a new block object and add it to the blockchain using the add_block method.
    ```
    Python
    pythonCopy code
    blockchain = Blockchain()

Create a new block

new_block = Block(1, datetime.datetime.now(), “Sample Data”, “previous_hash”, 0)

Add the block to the blockchain

blockchain.add_block(new_block)

This code creates a new instance of the `Blockchain` class, creates a new block object with some sample data, and adds it to the blockchain using the `add_block` method.


## 2.3 Validating Blockchain



1. 
Implement the `is_valid` method: This method will be used to validate the integrity of the blockchain. It will iterate through each block in the chain and verify that the hash of each block matches the previous block's hash.

Python
pythonCopy code
class Blockchain:
def init(self):
self.chain = []

def add_block(self, block):
    self.chain.append(block)

def is_valid(self):
    for i in range(1, len(self.chain)):
        current_block = self.chain[i]
        previous_block = self.chain[i - 1]
        if current_block.previous_hash != previous_block.hash():
            return Falsereturn True
This code adds the `is_valid` method to the `Blockchain` class.

1. 
Test the blockchain validation: After adding blocks to the blockchain, call the `is_valid` method to check if the blockchain is valid.

Python
pythonCopy code

Create some blocks and add them to the blockchain# Validate the blockchainif blockchain.is_valid():

print("Blockchain is valid.")

else:
print(“Blockchain is invalid.”)



This code validates the blockchain by calling the `is_valid` method and prints an appropriate message based on the result.


## 2.4 Testing the Blockchain


1. 
Add more blocks to the blockchain: Create additional blocks using different data and previous hashes and add them to the blockchain using the `add_block` method.
Python
pythonCopy code
#Create more blocks
block2 = Block(2, datetime.datetime.now(), "More Data", new_block.hash(), 0)
block3 = Block(3, datetime.datetime.now(), "Even More Data", block2.hash(), 0)

#Add the blocks to the blockchain
blockchain.add_block(block2)
blockchain.add_block(block3)
This code creates two additional blocks and adds them to the blockchain.

1. 
Test the blockchain validation again: After adding the new blocks, call the `is_valid` method to check the validity of the blockchain.
Python
pythonCopy code
# Validate the blockchainif blockchain.is_valid():
print("Blockchain is valid.")
else:
print("Blockchain is invalid.")
```

This code validates the blockchain and prints the result.

2.5 Conclusion

In this lesson, we have built the structure of our blockchain. We created a Blockchain class and implemented methods to add blocks to the chain and validate its integrity. We also tested blockchain by adding blocks and checking its validity.

免責聲明
* 投資有風險,入市須謹慎。本課程不作為投資理財建議。
* 本課程由入駐Gate Learn的作者創作,觀點僅代表作者本人,絕不代表Gate Learn讚同其觀點或證實其描述。
目錄
第2課

Building the Structure of the Blockchain

In this lesson, we will focus on building the structure of blockchain. We will define the necessary functions and methods to create and manage blocks, add blocks to the blockchain, and validate the integrity of the chain.

2.1 Creating the Blockchain Class

  1. Open the blockchain.py file in your code editor.

  2. Define a Blockchain class: This class will represent blockchain and hold the necessary methods to manage blocks and the chain itself.

    Python
    pythonCopy code
    class Blockchain:
     def __init__(self):
         self.chain = []
    

    This code defines a Blockchain class with an empty list called chain to store the blocks.

2.2 Adding Blocks to Blockchain

  1. Implement the add_block method: This method will be used to add blocks to the blockchain. It will take a block object as a parameter and append it to the chain.

    Python
    pythonCopy code
    class Blockchain:
     def __init__(self):
         self.chain = []
    
     def add_block(self, block):
         self.chain.append(block)
    

    This code adds the add_block method to the Blockchain class.

  2. Test adding blocks to the blockchain: In the main part of your code, after the class definition, create a new instance of the Blockchain class. Then, create a new block object and add it to the blockchain using the add_block method.
    ```
    Python
    pythonCopy code
    blockchain = Blockchain()

Create a new block

new_block = Block(1, datetime.datetime.now(), “Sample Data”, “previous_hash”, 0)

Add the block to the blockchain

blockchain.add_block(new_block)

This code creates a new instance of the `Blockchain` class, creates a new block object with some sample data, and adds it to the blockchain using the `add_block` method.


## 2.3 Validating Blockchain



1. 
Implement the `is_valid` method: This method will be used to validate the integrity of the blockchain. It will iterate through each block in the chain and verify that the hash of each block matches the previous block's hash.

Python
pythonCopy code
class Blockchain:
def init(self):
self.chain = []

def add_block(self, block):
    self.chain.append(block)

def is_valid(self):
    for i in range(1, len(self.chain)):
        current_block = self.chain[i]
        previous_block = self.chain[i - 1]
        if current_block.previous_hash != previous_block.hash():
            return Falsereturn True
This code adds the `is_valid` method to the `Blockchain` class.

1. 
Test the blockchain validation: After adding blocks to the blockchain, call the `is_valid` method to check if the blockchain is valid.

Python
pythonCopy code

Create some blocks and add them to the blockchain# Validate the blockchainif blockchain.is_valid():

print("Blockchain is valid.")

else:
print(“Blockchain is invalid.”)



This code validates the blockchain by calling the `is_valid` method and prints an appropriate message based on the result.


## 2.4 Testing the Blockchain


1. 
Add more blocks to the blockchain: Create additional blocks using different data and previous hashes and add them to the blockchain using the `add_block` method.
Python
pythonCopy code
#Create more blocks
block2 = Block(2, datetime.datetime.now(), "More Data", new_block.hash(), 0)
block3 = Block(3, datetime.datetime.now(), "Even More Data", block2.hash(), 0)

#Add the blocks to the blockchain
blockchain.add_block(block2)
blockchain.add_block(block3)
This code creates two additional blocks and adds them to the blockchain.

1. 
Test the blockchain validation again: After adding the new blocks, call the `is_valid` method to check the validity of the blockchain.
Python
pythonCopy code
# Validate the blockchainif blockchain.is_valid():
print("Blockchain is valid.")
else:
print("Blockchain is invalid.")
```

This code validates the blockchain and prints the result.

2.5 Conclusion

In this lesson, we have built the structure of our blockchain. We created a Blockchain class and implemented methods to add blocks to the chain and validate its integrity. We also tested blockchain by adding blocks and checking its validity.

免責聲明
* 投資有風險,入市須謹慎。本課程不作為投資理財建議。
* 本課程由入駐Gate Learn的作者創作,觀點僅代表作者本人,絕不代表Gate Learn讚同其觀點或證實其描述。