// SPDX-License-Identifier: CC0-1.0
pragmasolidity^0.8.19;import{OwnableUpgradeable}from"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";import{UniversalCharter}from"./UniversalCharter.sol";// Interfaces
import{IUniversalIdentity}from"./interface/IUniversalIdentity.sol";import{IUniversalCharter}from"./interface/IUniversalCharter.sol";/// @title UniversalIdentity
/// @notice UniversalIdentity 合约用于管理机器人的身份。
contractUniversalIdentityisIUniversalIdentity,OwnableUpgradeable{/// @notice 合约当前实现的版本标识符。
stringpublicconstantVERSION="v0.0.1";/// @notice 用于存储机器人已同意遵守的规则的映射
mapping(bytes=>bool)privaterobotRules;/// @notice 用于存储每个规则的链下合规性状态的映射
mapping(bytes=>bool)privatecomplianceStatus;/// @notice 跟踪机器人订阅的章程
mapping(address=>bool)privatesubscribedCharters;/// @notice 用于节省 revert gas 的自定义错误
errorRuleNotAgreed(bytesrule);errorRuleNotCompliant(bytesrule);errorRuleAlreadyAdded(bytesrule);/// @dev 用于在检查合规性时发出的事件
/// @param updater 合规性更新器(合约所有者)的地址
/// @param rule 已检查的规则
eventComplianceChecked(addressindexedupdater,bytesrule);/// @notice 用于检查规则是否存在的修饰符
modifierruleExists(bytesmemoryrule){require(robotRules[rule],"Rule does not exist");_;}/// @notice 用于设置所有者的构造函数
constructor(){initialize({_owner:address(0xdEaD)});}/// @dev 初始化函数
functioninitialize(address_owner)publicinitializer{__Ownable_init();transferOwnership(_owner);hardwareIdentity=_hardwareIdentity;}/// @notice 获取硬件身份信息
functiongetHardwareIdentity()externalviewreturns(HardwareIdentitymemory){returnhardwareIdentity;}/// @notice 为硬件验证生成新的挑战
functiongenerateChallenge()externalreturns(bytes32){bytes32challenge=keccak256(abi.encodePacked(block.timestamp,block.prevrandao,msg.sender));activeChallenge[challenge]=true;returnchallenge;}/// @notice 验证对特定挑战的响应
functionverifyChallenge(bytes32challenge,bytesmemorysignature)externalreturns(bool){if(!activeChallenge[challenge]){revertInvalidChallenge();}// Remove challenge after use
// 使用后删除挑战
deleteactiveChallenge[challenge];// Verify the signature using ECDSA
// 使用 ECDSA 验证签名
bytes32messageHash=keccak256(abi.encodePacked(challenge));bytes32ethSignedMessageHash=ECDSA.toEthSignedMessageHash(messageHash);addresssigner=ECDSA.recover(ethSignedMessageHash,signature);// Convert hardware public key to address for comparison
// 将硬件公钥转换为地址以进行比较
addresshardwareAddress=address(uint160(uint256(hardwareIdentity.publicKey)));if(signer!=hardwareAddress){revertInvalidSignature();}returntrue;}/// @notice 更新硬件身份信息
/// @param _hardwareIdentity 新的硬件身份信息
functionupdateHardwareIdentity(HardwareIdentitymemory_hardwareIdentity)externalonlyOwner{hardwareIdentity=_hardwareIdentity;}/// @notice 向机器人的身份添加规则
/// @param rule 表示机器人同意遵守的规则的动态字节数组。
functionaddRule(bytesmemoryrule)externaloverrideonlyOwner{if(robotRules[rule]){revertRuleAlreadyAdded(rule);}// Add rule to the mapping
// 将规则添加到映射
robotRules[rule]=true;emitRuleAdded(rule);}/// @notice 从机器人的身份中删除规则
/// @param rule 表示机器人不再同意遵守的规则的动态字节数组。
functionremoveRule(bytesmemoryrule)externaloverrideonlyOwnerruleExists(rule){robotRules[rule]=false;complianceStatus[rule]=false;emitRuleRemoved(rule);}/// @notice 使用其存储的规则集订阅和注册到特定的 UniversalCharter 合约
/// @param charter UniversalCharter 合约的地址
/// @param version 要获取和注册的规则集的版本
functionsubscribeAndRegisterToCharter(addresscharter,uint256version)external{require(!subscribedCharters[charter],"Already subscribed to this charter");subscribedCharters[charter]=true;// Fetch the rule set directly from the UniversalCharter contract using the public getter
// 使用公共 getter 直接从 UniversalCharter 合约获取规则集
bytes[]memoryruleSet=UniversalCharter(charter).getRuleSet(version);// Register as a robot in the charter using the fetched rule set
// 使用获取的规则集在章程中注册为机器人
UniversalCharter(charter).registerUser(IUniversalCharter.UserType.Robot,ruleSet);emitSubscribedToCharter(charter);}/// @notice 离开特定 UniversalCharter 合约的系统
/// @param charter 要离开的 UniversalCharter 合约的地址
functionleaveCharter(addresscharter)external{require(subscribedCharters[charter],"Not subscribed to this charter");// Call the leaveSystem function of the UniversalCharter contract
// 调用 UniversalCharter 合约的 leaveSystem 函数
UniversalCharter(charter).leaveSystem();// Unsubscribe from the charter after leaving
// 离开后从章程取消订阅
subscribedCharters[charter]=false;emitUnsubscribedFromCharter(charter);}/// @notice 更新规则的合规性状态(由所有者调用)
/// @param rule 表示规则的动态字节数组
/// @param status 合规性状态(如果合规,则为 true;如果不合规,则为 false)
functionupdateCompliance(bytesmemoryrule,boolstatus)externalonlyOwnerruleExists(rule){complianceStatus[rule]=status;emitComplianceChecked(msg.sender,rule);}/// @notice 检查机器人是否同意遵守特定规则以及是否合规
/// @param rule 要检查的规则。
/// @return bool 如果机器人已同意该规则并且合规,则返回 true
functioncheckCompliance(bytesmemoryrule)externalviewoverridereturns(bool){if(!robotRules[rule]){revertRuleNotAgreed(rule);}returntrue;}/// @notice 获取规则的合规性状态
/// @param rule 要检查的规则。
functiongetRule(bytesmemoryrule)externalviewreturns(bool){returnrobotRules[rule];}/// @notice 获取章程的订阅状态
/// @param charter 要检查的章程的地址。
functiongetSubscribedCharters(addresscharter)externalviewreturns(bool){returnsubscribedCharters[charter];}/// @notice 获取规则的合规性状态
/// @param rule 要检查的规则。
functiongetComplianceStatus(bytesmemoryrule)externalviewreturns(bool){returncomplianceStatus[rule];}}
// SPDX-License-Identifier: CC0-1.0
pragmasolidity0.8.20;import{OwnableUpgradeable}from"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";import{SystemConfig}from"./SystemConfig.sol";// Interfaces
import{IUniversalCharter}from"./interface/IUniversalCharter.sol";import{IUniversalIdentity}from"./interface/IUniversalIdentity.sol";/// @title UniversalCharter
/// @notice UniversalCharter 合约用于管理用户的注册和合规性。
contractUniversalCharterisIUniversalCharter,OwnableUpgradeable{/// @notice 用于存储有关注册用户信息的结构体
structUserInfo{boolisRegistered;UserTypeuserType;uint256ruleSetVersion;// 用户遵循的规则集版本
}/// @notice 用于存储注册用户的映射
mapping(address=>UserInfo)privateusers;/// @notice 用于按版本号存储规则集的映射
mapping(uint256=>bytes[])privateruleSets;/// @notice 用于跟踪规则集哈希及其对应版本的映射
mapping(bytes32=>uint256)privateruleSetVersions;/// @notice 合约当前实现的版本标识符。
stringpublicconstantVERSION="v0.0.1";/// @notice 用于跟踪规则集当前版本的变量
uint256privatecurrentVersion;/// @notice 用于存储 SystemConfig 合约地址的变量
SystemConfigpublicsystemConfig;/// @notice 当暂停时无法调用方法时的错误。 这将来可能会重命名为“Paused”,但它与“Paused”事件冲突。
errorCallPaused();/// @notice 当暂停时恢复。
modifierwhenNotPaused(){if(paused())revertCallPaused();_;}/// @notice 构建 UniversalCharter 合约。
constructor(){initialize({_owner:address(0xdEaD),_systemConfig:address(0xdEaD)});}/// @dev 初始化函数
functioninitialize(address_owner,address_systemConfig)publicinitializer{__Ownable_init();transferOwnership(_owner);systemConfig=SystemConfig(_systemConfig);}/// @notice 通过同意规则集注册用户(无论是人类还是机器人)
/// @param userType 用户的类型:人类或机器人
/// @param ruleSet 用户同意遵守的单个规则数组
functionregisterUser(UserTypeuserType,bytes[]memoryruleSet)externaloverridewhenNotPaused{require(!users[msg.sender].isRegistered,"User already registered");// Hash the rule set to find the corresponding version
// 哈希规则集以查找相应的版本
bytes32ruleSetHash=keccak256(abi.encode(ruleSet));uint256version=ruleSetVersions[ruleSetHash];require(version>0,"Invalid or unregistered rule set");// For robots, ensure compliance with each rule via the UniversalIdentity contract
// 对于机器人,请确保通过 UniversalIdentity 合约遵守每个规则
if(userType==UserType.Robot){require(_checkRobotCompliance(msg.sender,version),"Robot not compliant with rule set");}// Register the user with the versioned rule set
// 使用版本控制的规则集注册用户
users[msg.sender]=UserInfo({isRegistered:true,userType:userType,ruleSetVersion:version});emitUserRegistered(msg.sender,userType,ruleSet);}/// @notice 允许用户(人类或机器人)在通过合规性检查后离开系统
functionleaveSystem()externaloverridewhenNotPaused{require(users[msg.sender].isRegistered,"User not registered");UserInfomemoryuserInfo=users[msg.sender];// For robots, verify compliance with all rules in the rule set
// 对于机器人,验证规则集中所有规则的合规性
uint256version=userInfo.ruleSetVersion;if(userInfo.userType==UserType.Robot){require(_checkRobotCompliance(msg.sender,version),"Robot not compliant with rule set");}users[msg.sender]=UserInfo({isRegistered:false,userType:UserType.Human,ruleSetVersion:0});emitUserLeft(msg.sender);}/// @notice Internal function to verify robot hardware identity
// 用于验证机器人硬件身份的内部函数
/// @param robotAddress The address of the robot to verify
// 要验证的机器人的地址
/// @return bool Returns true if hardware verification succeeds
// 如果硬件验证成功,则返回 true
function_verifyRobotHardware(addressrobotAddress)internalreturns(bool){IUniversalIdentityrobot=IUniversalIdentity(robotAddress);// Get hardware identity to ensure it exists
// 获取硬件身份以确保其存在
robot.getHardwareIdentity();// Generate a new challenge
// 生成新的挑战
bytes32challenge=robot.generateChallenge();// Store the challenge for future reference
// 存储挑战以供将来参考
users[robotAddress].lastVerifiedChallenge=challenge;// Get signature from the robot (this would typically happen off-chain)
// 从机器人获取签名(这通常会发生在链下)
// For this implementation, we'll assume the signature is provided in a separate tx
// 对于此实现,我们将假设签名是在单独的 tx 中提供的
// and just verify the challenge exists
// 并仅验证挑战是否存在
returnchallenge!=0;}/// @notice 检查用户是否符合其注册规则集
/// @param user 用户(人类或机器人)的地址
/// @param ruleSet 要验证的单个规则数组
/// @return bool 如果用户符合给定的规则集,则返回 true
functioncheckCompliance(addressuser,bytes[]memoryruleSet)externalviewoverridereturns(bool){require(users[user].isRegistered,"User not registered");// Hash the provided rule set to find the corresponding version
// 哈希提供的规则集以查找相应的版本
bytes32ruleSetHash=keccak256(abi.encode(ruleSet));uint256version=ruleSetVersions[ruleSetHash];require(version>0,"Invalid or unregistered rule set");require(users[user].ruleSetVersion==version,"Rule set version mismatch");// For robots, check compliance with each rule in the UniversalIdentity contract
// 对于机器人,请检查 UniversalIdentity 合约中每个规则的合规性
if(users[user].userType==UserType.Robot){return_checkRobotCompliance(user,version);}// If the user is human, compliance is assumed for now (can be extended)
// 如果用户是人类,则目前假定合规(可以扩展)
returntrue;}/// @notice Internal function to check compliance for robots with their rule set version
// 用于检查机器人是否符合其规则集版本的内部函数
/// @dev This function will revert if the robot is not compliant with any rule. Returns true for view purposes.
// @dev 如果机器人不符合任何规则,此函数将恢复。 出于视图目的返回 true。
/// @param robotAddress The address of the robot
// 机器人的地址
/// @param version The version of the rule set to verify compliance with
// 用于验证合规性的规则集版本
/// @return bool Returns true if the robot is compliant with all the rules in the rule set
// 如果机器人符合规则集中的所有规则,则返回 true
function_checkRobotCompliance(addressrobotAddress,uint256version)internalviewreturns(bool){IUniversalIdentityrobot=IUniversalIdentity(robotAddress);bytes[]memoryrules=ruleSets[version];for(uint256i=0;i<rules.length;i++){if(!robot.checkCompliance(rules[i])){returnfalse;}}returntrue;}/// @notice Updates or defines a new rule set version.
// 更新或定义新的规则集版本。
/// @param newRuleSet The array of new individual rules.
// 新的单个规则数组。
/// @dev This function SHOULD be restricted to authorized users (e.g., contract owner).
// @dev 此函数应该仅限于授权用户(例如,合约所有者)。
functionupdateRuleSet(bytes[]memorynewRuleSet)externalwhenNotPausedonlyOwner{require(newRuleSet.length>0,"Cannot update to an empty rule set");// Hash the new rule set and ensure it's not already registered
// 哈希新的规则集并确保尚未注册
bytes32ruleSetHash=keccak256(abi.encode(newRuleSet));require(ruleSetVersions[ruleSetHash]==0,"Rule set already registered");// Increment the version and store the new rule set
// 递增版本并存储新的规则集
currentVersion+=1;ruleSets[currentVersion]=newRuleSet;ruleSetVersions[ruleSetHash]=currentVersion;emitRuleSetUpdated(newRuleSet,msg.sender);}/// @notice Getter for the latest version of the rule set.
// 规则集最新版本的 Getter。
functiongetLatestRuleSetVersion()externalviewreturns(uint256){returncurrentVersion;}/// @notice Get the rule set for a specific version.
// 获取特定版本的规则集。
/// @param version The version of the rule set to retrieve.
// 要检索的规则集版本。
functiongetRuleSet(uint256version)externalviewreturns(bytes[]memory){returnruleSets[version];}/// @notice Get the version number for a specific rule set.
// 获取特定规则集的版本号。
/// @param ruleSet The hash of the rule set to retrieve the version for.
// 规则集的哈希,用于检索版本。
functiongetRuleSetVersion(bytes32ruleSet)externalviewreturns(uint256){returnruleSetVersions[ruleSet];}functiongetUserInfo(addressuser)externalviewreturns(UserInfomemory){returnusers[user];}/// @notice Getter for the current paused status.
// 当前暂停状态getter。
/// @return paused_ Whether or not the contract is paused.
// @return paused_ 合约是否已暂停。
functionpaused()publicviewreturns(boolpaused_){paused_=systemConfig.paused();}}