| | 1 | | using NostrSure.Domain.Interfaces; |
| | 2 | | using NostrSure.Domain.Services; |
| | 3 | | using NostrSure.Domain.Validation; |
| | 4 | | using NostrSure.Domain.ValueObjects; |
| | 5 | | using System.Text; |
| | 6 | | using System.Text.Json; |
| | 7 | |
|
| | 8 | | namespace NostrSure.Domain.Entities; |
| | 9 | |
|
| | 10 | | /// <summary> |
| | 11 | | /// Legacy NostrEventValidator maintained for backward compatibility. |
| | 12 | | /// Consider migrating to ModularNostrEventValidator for better performance and testability. |
| | 13 | | /// </summary> |
| | 14 | | public sealed class NostrEventValidator : INostrEventValidator |
| | 15 | | { |
| | 16 | | // Internal services for improved performance while maintaining compatibility |
| | 17 | | private readonly IHexConverter _hexConverter; |
| | 18 | | private readonly ICryptographicService _cryptographicService; |
| | 19 | | private readonly IEventIdCalculator _eventIdCalculator; |
| | 20 | |
|
| 24 | 21 | | public NostrEventValidator() |
| 24 | 22 | | { |
| | 23 | | // Use optimized services internally for better performance |
| 24 | 24 | | _hexConverter = new OptimizedHexConverter(); |
| 24 | 25 | | _cryptographicService = new OptimizedCryptographicService(); |
| 24 | 26 | | _eventIdCalculator = new SimpleEventIdCalculator(); |
| 24 | 27 | | } |
| | 28 | |
|
| | 29 | | #region New Async Methods |
| | 30 | |
|
| | 31 | | public Task<ValidationResult> ValidateAsync(NostrEvent evt, CancellationToken cancellationToken = default) |
| 1 | 32 | | { |
| 1 | 33 | | var result = Validate(evt); |
| 1 | 34 | | return Task.FromResult(result); |
| 1 | 35 | | } |
| | 36 | |
|
| | 37 | | public ValidationResult Validate(NostrEvent evt) |
| 3 | 38 | | { |
| | 39 | | // Validate all components and return the first failure or success |
| 3 | 40 | | if (!ValidateKind(evt, out var kindError)) |
| 0 | 41 | | return ValidationResult.Failure(kindError, "INVALID_KIND"); |
| | 42 | |
|
| 3 | 43 | | if (!ValidateTags(evt, out var tagError)) |
| 1 | 44 | | return ValidationResult.Failure(tagError, "INVALID_TAGS"); |
| | 45 | |
|
| 2 | 46 | | if (!ValidateEventId(evt, out var eventIdError)) |
| 2 | 47 | | return ValidationResult.Failure(eventIdError, "INVALID_EVENT_ID"); |
| | 48 | |
|
| 0 | 49 | | if (!ValidateSignature(evt, out var signatureError)) |
| 0 | 50 | | return ValidationResult.Failure(signatureError, "INVALID_SIGNATURE"); |
| | 51 | |
|
| 0 | 52 | | return ValidationResult.Success(); |
| 3 | 53 | | } |
| | 54 | |
|
| | 55 | | #endregion |
| | 56 | |
|
| | 57 | | #region Legacy Methods |
| | 58 | |
|
| | 59 | | public bool ValidateSignature(NostrEvent evt, out string error) |
| 9 | 60 | | { |
| | 61 | | try |
| 9 | 62 | | { |
| 9 | 63 | | if (string.IsNullOrWhiteSpace(evt.Sig)) |
| 1 | 64 | | { |
| 1 | 65 | | error = "Signature is empty."; |
| 1 | 66 | | return false; |
| | 67 | | } |
| 8 | 68 | | if (string.IsNullOrWhiteSpace(evt.Pubkey?.Value)) |
| 1 | 69 | | { |
| 1 | 70 | | error = "Pubkey is empty."; |
| 1 | 71 | | return false; |
| | 72 | | } |
| 7 | 73 | | if (string.IsNullOrWhiteSpace(evt.Id)) |
| 1 | 74 | | { |
| 1 | 75 | | error = "Event ID is empty."; |
| 1 | 76 | | return false; |
| | 77 | | } |
| | 78 | |
|
| | 79 | | // Use optimized hex converter with stack allocation |
| 6 | 80 | | Span<byte> eventIdBytes = stackalloc byte[32]; |
| 6 | 81 | | Span<byte> pubkeyBytes = stackalloc byte[32]; |
| 6 | 82 | | Span<byte> sigBytes = stackalloc byte[64]; |
| | 83 | |
|
| 6 | 84 | | if (!_hexConverter.TryParseHex(evt.Id, eventIdBytes, out var eventIdLength) || eventIdLength != 32) |
| 1 | 85 | | { |
| 1 | 86 | | error = "Invalid event ID length (must be 32 bytes)."; |
| 1 | 87 | | return false; |
| | 88 | | } |
| 5 | 89 | | if (!_hexConverter.TryParseHex(evt.Pubkey.Value, pubkeyBytes, out var pubkeyLength) || pubkeyLength != 32) |
| 1 | 90 | | { |
| 1 | 91 | | error = "Invalid pubkey length for x-only pubkey (must be 32 bytes)."; |
| 1 | 92 | | return false; |
| | 93 | | } |
| 4 | 94 | | if (!_hexConverter.TryParseHex(evt.Sig, sigBytes, out var sigLength) || sigLength != 64) |
| 1 | 95 | | { |
| 1 | 96 | | error = "Invalid signature length for Schnorr signature (must be 64 bytes)."; |
| 1 | 97 | | return false; |
| | 98 | | } |
| | 99 | |
|
| | 100 | | // Use optimized cryptographic service |
| 3 | 101 | | bool valid = _cryptographicService.VerifySchnorrSignature(sigBytes, eventIdBytes, pubkeyBytes); |
| 3 | 102 | | if (!valid) |
| 0 | 103 | | { |
| 0 | 104 | | error = "Signature verification failed."; |
| 0 | 105 | | return false; |
| | 106 | | } |
| | 107 | |
|
| 3 | 108 | | error = string.Empty; |
| 3 | 109 | | return true; |
| | 110 | | } |
| 0 | 111 | | catch (Exception ex) |
| 0 | 112 | | { |
| 0 | 113 | | error = $"Exception during signature validation: {ex.Message}"; |
| 0 | 114 | | return false; |
| | 115 | | } |
| 9 | 116 | | } |
| | 117 | |
|
| | 118 | | public bool ValidateEventId(NostrEvent evt, out string error) |
| 7 | 119 | | { |
| | 120 | | try |
| 7 | 121 | | { |
| 7 | 122 | | var calculatedId = _eventIdCalculator.CalculateEventId(evt); |
| 7 | 123 | | if (evt.Id != calculatedId) |
| 3 | 124 | | { |
| 3 | 125 | | error = $"Event ID mismatch. Expected: {calculatedId}, Got: {evt.Id}"; |
| 3 | 126 | | return false; |
| | 127 | | } |
| 4 | 128 | | error = string.Empty; |
| 4 | 129 | | return true; |
| | 130 | | } |
| 0 | 131 | | catch (Exception ex) |
| 0 | 132 | | { |
| 0 | 133 | | error = $"Exception during event ID validation: {ex.Message}"; |
| 0 | 134 | | return false; |
| | 135 | | } |
| 7 | 136 | | } |
| | 137 | |
|
| | 138 | | public bool ValidateKind(NostrEvent evt, out string error) |
| 5 | 139 | | { |
| 5 | 140 | | if (!Enum.IsDefined(typeof(EventKind), evt.Kind)) |
| 1 | 141 | | { |
| 1 | 142 | | error = $"Unknown event kind: {evt.Kind}"; |
| 1 | 143 | | return false; |
| | 144 | | } |
| 4 | 145 | | error = string.Empty; |
| 4 | 146 | | return true; |
| 5 | 147 | | } |
| | 148 | |
|
| | 149 | | public bool ValidateTags(NostrEvent evt, out string error) |
| 11 | 150 | | { |
| 11 | 151 | | if (evt.Tags == null) |
| 1 | 152 | | { |
| 1 | 153 | | error = "Tags are null."; |
| 1 | 154 | | return false; |
| | 155 | | } |
| | 156 | |
|
| 44 | 157 | | foreach (var tag in evt.Tags) |
| 9 | 158 | | { |
| 9 | 159 | | if (tag == null) |
| 1 | 160 | | { |
| 1 | 161 | | error = "Tag is null."; |
| 1 | 162 | | return false; |
| | 163 | | } |
| | 164 | |
|
| 8 | 165 | | if (string.IsNullOrWhiteSpace(tag.Name)) |
| 0 | 166 | | { |
| 0 | 167 | | error = "Tag name is empty or null."; |
| 0 | 168 | | return false; |
| | 169 | | } |
| | 170 | |
|
| 8 | 171 | | if (!tag.IsValid()) |
| 2 | 172 | | { |
| 2 | 173 | | error = $"Invalid tag: {tag.Name}"; |
| 2 | 174 | | return false; |
| | 175 | | } |
| | 176 | |
|
| 6 | 177 | | if (tag.Values.Any(string.IsNullOrWhiteSpace)) |
| 1 | 178 | | { |
| 1 | 179 | | error = "Tag contains empty value."; |
| 1 | 180 | | return false; |
| | 181 | | } |
| 5 | 182 | | } |
| | 183 | |
|
| 6 | 184 | | error = string.Empty; |
| 6 | 185 | | return true; |
| 11 | 186 | | } |
| | 187 | |
|
| | 188 | | #endregion |
| | 189 | |
|
| | 190 | | #region Legacy Helper Methods (Deprecated) |
| | 191 | |
|
| | 192 | | [Obsolete("This method uses legacy hex parsing. Consider using ModularNostrEventValidator for better performance.")] |
| | 193 | | private string CalculateEventId(NostrEvent evt) |
| 0 | 194 | | { |
| | 195 | | // Keep legacy implementation for backward compatibility |
| 0 | 196 | | var options = new JsonSerializerOptions |
| 0 | 197 | | { |
| 0 | 198 | | WriteIndented = false, |
| 0 | 199 | | Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping |
| 0 | 200 | | }; |
| | 201 | |
|
| 0 | 202 | | var tagsArrays = evt.Tags.Select(tag => |
| 0 | 203 | | { |
| 0 | 204 | | var array = new List<string> { tag.Name }; |
| 0 | 205 | | array.AddRange(tag.Values); |
| 0 | 206 | | return array.ToArray(); |
| 0 | 207 | | }).ToArray(); |
| | 208 | |
|
| 0 | 209 | | var eventArray = new object[] |
| 0 | 210 | | { |
| 0 | 211 | | 0, |
| 0 | 212 | | evt.Pubkey.Value, |
| 0 | 213 | | evt.CreatedAt.ToUnixTimeSeconds(), |
| 0 | 214 | | (int)evt.Kind, |
| 0 | 215 | | tagsArrays, |
| 0 | 216 | | evt.Content |
| 0 | 217 | | }; |
| | 218 | |
|
| 0 | 219 | | var serialized = JsonSerializer.Serialize(eventArray, options); |
| 0 | 220 | | var utf8Bytes = Encoding.UTF8.GetBytes(serialized); |
| 0 | 221 | | var hash = NBitcoin.Crypto.Hashes.SHA256(utf8Bytes); |
| 0 | 222 | | return Convert.ToHexString(hash).ToLowerInvariant(); |
| 0 | 223 | | } |
| | 224 | |
|
| | 225 | | [Obsolete("This method uses legacy hex parsing. Consider using OptimizedHexConverter for better performance.")] |
| | 226 | | private static byte[] ParseHex(string hex) |
| 0 | 227 | | { |
| 0 | 228 | | if (hex.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) |
| 0 | 229 | | hex = hex.Substring(2); |
| 0 | 230 | | var bytes = new byte[hex.Length / 2]; |
| 0 | 231 | | for (int i = 0; i < bytes.Length; i++) |
| 0 | 232 | | bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); |
| 0 | 233 | | return bytes; |
| 0 | 234 | | } |
| | 235 | |
|
| | 236 | | [Obsolete("This method is unused. Consider using OptimizedHexConverter.TryParseHex instead.")] |
| | 237 | | private static bool TryParseHex(string hex, out byte[] bytes) |
| 0 | 238 | | { |
| | 239 | | try |
| 0 | 240 | | { |
| 0 | 241 | | bytes = ParseHex(hex); |
| 0 | 242 | | return true; |
| | 243 | | } |
| 0 | 244 | | catch |
| 0 | 245 | | { |
| 0 | 246 | | bytes = Array.Empty<byte>(); |
| 0 | 247 | | return false; |
| | 248 | | } |
| 0 | 249 | | } |
| | 250 | |
|
| | 251 | | #endregion |
| | 252 | | } |