파이썬으로 블록체인 네트워크 구축하기

In recent years, blockchain technology has gained significant attention for its potential to revolutionize various industries. If you are interested in understanding how a blockchain network works and want to build your own from scratch using Python, this blog post is for you!

What is a Blockchain?

A blockchain is a decentralized and distributed ledger that records transactions across multiple computers in a network. It is designed to be transparent, secure, and immutable. Each transaction is stored in a block, which is linked to the previous block using cryptographic hashes, forming a chain of blocks.

Getting Started

To build a basic blockchain network using Python, we will need a few key components:

  1. Block: A class that represents a block in the blockchain.
  2. Blockchain: A class that manages the chain of blocks.
  3. Cryptography: A library to generate and verify cryptographic hashes.

Implementing the Block Class

First, let’s create a Block class that will hold the transaction data, timestamp, previous hash, and generate a unique hash for each block.

class Block:
    def __init__(self, data, previous_hash):
        self.data = data
        self.timestamp = datetime.now()
        self.previous_hash = previous_hash
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        return hashlib.sha256((str(self.timestamp) + str(self.data) + str(self.previous_hash)).encode()).hexdigest()

Implementing the Blockchain Class

Next, we need a Blockchain class that will manage the chain of blocks and provide methods to add new blocks and validate the integrity of the chain.

class Blockchain:
    def __init__(self):
        self.chain = [self.create_genesis_block()]

    def create_genesis_block(self):
        return Block("Genesis Block", "0")

    def get_latest_block(self):
        return self.chain[-1]

    def add_block(self, new_block):
        new_block.previous_hash = self.get_latest_block().hash
        new_block.hash = new_block.calculate_hash()
        self.chain.append(new_block)

    def is_chain_valid(self):
        for i in range(1, len(self.chain)):
            current_block = self.chain[i]
            previous_block = self.chain[i - 1]

            if current_block.hash != current_block.calculate_hash():
                return False

            if current_block.previous_hash != previous_block.hash:
                return False

        return True

Testing the Blockchain

Now, let’s test our blockchain network by creating an instance of the Blockchain class and adding some sample blocks.

# Create a new Blockchain
my_blockchain = Blockchain()

# Add new blocks to the chain
my_blockchain.add_block(Block("Transaction 1", ""))
my_blockchain.add_block(Block("Transaction 2", ""))
my_blockchain.add_block(Block("Transaction 3", ""))

# Check if the chain is valid
is_valid = my_blockchain.is_chain_valid()

print("Is the blockchain valid?", is_valid)

Conclusion

Building a blockchain network from scratch may seem complex at first, but by understanding the fundamental concepts and using Python, it becomes more accessible. In this blog post, we implemented basic classes to represent blocks and manage the chain in a blockchain network. This is just the beginning, and there are many more advanced topics and features to explore in the world of blockchain development.

#python #blockchain