From c219100e649d87ca809be39e701c8bfaeaa3a8f3 Mon Sep 17 00:00:00 2001 From: Giovanni Petrantoni Date: Tue, 19 May 2020 17:22:49 +0900 Subject: [PATCH] Use results and no exceptions in chacha and curve25519 (#182) --- libp2p/crypto/chacha20poly1305.nim | 2 ++ libp2p/crypto/curve25519.nim | 21 +++++++++++++++------ libp2p/protocols/secure/noise.nim | 2 +- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/libp2p/crypto/chacha20poly1305.nim b/libp2p/crypto/chacha20poly1305.nim index df2d44b..fb43f73 100644 --- a/libp2p/crypto/chacha20poly1305.nim +++ b/libp2p/crypto/chacha20poly1305.nim @@ -15,6 +15,8 @@ # RFC @ https://tools.ietf.org/html/rfc7539 +{.push raises: [Defect].} + import bearssl # have to do this due to a nim bug and raises[] on callbacks diff --git a/libp2p/crypto/curve25519.nim b/libp2p/crypto/curve25519.nim index ba3f63c..5c0b0ed 100644 --- a/libp2p/crypto/curve25519.nim +++ b/libp2p/crypto/curve25519.nim @@ -15,7 +15,11 @@ # RFC @ https://tools.ietf.org/html/rfc7748 +{.push raises: [Defect].} + import bearssl +import stew/results +export results const Curve25519KeySize* = 32 @@ -24,7 +28,8 @@ type Curve25519* = object Curve25519Key* = array[Curve25519KeySize, byte] pcuchar = ptr cuchar - Curver25519RngError* = object of CatchableError + Curve25519Error* = enum + Curver25519RngError proc intoCurve25519Key*(s: openarray[byte]): Curve25519Key = assert s.len == Curve25519KeySize @@ -100,12 +105,16 @@ proc mulgen*(_: type[Curve25519], dst: var Curve25519Key, point: Curve25519Key) proc public*(private: Curve25519Key): Curve25519Key = Curve25519.mulgen(result, private) -proc random*(_: type[Curve25519Key]): Curve25519Key = +proc random*(_: type[Curve25519Key]): Result[Curve25519Key, Curve25519Error] = var rng: BrHmacDrbgContext + var res: Curve25519Key let seeder = brPrngSeederSystem(nil) brHmacDrbgInit(addr rng, addr sha256Vtable, nil, 0) if seeder(addr rng.vtable) == 0: - raise newException(ValueError, "Could not seed RNG") - let defaultBrEc = brEcGetDefault() - if brEcKeygen(addr rng.vtable, defaultBrEc, nil, addr result[0], EC_curve25519) != Curve25519KeySize: - raise newException(Curver25519RngError, "Could not generate random data") + err(Curver25519RngError) + else: + let defaultBrEc = brEcGetDefault() + if brEcKeygen(addr rng.vtable, defaultBrEc, nil, addr res[0], EC_curve25519) != Curve25519KeySize: + err(Curver25519RngError) + else: + ok(res) diff --git a/libp2p/protocols/secure/noise.nim b/libp2p/protocols/secure/noise.nim index cdbad72..cfb46e6 100644 --- a/libp2p/protocols/secure/noise.nim +++ b/libp2p/protocols/secure/noise.nim @@ -88,7 +88,7 @@ type # Utility proc genKeyPair(): KeyPair = - result.privateKey = Curve25519Key.random() + result.privateKey = Curve25519Key.random().tryGet() result.publicKey = result.privateKey.public() proc hashProtocol(name: string): MDigest[256] =