# # Ethereum KeyFile # (c) Copyright 2018-2024 # Status Research & Development GmbH # # Licensed under either of # Apache License, version 2.0, (LICENSE-APACHEv2) # MIT license (LICENSE-MIT) ## This module implements interface to cross-platform UUID ## generator. ## ## - ``Windows`` - using rpcrt4.dll's `UuidCreate()`. ## - ``Linux`` and ``Android`` - using `/proc/sys/kernel/random/uuid`. ## - ``MacOS`` and ``iOS`` - using `uuid_generate_random()`. ## - ``FreeBSD``, ``OpenBSD``, ``NetBSD``, ## ``DragonflyBSD`` - using `uuid_create()`. {.push raises: [].} import stew/[byteutils, endians2], results from nimcrypto/utils import stripSpaces export results type UUID* = object ## Represents UUID object data*: array[16, byte] UuidResult*[T] = Result[T, cstring] proc uuidFromString*(s: string): UuidResult[UUID] = ## Convert string representation of UUID into UUID object. if len(s) != 36: return err("uuid: length must be 36 bytes") for i in 0.. 0: result += res elif res == 0: break else: if osLastError().int32 != EINTR: result = -1 break discard posix.close(fd) proc uuidGenerate*(): UuidResult[UUID] = var buffer = newString(37) if uuidRead(buffer, 36) == 36: buffer.setLen(36) uuidFromString(buffer) else: var output: UUID if randomBytes(output.data) == sizeof(output.data): ok(output) else: err("uuid: cannot get random bytes") else: import nimcrypto/sysrand proc uuidGenerate*(): UuidResult[UUID] = var output: UUID if randomBytes(output.data) == sizeof(output.data): ok(output) else: err("uuid: cannot get random bytes") elif defined(windows): proc UuidCreate(p: pointer): int32 {.stdcall, dynlib: "rpcrt4", importc: "UuidCreate".} proc uuidGenerate*(): UuidResult[UUID] = var output: UUID if UuidCreate(cast[pointer](addr output)) == 0: ok(output) else: err("uuid: UuidCreate failed") elif not defined(nimdoc): import nimcrypto/sysrand proc uuidGenerate*(): UuidResult[UUID] = var output: UUID if randomBytes(output.data) == sizeof(output.data): ok(output) else: err("uuid: cannot get random bytes")