From 5b5ae96297d2e5766ce475f9d506ce8be0b8ab3b Mon Sep 17 00:00:00 2001 From: Carti Date: Sun, 1 Nov 2026 10:22:05 +0100 Subject: [PATCH 1/2] HashBench: Add a benchmark --- NBitcoin.Bench/HashBench.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/NBitcoin.Bench/HashBench.cs b/NBitcoin.Bench/HashBench.cs index ef756c5c4..f05c7d0d1 100644 --- a/NBitcoin.Bench/HashBench.cs +++ b/NBitcoin.Bench/HashBench.cs @@ -1,6 +1,7 @@ using BenchmarkDotNet.Attributes; using NBitcoin.Crypto; using NBitcoin.DataEncoders; +using System; namespace NBitcoin.Bench; @@ -15,6 +16,12 @@ public void Setup() bytes = Encoders.Hex.DecodeData("d54994ece1d11b19785c7248868696250ab195605b469632b7bd68130e880c9a"); } + [Benchmark] + public void Hash160() + { + Hashes.Hash160(bytes.AsSpan()); + } + [Benchmark] public void SHA1() { From 7ffbf814f11ce200977ad9d8e35109592538929f Mon Sep 17 00:00:00 2001 From: Carti Date: Sun, 1 Nov 2026 10:11:46 +0100 Subject: [PATCH 2/2] Hashes: Optimize `Hash160` --- NBitcoin/Crypto/Hashes.cs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/NBitcoin/Crypto/Hashes.cs b/NBitcoin/Crypto/Hashes.cs index 328a9f8c8..ce4d0aae8 100644 --- a/NBitcoin/Crypto/Hashes.cs +++ b/NBitcoin/Crypto/Hashes.cs @@ -46,11 +46,11 @@ public static uint160 Hash160(byte[] data) { return Hash160(data, 0, data.Length); } + #if HAS_SPAN public static uint160 Hash160(ReadOnlySpan data) { - // TODO: optimize - return Hash160(data.ToArray()); + return new uint160(Hash160RawBytes(data)); } #endif @@ -63,8 +63,17 @@ public static uint160 Hash160(byte[] data, int offset, int count) { return new uint160(Hash160RawBytes(data, offset, count)); } + public static byte[] Hash160RawBytes(byte[] data) - => Hash160RawBytes(data, 0, data.Length); + => Hash160RawBytes(data, 0, data.Length); + +#if HAS_SPAN + public static byte[] Hash160RawBytes(ReadOnlySpan data) + { + return RIPEMD160(SHA256(data)); + } +#endif + public static byte[] Hash160RawBytes(byte[] data, int offset, int count) { return RIPEMD160(SHA256(data, offset, count));