Home  >  Article  >  Backend Development  >  Build your first Python blockchain project from scratch

Build your first Python blockchain project from scratch

WBOY
WBOYforward
2024-02-24 21:10:02940browse

Build your first Python blockchain project from scratch

1. Blockchain Overview

Blockchain is a distributeddatabase used to record transactions in a secure, transparent and tamper-proof manner . It consists of a chain-like structure in which each block contains a certain amount of transaction information, the hash of the previous block and other metadata. The core technology of blockchain is distributed ledger and consensus mechanism, which is essentially a decentralized database.

2. Blockchain implementation in Python

First, we create a new pythonproject and install the necessary libraries.

Python
import hashlib
import JSON
from datetime import datetime

Then, we create a new blockchain class.

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

def create_genesis_block(self):
"""
创建创世区块
"""
genesis_block = {
"index": 0,
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"data": "Genesis block",
"previous_hash": "0",
}
self.chain.append(genesis_block)

def add_block(self, data):
"""
添加新区块到区块链中
"""
new_block = {
"index": len(self.chain),
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"data": data,
"previous_hash": self.chain[-1]["hash"],
}
self.chain.append(new_block)

def get_block_hash(self, block):
"""
获取区块的哈希值
"""
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()

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["previous_hash"] != self.get_block_hash(previous_block):
return False
if self.get_block_hash(current_block) != current_block["hash"]:
return False
return True

3. Run the blockchain

Now, we can run our blockchain.

python
blockchain = Blockchain()
blockchain.add_block("Hello, world!")
blockchain.add_block("This is a test.")
print(blockchain.chain)

The output results are as follows:

[
{
"index": 0,
"timestamp": "2023-03-08 15:46:17",
"data": "Genesis block",
"previous_hash": "0",
},
{
"index": 1,
"timestamp": "2023-03-08 15:46:18",
"data": "Hello, world!",
"previous_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
},
{
"index": 2,
"timestamp": "2023-03-08 15:46:19",
"data": "This is a test.",
"previous_hash": "0a753b9f3c2650581980d3D1d1b47f56d63e6c27b813b7ec4461863b4c724a2f",
}
]

4 Conclusion

Through this article, you have understood the basic concepts of blockchain and learned how to use Python to implement a simple blockchain. You can use this as a basis to further explore blockchain applications and development.

The above is the detailed content of Build your first Python blockchain project from scratch. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete