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() { 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));