已经使用Geth搭建私有链,连接matemask,使用remix部署好智能合约。 智能合约(remix)代码片段:
// 注册新用户
function register(string memory _username, bytes32 _passwordHash) public {
require(usernameToId[_username] == 0, "Username already exists");
// 分配新ID,并立即递增以备下次使用
uint256 newId = currentId++;
// 创建新用户
User memory newUser = User({
username: _username,
passwordHash: _passwordHash,
id: newId
});
// 在映射中存储新用户和用户名到ID的映射
users[newId] = newUser;
usernameToId[_username] = newId;
// 触发事件
emit UserRegistered(newId, _username);
}
// 用户登录
// 此函数现在返回用户的ID和密码的哈希,而不是验证密码
function login(string memory _username) public view returns (uint256 userId, bytes32 passwordHash) {
userId = usernameToId[_username];
require(userId != 0, "User does not exist");
passwordHash = users[userId].passwordHash;
}
web3.py部分片段:
tx_hash_register = user_management.register_user("user1", "user1pass", from_address, private_key)
print(f"Transaction hash (register): {tx_hash_register}")
time.sleep(3)
# 获取交易收据
tx_receipt = user_management.w3.eth.get_transaction_receipt(tx_hash_register)
# 检查状态字段以确认交易是否成功
if tx_receipt is not None and tx_receipt.status == 1:
print(f"Transaction {tx_hash_register} was successful.")
else:
print(f"Transaction {tx_hash_register} failed or is pending.")
username = "user1"
if user_management.user_exists(username):
print(f"User {username} exists.")
else:
print(f"User {username} does not exist or another error occurred.")
执行结果: Transaction hash (register): 0xd09f279169969791e08f7cdf10f896fe5d7bed6e4ce326cfd79e16948e8a2cd9 Transaction 0xd09f279169969791e08f7cdf10f896fe5d7bed6e4ce326cfd79e16948e8a2cd9 was successful. An exception occurred: Could not transact with/call contract function, is contract deployed correctly and chain synced? User user1 does not exist or another error occurred. 可以正确调用智能合约的register(),且成功创建区块存储信息,但是却无法调用login()。错误信息为:An exception occurred: Could not transact with/call contract function, is contract deployed correctly and chain synced? 请问各位有什么解决方法。