¿Cómo generar un identificador único en Solidity?

Estoy haciendo un formulario de registro de estudiantes y necesito un identificador único para ellos. ¿Hay algún método en Solidity que dé un número único para cada estudiante que se registre?

Respuestas (3)

No hay un generador de identificación único integrado en Solidity.

2 ideas:

  • use un contador, uinty asegúrese de solo incrementarlo
  • use keccak256la función hash en datos únicos sobre el estudiante, como su nombre de usuario o dirección de correo electrónico
¿Puedo ampliar la parte uint? Lo intenté de esa manera, pero cada vez que se llama al contrato, el valor se establece en el valor predeterminado.
@Rajat Like function getID() returns(uint) { return ++counter; }Contract tiene una variable de estado denominada counter.

Consulte los métodos create()y en este contrato:createWithNonce()

https://github.com/link-blockchain/blobstore/blob/master/blobstore.sol

create()toma el blockhash del bloque anterior con la dirección del remitente y los hash (con keccak256) para crear un identificador único:

/**
     * @dev Creates a new blob. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. Consider createWithNonce() if not calling from another contract.
     * @param flags Packed blob settings.
     * @param contents Contents of the blob to be stored.
     * @return blobId Id of the blob.
     */
    function create(bytes4 flags, bytes contents) external returns (bytes20 blobId) {
        // Generate the blobId.
        blobId = bytes20(keccak256(msg.sender, block.blockhash(block.number - 1)));
        // Make sure this blobId has not been used before (could be in the same block).
        while (blobInfo[blobId].blockNumber != 0) {
            blobId = bytes20(keccak256(blobId));
        }
        // Store blob info in state.
        blobInfo[blobId] = BlobInfo({
            flags: flags,
            revisionCount: 1,
            blockNumber: uint32(block.number),
            owner: (flags & ANONYMOUS != 0) ? 0 : msg.sender,
        });
        // Store the first revision in a log in the current block.
        Store(blobId, 0, contents);
}

createWithNonce:

/**
     * @dev Creates a new blob using provided nonce. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. This method is cheaper than create(), especially if multiple blobs from the same account end up in the same block. However, it is not suitable for calling from other contracts because it will throw if a unique nonce is not provided.
     * @param flagsNonce First 4 bytes: Packed blob settings. The parameter as a whole must never have been passed to this function from the same account, or it will throw.
     * @param contents Contents of the blob to be stored.
     * @return blobId Id of the blob.
     */
    function createWithNonce(bytes32 flagsNonce, bytes contents) external returns (bytes20 blobId) {
        // Generate the blobId.
        blobId = bytes20(keccak256(msg.sender, flagsNonce));
        // Make sure this blobId has not been used before.
        if (blobInfo[blobId].blockNumber != 0) {
            throw;
        }
        // Store blob info in state.
        blobInfo[blobId] = BlobInfo({
            flags: bytes4(flagsNonce),
            revisionCount: 1,
            blockNumber: uint32(block.number),
            owner: (bytes4(flagsNonce) & ANONYMOUS != 0) ? 0 : msg.sender,
        });
        // Store the first revision in a log in the current block.
        Store(blobId, 0, contents);
}
Bienvenido al sitio! Votaré a favor, pero un fragmento de código o dos también podrían mejorar esta respuesta.
Creé un formulario de registro de estudiante y tomé la entrada como nombre, apellido y estudianteRegId.
¿No es "while (blobInfo[blobId].blockNumber != 0)" propenso al bucle de quema de GAS? En caso de que el blobId ya se haya utilizado (donde 2+ txs ocurrieron de cerca), esto se repetirá hasta que se extraiga un nuevo bloque. @jonathan-marrón

Puedes jugar en este sitio https://ethfiddle.com/mn8VfzWoN9

contract Student {
  uint public studentId;

  function getStudentId() public returns (uint) {
    return studentId++;
  }
}

Cada vez que invoque getStudentIdla función, studentIdaumentará 1.

Tal vez tenga que reemplazarlo publiccon internalalguna declaración de validación.

Hazlo en oraciones, de lo contrario, la calidad de la publicación se verá mal y la gente comenzará a votar negativamente.
Lo siento, corregiré esta respuesta.