From d9af7a8f8a76bdf78d0056032d0e1d92d1e7f11e Mon Sep 17 00:00:00 2001 From: Ben Adams Date: Sat, 1 Nov 2025 16:17:11 +0000 Subject: [PATCH] Optimize Ripemd --- .../Nethermind.Core.Test/RipemdTests.cs | 2 +- src/Nethermind/Nethermind.Crypto/Ripemd.cs | 32 +++++++++++-------- .../Ripemd160Precompile.cs | 2 +- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/src/Nethermind/Nethermind.Core.Test/RipemdTests.cs b/src/Nethermind/Nethermind.Core.Test/RipemdTests.cs index 88403a11e132..b7c4e8115218 100644 --- a/src/Nethermind/Nethermind.Core.Test/RipemdTests.cs +++ b/src/Nethermind/Nethermind.Core.Test/RipemdTests.cs @@ -9,7 +9,7 @@ namespace Nethermind.Core.Test [TestFixture] public class RipemdTests { - public const string RipemdOfEmptyString = "9c1185a5c5e9fc54612808977ee8f548b2258d31"; + public const string RipemdOfEmptyString = "0000000000000000000000009c1185a5c5e9fc54612808977ee8f548b2258d31"; [Test] public void Empty_byte_array() diff --git a/src/Nethermind/Nethermind.Crypto/Ripemd.cs b/src/Nethermind/Nethermind.Crypto/Ripemd.cs index fc02c2e524ef..8fc68db757e3 100644 --- a/src/Nethermind/Nethermind.Crypto/Ripemd.cs +++ b/src/Nethermind/Nethermind.Crypto/Ripemd.cs @@ -1,25 +1,29 @@ // SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only +using System; using Nethermind.Core.Extensions; using Org.BouncyCastle.Crypto.Digests; -namespace Nethermind.Crypto +namespace Nethermind.Crypto; + +public static class Ripemd { - public static class Ripemd + const int HashOutputLength = 32; + + public static byte[] Compute(ReadOnlySpan input) { - public static byte[] Compute(byte[] input) - { - var digest = new RipeMD160Digest(); - digest.BlockUpdate(input, 0, input.Length); - var result = new byte[digest.GetDigestSize()]; - digest.DoFinal(result, 0); - return result; - } + RipeMD160Digest digest = new(); + digest.BlockUpdate(input); + byte[] result = new byte[HashOutputLength]; + int length = digest.GetDigestSize(); + Span span = result.AsSpan(HashOutputLength - length, length); + digest.DoFinal(span); + return result; + } - public static string ComputeString(byte[] input) - { - return Compute(input).ToHexString(false); - } + public static string ComputeString(ReadOnlySpan input) + { + return Compute(input).ToHexString(false); } } diff --git a/src/Nethermind/Nethermind.Evm.Precompiles/Ripemd160Precompile.cs b/src/Nethermind/Nethermind.Evm.Precompiles/Ripemd160Precompile.cs index a4977a63c8c4..092a6689de57 100644 --- a/src/Nethermind/Nethermind.Evm.Precompiles/Ripemd160Precompile.cs +++ b/src/Nethermind/Nethermind.Evm.Precompiles/Ripemd160Precompile.cs @@ -38,6 +38,6 @@ public long DataGasCost(ReadOnlyMemory inputData, IReleaseSpec releaseSpec { Metrics.Ripemd160Precompile++; - return (Ripemd.Compute(inputData.ToArray()).PadLeft(32), true); + return (Ripemd.Compute(inputData.Span), true); } }