You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Hyperledger Composer开发登录验证智能合约的技术问询

完善Hyperledger Composer登录验证交易函数

嘿,你已经把登录验证的基础模型(参与者和交易)定义得很清晰了!我来帮你把交易函数补全,顺便提几个生产环境必须注意的关键点,避免踩坑。

完整交易函数实现(匹配你的现有模型)

/**
 * 登录验证交易函数
 * @param {org.example.SampleLogin} tx - 传入的登录交易实例
 * @returns {boolean} 验证结果:匹配返回true,不匹配/异常返回false
 */
Transaction function sampleLogin(tx) {
    // 先做边界检查:避免传入无效的参与者引用导致合约报错
    if (!tx.participant) {
        console.error("未指定需要验证的参与者");
        return false;
    }

    // 从参与者实例中取出存储的用户名和密码
    const storedUsername = tx.participant.username;
    const storedPassword = tx.participant.password;

    // 获取用户输入的登录凭证
    const inputUsername = tx.inputUsername;
    const inputPassword = tx.inputPassword;

    // 核心验证逻辑(明文对比仅作演示!生产环境绝对不能这么干)
    if (storedUsername === inputUsername && storedPassword === inputPassword) {
        console.log(`参与者 ${tx.participant.participantId} 登录验证通过`);
        return true;
    } else {
        console.log(`参与者 ${tx.participant.participantId} 登录验证失败`);
        return false;
    }
}

必须注意的生产环境优化点

  • 绝对不能明文存储密码!:上面的明文对比只是为了演示核心逻辑,真实项目里,你必须在用户注册时用哈希算法(比如bcrypt)对密码加密后再存储,验证时对用户输入的密码做相同哈希处理后再对比,绝对不能直接存明文密码!
  • 边界检查很重要:我加了!tx.participant的判断,避免因为传入无效的参与者引用导致合约抛出异常,这样你的Web应用能收到明确的false返回值,而不是一堆错误栈。
  • 返回值直接可用:交易函数直接返回布尔值,你的Web应用调用这个交易后,就能拿到结果直接判断登录是否成功。

可选优化:通过用户名自动查询参与者

如果你的Web应用不想提前传入参与者引用,而是想直接通过用户名查询验证,可以修改交易模型和函数:

修改后的交易模型

transaction SampleLogin {
  o String inputUsername
  o String inputPassword
}

对应的交易函数

Transaction function sampleLogin(tx) {
    // 获取参与者注册表
    const participantRegistry = await getParticipantRegistry('org.example.SampleParticipant');
    // 通过用户名查询对应的参与者
    const matchedParticipants = await participantRegistry.query(
        'SELECT org.example.SampleParticipant WHERE username == $inputUsername',
        { inputUsername: tx.inputUsername }
    );

    // 没找到对应用户名的参与者
    if (matchedParticipants.length === 0) {
        console.error(`未找到用户名 ${tx.inputUsername} 的参与者`);
        return false;
    }

    const targetParticipant = matchedParticipants[0];
    // 生产环境记得用哈希对比!
    return targetParticipant.password === tx.inputPassword;
}

内容的提问来源于stack exchange,提问作者peterDalis. st

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:59:44