| | 1 | | using NostrSure.Domain.Entities; |
| | 2 | | using NostrSure.Domain.Validation; |
| | 3 | | using System.Security.Cryptography; |
| | 4 | | using System.Text; |
| | 5 | | using System.Text.Encodings.Web; |
| | 6 | | using System.Text.Json; |
| | 7 | |
|
| | 8 | | namespace NostrSure.Domain.Services; |
| | 9 | |
|
| | 10 | | /// <summary> |
| | 11 | | /// Simple event ID calculator without caching for scenarios where caching is not desired |
| | 12 | | /// This implementation closely matches the original legacy implementation to ensure compatibility |
| | 13 | | /// </summary> |
| | 14 | | public sealed class SimpleEventIdCalculator : IEventIdCalculator |
| | 15 | | { |
| | 16 | | private readonly JsonSerializerOptions _jsonOptions; |
| 0 | 17 | | private static readonly SHA256 _sha256 = SHA256.Create(); |
| | 18 | |
|
| 28 | 19 | | public SimpleEventIdCalculator() |
| 28 | 20 | | { |
| 28 | 21 | | _jsonOptions = new JsonSerializerOptions |
| 28 | 22 | | { |
| 28 | 23 | | WriteIndented = false, |
| 28 | 24 | | Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping |
| 28 | 25 | | }; |
| 28 | 26 | | } |
| | 27 | |
|
| | 28 | | public string CalculateEventId(NostrEvent evt) |
| 11 | 29 | | { |
| | 30 | | // Match the exact legacy implementation format for compatibility |
| 11 | 31 | | var tagsArrays = evt.Tags.Select(tag => |
| 11 | 32 | | { |
| 11 | 33 | | var array = new List<string> { tag.Name }; |
| 11 | 34 | | array.AddRange(tag.Values); |
| 11 | 35 | | return array.ToArray(); |
| 22 | 36 | | }).ToArray(); |
| | 37 | |
|
| 11 | 38 | | var eventArray = new object[] |
| 11 | 39 | | { |
| 11 | 40 | | 0, |
| 11 | 41 | | evt.Pubkey.Value, |
| 11 | 42 | | evt.CreatedAt.ToUnixTimeSeconds(), |
| 11 | 43 | | (int)evt.Kind, |
| 11 | 44 | | tagsArrays, |
| 11 | 45 | | evt.Content |
| 11 | 46 | | }; |
| | 47 | |
|
| 11 | 48 | | var serialized = JsonSerializer.Serialize(eventArray, _jsonOptions); |
| | 49 | |
|
| 11 | 50 | | var utf8Bytes = Encoding.UTF8.GetBytes(serialized); |
| 11 | 51 | | var hash = NBitcoin.Crypto.Hashes.SHA256(utf8Bytes); |
| 11 | 52 | | return Convert.ToHexString(hash).ToLowerInvariant(); |
| 11 | 53 | | } |
| | 54 | | } |