diff --git a/libp2p/crypto/chacha20poly1305.nim b/libp2p/crypto/chacha20poly1305.nim index d208d7d..8aea54a 100644 --- a/libp2p/crypto/chacha20poly1305.nim +++ b/libp2p/crypto/chacha20poly1305.nim @@ -44,17 +44,18 @@ proc intoChaChaPolyTag*(s: seq[byte]): ChaChaPolyTag = # this is reconciled at runtime # we do this in the global scope / module init -# try for the best first -var - chachapoly_native_impl: Poly1305Run = poly1305CtmulqGet() - chacha_native_impl: Chacha20Run = chacha20Sse2Get() +template fetchImpl: untyped = + # try for the best first + var + chachapoly_native_impl {.inject.}: Poly1305Run = poly1305CtmulqGet() + chacha_native_impl {.inject.}: Chacha20Run = chacha20Sse2Get() -# fall back if not available -if chachapoly_native_impl == nil: - chachapoly_native_impl = poly1305CtmulRun + # fall back if not available + if chachapoly_native_impl == nil: + chachapoly_native_impl = poly1305CtmulRun -if chacha_native_impl == nil: - chacha_native_impl = chacha20CtRun + if chacha_native_impl == nil: + chacha_native_impl = chacha20CtRun proc encrypt*(_: type[ChaChaPoly], key: var ChaChaPolyKey, @@ -62,6 +63,8 @@ proc encrypt*(_: type[ChaChaPoly], tag: var ChaChaPolyTag, data: var openarray[byte], aad: var openarray[byte]) = + fetchImpl() + chachapoly_native_impl( addr key[0], addr nonce[0], @@ -79,6 +82,8 @@ proc decrypt*(_: type[ChaChaPoly], tag: var ChaChaPolyTag, data: var openarray[byte], aad: var openarray[byte]) = + fetchImpl() + chachapoly_native_impl( addr key[0], addr nonce[0], diff --git a/libp2p/crypto/curve25519.nim b/libp2p/crypto/curve25519.nim index 760f554..4d6f4ab 100644 --- a/libp2p/crypto/curve25519.nim +++ b/libp2p/crypto/curve25519.nim @@ -46,8 +46,6 @@ const ] Basepoint*: Curve25519Key = [9.byte, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -let defaultBrEc = brEcGetDefault() - proc byteswap*(buf: var Curve25519Key) {.inline.} = for i in 0..<16: let @@ -56,6 +54,8 @@ proc byteswap*(buf: var Curve25519Key) {.inline.} = buf[31 - i] = x proc mul*(_: type[Curve25519], dst: var Curve25519Key, scalar: Curve25519Key, point: Curve25519Key) = + let defaultBrEc = brEcGetDefault() + # The source point is provided in array G (of size Glen bytes); # the multiplication result is written over it. dst = scalar @@ -74,6 +74,8 @@ proc mul*(_: type[Curve25519], dst: var Curve25519Key, scalar: Curve25519Key, po assert res == 1 proc mulgen*(_: type[Curve25519], dst: var Curve25519Key, scalar: Curve25519Key) = + let defaultBrEc = brEcGetDefault() + block iterate: while true: block derive: