Skip to content

Commit

Permalink
fifo cache
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashuaidehao committed Mar 5, 2024
1 parent f296bba commit 9b7f1f2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/Neo/Cryptography/Crypto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using Neo.IO.Caching;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
Expand Down Expand Up @@ -100,7 +101,8 @@ public static bool VerifySignature(ReadOnlySpan<byte> message, ReadOnlySpan<byte
}
}

private static readonly Dictionary<ECC.ECPoint, ECDsa> CacheECDsa = new();
//private static readonly Dictionary<ECC.ECPoint, ECDsa> CacheECDsa = new();
private static readonly ECDsaCache CacheECDsa = new ECDsaCache();

/// <summary>
/// Create and cache ECDsa objects
Expand All @@ -110,9 +112,9 @@ public static bool VerifySignature(ReadOnlySpan<byte> message, ReadOnlySpan<byte
/// <exception cref="NotSupportedException"></exception>
public static ECDsa CreateECDsa(ECC.ECPoint pubkey)
{
if (CacheECDsa.TryGetValue(pubkey, out var cache))
if (CacheECDsa.TryGet(pubkey, out var cache))
{
return cache;
return cache.value;
}
ECCurve curve =
pubkey.Curve == ECC.ECCurve.Secp256r1 ? ECCurve.NamedCurves.nistP256 :
Expand All @@ -128,7 +130,7 @@ public static ECDsa CreateECDsa(ECC.ECPoint pubkey)
Y = buffer[33..]
}
});
CacheECDsa[pubkey] = ecdsa;
CacheECDsa.Add(new ECDsaCacheItem(pubkey, ecdsa));
return ecdsa;
}

Expand Down
32 changes: 32 additions & 0 deletions src/Neo/IO/Caching/ECDsaCache.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (C) 2015-2024 The Neo Project.
//
// ECDsaCache.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using Neo.Cryptography.ECC;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Neo.IO.Caching
{
record ECDsaCacheItem(Cryptography.ECC.ECPoint key, ECDsa value);
internal class ECDsaCache : FIFOCache<Cryptography.ECC.ECPoint, ECDsaCacheItem>
{
public ECDsaCache(int max_capacity = 20000) : base(max_capacity, EqualityComparer<Cryptography.ECC.ECPoint>.Default)
{
}

protected override Cryptography.ECC.ECPoint GetKeyForItem(ECDsaCacheItem item)
{
return item.key;
}
}
}

0 comments on commit 9b7f1f2

Please sign in to comment.