0

I have this smart contract:

contract Truerec {
    struct Certificate {
        address issuerAddress;
        string  identityType;
        string  identityHash;
        string  dataHash;
        bool   revoked;
    }

    mapping(bytes32 => Certificate) certificates;

    function issue(string _key, 
        string _identityType, 
        string _identityHash, 
        string _dataHash) {
        certificates[sha3(_key)] = Certificate(
            msg.sender,
            _identityType,
            _identityHash,
            _dataHash,
            false
        );
    }
    ...
}

How can I check whether a mapping already exists and by using that make sure that if the key already exists, that the existing mapping will not be overwritten?

I need something like:

function issue(string _key, 
    string _identityType, 
    string _identityHash, 
    string _dataHash) {

    require(!key_exists(sha3(_key, certificates)]

    certificates[sha3(_key)] = Certificate(
        msg.sender,
        _identityType,
        _identityHash,
        _dataHash,
        false
    );
}
3

From: http://solidity.readthedocs.io/en/develop/types.html#mappings

Mappings can be seen as hashtables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros: a type’s default value.

A trick I have seen being used some times is to have a bool as the first field, as follows:

struct Certificate {
    bool exists;
    address issuerAddress;
    string  identityType;
    string  identityHash;
    string  dataHash;
    bool   revoked;
}

When a certificate is created, set the exists field to always be true. The default value of a bool is false. So the check to see whether a key is already mapped would be:

certificates[sha3(_key)].exists

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.