1. 基于区块链的土地交易平台
from web3 import Web3
import json
# 连接到节点
w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
# 检查连接
if w3.isConnected():
print("Connected to Ethereum node")
else:
print("Connection failed")
# 部署合约
compiled_sol = json.load(open('LandContract.json'))
bytecode = compiled_sol['contracts']['LandContract.sol']['LandContract']['evm']['bytecode']['object']
abi = compiled_sol['contracts']['LandContract.sol']['LandContract']['abi']
LandContract = w3.eth.contract(abi=abi, bytecode=bytecode)
tx_hash = LandContract.constructor().transact({'from': w3.eth.accounts[0]})
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
# 合约实例
land_contract = w3.eth.contract(address=tx_receipt.contractAddress, abi=abi)
# 定义交易功能
def create_land(owner, location, size):
tx_hash = land_contract.functions.createLand(owner, location, size).transact({'from': owner})
w3.eth.waitForTransactionReceipt(tx_hash)
print(f"Land created at {location} with size {size}")
def transfer_land(land_id, new_owner):
tx_hash = land_contract.functions.transferLand(land_id, new_owner).transact({'from': w3.eth.accounts[0]})
w3.eth.waitForTransactionReceipt(tx_hash)
print(f"Land ID {land_id} transferred to {new_owner}")
# 示例交易
create_land(w3.eth.accounts[1], "Location1", 100)
transfer_land(0, w3.eth.accounts[2])