区块链的基本构思是保障数据的安全、透明和去

          时间:2025-07-21 15:39:13

          主页 > 数字货币 >

          区块链的基本构思是保障数据的安全、透明和去中心化。以下是一个简单的区块链的Python实现代码示例,这段代码定义了一个区块和一个区块链的基本形式。

```python
import hashlib
import time

class Block:
    def __init__(self, index, previous_hash, timestamp, data, hash):
        self.index = index
        self.previous_hash = previous_hash
        self.timestamp = timestamp
        self.data = data
        self.hash = hash

    @staticmethod
    def calculate_hash(index, previous_hash, timestamp, data):
        value = str(index)   previous_hash   str(timestamp)   data
        return hashlib.sha256(value.encode()).hexdigest()

class Blockchain:
    def __init__(self):
        self.chain = []
        self.create_block(previous_hash='0')

    def create_block(self, data):
        index = len(self.chain)   1
        previous_hash = self.chain[-1].hash if self.chain else '0'
        timestamp = time.time()
        hash = Block.calculate_hash(index, previous_hash, timestamp, data)
        block = Block(index, previous_hash, timestamp, data, hash)
        self.chain.append(block)
        return block

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

# 示例如何创建一个区块链
if __name__ == 区块链的基本构思是保障数据的安全、透明和去中心化。以下是一个简单的区块链的Python实现代码示例,这段代码定义了一个区块和一个区块链的基本形式。

```python
import hashlib
import time

class Block:
    def __init__(self, index, previous_hash, timestamp, data, hash):
        self.index = index
        self.previous_hash = previous_hash
        self.timestamp = timestamp
        self.data = data
        self.hash = hash

    @staticmethod
    def calculate_hash(index, previous_hash, timestamp, data):
        value = str(index)   previous_hash   str(timestamp)   data
        return hashlib.sha256(value.encode()).hexdigest()

class Blockchain:
    def __init__(self):
        self.chain = []
        self.create_block(previous_hash='0')

    def create_block(self, data):
        index = len(self.chain)   1
        previous_hash = self.chain[-1].hash if self.chain else '0'
        timestamp = time.time()
        hash = Block.calculate_hash(index, previous_hash, timestamp, data)
        block = Block(index, previous_hash, timestamp, data, hash)
        self.chain.append(block)
        return block

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

# 示例如何创建一个区块链
if __name__ ==