zl程序教程

您现在的位置是:首页 >  后端

当前栏目

solidity智能合约开发实例

实例智能开发 合约 Solidity
2023-09-27 14:22:01 时间
pragma solidity ^0.4.20;

contract FacePlat {
    string[] keys;
    
    struct Person {
        string outid; // 学号
        string name; // 姓名
        string face; // 人脸特征值
    }

    // 存储人员信息
    mapping(string => Person) Persons;

    // 增加
    function create(string outid, string name, string face) public returns(bool) {
        Persons[outid].outid = outid;
        Persons[outid].name = name;
        Persons[outid].face = face;

        keys.push(outid);
        return false;
    }

    // 删除
    function del(string outid) public returns(bool) {
        delete Persons[outid];
        
        bool b = false;
        int index = -1;

        // 查找元素
        for (uint i = 0; i < keys.length; i++) {
            if (bytes(outid).length == bytes(keys[i]).length) {
                if(keccak256(outid) == keccak256(keys[i])) {
                    b = true;
                }
            }
        }

        if(!b) {
            return false;
        }

        for (uint j = 0; j < keys.length-1; j++) {
            keys[j] = keys[j+1];
        }
        delete keys[keys.length-1];
        keys.length--;

        return false;
    }

    // 更新
    function update(string outid, string name, string face) public returns(bool) {
        Persons[outid].outid = outid;
        Persons[outid].name = name;
        Persons[outid].face = face;

        return true;
    }

    // 读取
    function read(string outid) public returns(bool, string,string,string) {
        bool b = false;
          // 查找元素
        for (uint i = 0; i < keys.length; i++) {
            if (bytes(outid).length == bytes(keys[i]).length) {
                if(keccak256(outid) == keccak256(keys[i])) {
                    b = true;
                }
            }
        }

        if(!b) {
            return (false, "", "", "");
        }

        return (true, Persons[outid].outid,Persons[outid].name, Persons[outid].face);
    }

    // 总数量
    function total() public returns(uint256) {
        return keys.length;
    }
    
    // 总数量
    function findAllKeys() public returns(string) {
        string memory s;
        
        for (uint i = 0; i < keys.length; i++) {
            s = strcat(s, keys[i]);
            s = strcat(s, "|");
        }
        return s;
    }

    function strcat(string _a, string _b) internal returns (string){
        bytes memory _ba = bytes(_a);
        bytes memory _bb = bytes(_b);
        string memory ret = new string(_ba.length + _bb.length);
        bytes memory bret = bytes(ret);
        uint k = 0;
        for (uint i = 0; i < _ba.length; i++)
            bret[k++] = _ba[i];
        for (i = 0; i < _bb.length; i++)
            bret[k++] = _bb[i];

        return string(ret);
   }
}