| | 1 | | namespace NLightning.Bolt11.Services; |
| | 2 | |
|
| | 3 | | using Interfaces; |
| | 4 | | using Models; |
| | 5 | |
|
| | 6 | | public class InvoiceValidationService : IInvoiceValidationService |
| | 7 | | { |
| | 8 | | public ValidationResult ValidateInvoice(Invoice invoice) |
| | 9 | | { |
| 84 | 10 | | var results = new List<ValidationResult> |
| 84 | 11 | | { |
| 84 | 12 | | ValidateRequiredFields(invoice), |
| 84 | 13 | | ValidateFieldCombinations(invoice), |
| 84 | 14 | | }; |
| | 15 | |
|
| 252 | 16 | | var errors = results.SelectMany(r => r.Errors).ToList(); |
| 84 | 17 | | return new ValidationResult(errors.Count == 0, errors); |
| | 18 | | } |
| | 19 | |
|
| | 20 | | public ValidationResult ValidateRequiredFields(Invoice invoice) |
| | 21 | | { |
| 108 | 22 | | var errors = new List<string>(); |
| | 23 | |
|
| | 24 | | // Payment hash is required (p field) |
| 108 | 25 | | if (invoice.PaymentHash is null) |
| 12 | 26 | | errors.Add($"{nameof(invoice.PaymentHash)} is required"); |
| | 27 | |
|
| | 28 | | // Payment secret is required (s field) |
| 108 | 29 | | if (invoice.PaymentSecret is null) |
| 8 | 30 | | errors.Add($"{nameof(invoice.PaymentSecret)} is required"); |
| | 31 | |
|
| | 32 | | // Either description or description hash is required (d or h field) |
| 108 | 33 | | var hasDescription = invoice.Description is not null; |
| 108 | 34 | | var hasDescriptionHash = invoice.DescriptionHash is not null; |
| 108 | 35 | | if (!hasDescription && !hasDescriptionHash) |
| 8 | 36 | | errors.Add($"Either {nameof(invoice.Description)} or {nameof(invoice.DescriptionHash)} is required"); |
| | 37 | |
|
| 108 | 38 | | return new ValidationResult(errors.Count == 0, errors); |
| | 39 | | } |
| | 40 | |
|
| | 41 | | public ValidationResult ValidateFieldCombinations(Invoice invoice) |
| | 42 | | { |
| 100 | 43 | | var errors = new List<string>(); |
| | 44 | |
|
| | 45 | | // Description and description hash are mutually exclusive |
| 100 | 46 | | var hasDescription = invoice.Description is not null; |
| 100 | 47 | | var hasDescriptionHash = invoice.DescriptionHash is not null; |
| 100 | 48 | | if (hasDescription && hasDescriptionHash) |
| 12 | 49 | | errors.Add($"{nameof(invoice.Description)} and {nameof(invoice.DescriptionHash)} cannot both be present"); |
| | 50 | |
|
| 100 | 51 | | return new ValidationResult(errors.Count == 0, errors); |
| | 52 | | } |
| | 53 | | } |