| | 1 | | using System.Diagnostics.CodeAnalysis; |
| | 2 | | using System.Text; |
| | 3 | | using System.Text.RegularExpressions; |
| | 4 | | using NBitcoin; |
| | 5 | |
|
| | 6 | | namespace NLightning.Bolt11.Models; |
| | 7 | |
|
| | 8 | | using Domain.Constants; |
| | 9 | | using Domain.Crypto.Constants; |
| | 10 | | using Domain.Enums; |
| | 11 | | using Domain.Models; |
| | 12 | | using Domain.Money; |
| | 13 | | using Domain.Node; |
| | 14 | | using Domain.Protocol.Constants; |
| | 15 | | using Domain.Protocol.Interfaces; |
| | 16 | | using Domain.Protocol.ValueObjects; |
| | 17 | | using Domain.Utils; |
| | 18 | | using Enums; |
| | 19 | | using Exceptions; |
| | 20 | | using Infrastructure.Bitcoin.Encoders; |
| | 21 | | using Infrastructure.Crypto.Hashes; |
| | 22 | | using Services; |
| | 23 | | using TaggedFields; |
| | 24 | |
|
| | 25 | | /// <summary> |
| | 26 | | /// Represents a BOLT11 Invoice |
| | 27 | | /// </summary> |
| | 28 | | /// <remarks> |
| | 29 | | /// The invoice is a payment request that can be sent to a payer to request a payment. |
| | 30 | | /// </remarks> |
| | 31 | | public partial class Invoice |
| | 32 | | { |
| | 33 | | #region Private Fields |
| | 34 | |
|
| 8 | 35 | | private static readonly InvoiceValidationService s_invoiceValidationService = new(); |
| | 36 | |
|
| 8 | 37 | | private static readonly Dictionary<string, BitcoinNetwork> s_supportedNetworks = new() |
| 8 | 38 | | { |
| 8 | 39 | | { InvoiceConstants.PrefixMainet, BitcoinNetwork.Mainnet }, |
| 8 | 40 | | { InvoiceConstants.PrefixTestnet, BitcoinNetwork.Testnet }, |
| 8 | 41 | | { InvoiceConstants.PrefixSignet, BitcoinNetwork.Signet }, |
| 8 | 42 | | { InvoiceConstants.PrefixRegtest, BitcoinNetwork.Regtest }, |
| 8 | 43 | | { InvoiceConstants.PrefixMainet.ToUpperInvariant(), BitcoinNetwork.Mainnet }, |
| 8 | 44 | | { InvoiceConstants.PrefixTestnet.ToUpperInvariant(), BitcoinNetwork.Testnet }, |
| 8 | 45 | | { InvoiceConstants.PrefixSignet.ToUpperInvariant(), BitcoinNetwork.Signet }, |
| 8 | 46 | | { InvoiceConstants.PrefixRegtest.ToUpperInvariant(), BitcoinNetwork.Regtest } |
| 8 | 47 | | }; |
| | 48 | |
|
| | 49 | | [GeneratedRegex(@"^[a-z]+((\d+)([munp])?)?$")] |
| | 50 | | private static partial Regex AmountRegex(); |
| | 51 | |
|
| | 52 | | private readonly ISecureKeyManager? _secureKeyManager; |
| | 53 | |
|
| 320 | 54 | | private readonly TaggedFieldList _taggedFields = []; |
| | 55 | |
|
| | 56 | | private string? _invoiceString; |
| | 57 | |
|
| | 58 | | #endregion |
| | 59 | |
|
| | 60 | | #region Public Properties |
| | 61 | |
|
| | 62 | | /// <summary> |
| | 63 | | /// The network the invoice is created for |
| | 64 | | /// </summary> |
| 308 | 65 | | public BitcoinNetwork BitcoinNetwork { get; } |
| | 66 | |
|
| | 67 | | /// <summary> |
| | 68 | | /// The amount for the invoice |
| | 69 | | /// </summary> |
| 476 | 70 | | public LightningMoney Amount { get; } |
| | 71 | |
|
| | 72 | | /// <summary> |
| | 73 | | /// The timestamp of the invoice |
| | 74 | | /// </summary> |
| | 75 | | /// <remarks> |
| | 76 | | /// The timestamp is the time the invoice was created in seconds since the Unix epoch. |
| | 77 | | /// </remarks> |
| 164 | 78 | | public long Timestamp { get; } |
| | 79 | |
|
| | 80 | | /// <summary> |
| | 81 | | /// The signature of the invoice |
| | 82 | | /// </summary> |
| 64 | 83 | | public CompactSignature Signature { get; } |
| | 84 | |
|
| | 85 | | /// <summary> |
| | 86 | | /// The human-readable part of the invoice |
| | 87 | | /// </summary> |
| 456 | 88 | | public string HumanReadablePart { get; } |
| | 89 | |
|
| | 90 | | #endregion |
| | 91 | |
|
| | 92 | | #region Public Properties from Tagged Fields |
| | 93 | |
|
| | 94 | | /// <summary> |
| | 95 | | /// The payment hash of the invoice |
| | 96 | | /// </summary> |
| | 97 | | /// <remarks> |
| | 98 | | /// The payment hash is a 32-byte hash used to identify a payment |
| | 99 | | /// </remarks> |
| | 100 | | /// <seealso cref="NBitcoin.uint256"/> |
| | 101 | | [DisallowNull] |
| | 102 | | public uint256? PaymentHash |
| | 103 | | { |
| | 104 | | get |
| | 105 | | { |
| 164 | 106 | | return _taggedFields.TryGet<PaymentHashTaggedField>(TaggedFieldTypes.PaymentHash, out var paymentHash) |
| 164 | 107 | | ? paymentHash.Value |
| 164 | 108 | | : null; |
| | 109 | | } |
| | 110 | | internal set |
| | 111 | | { |
| 128 | 112 | | _taggedFields.Add(new PaymentHashTaggedField(value)); |
| 128 | 113 | | } |
| | 114 | | } |
| | 115 | |
|
| | 116 | | /// <summary> |
| | 117 | | /// The Routing Information of the invoice |
| | 118 | | /// </summary> |
| | 119 | | /// <remarks> |
| | 120 | | /// The routing information is used to hint about the route the payment could take |
| | 121 | | /// </remarks> |
| | 122 | | /// <seealso cref="RoutingInfoCollection"/> |
| | 123 | | /// <seealso cref="RoutingInfo"/> |
| | 124 | | [DisallowNull] |
| | 125 | | public RoutingInfoCollection? RoutingInfos |
| | 126 | | { |
| | 127 | | get |
| | 128 | | { |
| 100 | 129 | | return _taggedFields.TryGet<RoutingInfoTaggedField>(TaggedFieldTypes.RoutingInfo, out var routingInfo) |
| 100 | 130 | | ? routingInfo.Value |
| 100 | 131 | | : null; |
| | 132 | | } |
| | 133 | | set |
| | 134 | | { |
| 16 | 135 | | _taggedFields.Add(new RoutingInfoTaggedField(value)); |
| 16 | 136 | | value.Changed += OnTaggedFieldsChanged; |
| 16 | 137 | | } |
| | 138 | | } |
| | 139 | |
|
| | 140 | | /// <summary> |
| | 141 | | /// The features of the invoice |
| | 142 | | /// </summary> |
| | 143 | | /// <remarks> |
| | 144 | | /// The features are used to specify the features the payer should support |
| | 145 | | /// </remarks> |
| | 146 | | /// <seealso cref="FeatureSet"/> |
| | 147 | | [DisallowNull] |
| | 148 | | public FeatureSet? Features |
| | 149 | | { |
| | 150 | | get |
| | 151 | | { |
| 112 | 152 | | return _taggedFields.TryGet<FeaturesTaggedField>(TaggedFieldTypes.Features, out var features) |
| 112 | 153 | | ? features.Value |
| 112 | 154 | | : null; |
| | 155 | | } |
| | 156 | | set |
| | 157 | | { |
| 52 | 158 | | _taggedFields.Add(new FeaturesTaggedField(value)); |
| 52 | 159 | | value.Changed += OnTaggedFieldsChanged; |
| 52 | 160 | | } |
| | 161 | | } |
| | 162 | |
|
| | 163 | | /// <summary> |
| | 164 | | /// The expiry date of the invoice |
| | 165 | | /// </summary> |
| | 166 | | /// <remarks> |
| | 167 | | /// The expiry date is the date the invoice expires |
| | 168 | | /// </remarks> |
| | 169 | | /// <seealso cref="DateTimeOffset"/> |
| | 170 | | public DateTimeOffset ExpiryDate |
| | 171 | | { |
| | 172 | | get |
| | 173 | | { |
| 20 | 174 | | return _taggedFields.TryGet<ExpiryTimeTaggedField>(TaggedFieldTypes.ExpiryTime, out var expireIn) |
| 20 | 175 | | ? DateTimeOffset.FromUnixTimeSeconds(Timestamp + expireIn.Value) |
| 20 | 176 | | : DateTimeOffset.FromUnixTimeSeconds(Timestamp + InvoiceConstants.DefaultExpirationSeconds); |
| | 177 | | } |
| | 178 | | set |
| | 179 | | { |
| 16 | 180 | | var expireIn = value.ToUnixTimeSeconds() - Timestamp; |
| 16 | 181 | | _taggedFields.Add(new ExpiryTimeTaggedField((int)expireIn)); |
| 16 | 182 | | } |
| | 183 | | } |
| | 184 | |
|
| | 185 | | /// <summary> |
| | 186 | | /// The fallback addresses of the invoice |
| | 187 | | /// </summary> |
| | 188 | | /// <remarks> |
| | 189 | | /// The fallback addresses are used to specify the fallback addresses the payer can use |
| | 190 | | /// </remarks> |
| | 191 | | /// <seealso cref="BitcoinAddress"/> |
| | 192 | | [DisallowNull] |
| | 193 | | public List<BitcoinAddress>? FallbackAddresses |
| | 194 | | { |
| | 195 | | get |
| | 196 | | { |
| 36 | 197 | | return _taggedFields |
| 36 | 198 | | .TryGetAll(TaggedFieldTypes.FallbackAddress, out List<FallbackAddressTaggedField> fallbackAddress) |
| 52 | 199 | | ? fallbackAddress.Select(x => x.Value).ToList() |
| 36 | 200 | | : null; |
| | 201 | | } |
| | 202 | | set |
| | 203 | | { |
| 52 | 204 | | _taggedFields.AddRange(value.Select(x => new FallbackAddressTaggedField(x))); |
| 24 | 205 | | } |
| | 206 | | } |
| | 207 | |
|
| | 208 | | /// <summary> |
| | 209 | | /// The description of the invoice |
| | 210 | | /// </summary> |
| | 211 | | /// <remarks> |
| | 212 | | /// The description is a UTF-8 encoded string that describes, in short, the purpose of payment |
| | 213 | | /// </remarks> |
| | 214 | | public string? Description |
| | 215 | | { |
| | 216 | | get |
| | 217 | | { |
| 240 | 218 | | return _taggedFields.TryGet<DescriptionTaggedField>(TaggedFieldTypes.Description, out var description) |
| 240 | 219 | | ? description.Value |
| 240 | 220 | | : null; |
| | 221 | | } |
| | 222 | | internal set |
| | 223 | | { |
| 116 | 224 | | if (value != null) |
| | 225 | | { |
| 116 | 226 | | _taggedFields.Add(new DescriptionTaggedField(value)); |
| | 227 | | } |
| | 228 | | else |
| | 229 | | { |
| 0 | 230 | | _taggedFields.RemoveAll(t => t.Type.Equals(TaggedFieldTypes.Description)); |
| | 231 | | } |
| 0 | 232 | | } |
| | 233 | | } |
| | 234 | |
|
| | 235 | | /// <summary> |
| | 236 | | /// The payment secret of the invoice |
| | 237 | | /// </summary> |
| | 238 | | /// <remarks> |
| | 239 | | /// The payment secret is a 32-byte secret used to identify a payment |
| | 240 | | /// </remarks> |
| | 241 | | /// <seealso cref="uint256"/> |
| | 242 | | [DisallowNull] |
| | 243 | | public uint256? PaymentSecret |
| | 244 | | { |
| | 245 | | get |
| | 246 | | { |
| 164 | 247 | | return _taggedFields.TryGet<PaymentSecretTaggedField>(TaggedFieldTypes.PaymentSecret, out var paymentSecret) |
| 164 | 248 | | ? paymentSecret.Value |
| 164 | 249 | | : null; |
| | 250 | | } |
| | 251 | | internal set |
| | 252 | | { |
| 136 | 253 | | _taggedFields.Add(new PaymentSecretTaggedField(value)); |
| 136 | 254 | | } |
| | 255 | | } |
| | 256 | |
|
| | 257 | | /// <summary> |
| | 258 | | /// The payee pubkey of the invoice |
| | 259 | | /// </summary> |
| | 260 | | /// <remarks> |
| | 261 | | /// The payee pubkey is the pubkey of the payee |
| | 262 | | /// </remarks> |
| | 263 | | /// <seealso cref="PubKey"/> |
| | 264 | | [DisallowNull] |
| | 265 | | public PubKey? PayeePubKey |
| | 266 | | { |
| | 267 | | get |
| | 268 | | { |
| 120 | 269 | | return _taggedFields.TryGet<PayeePubKeyTaggedField>(TaggedFieldTypes.PayeePubKey, out var payeePubKey) |
| 120 | 270 | | ? payeePubKey.Value |
| 120 | 271 | | : null; |
| | 272 | | } |
| | 273 | | set |
| | 274 | | { |
| 64 | 275 | | _taggedFields.Add(new PayeePubKeyTaggedField(value)); |
| 64 | 276 | | } |
| | 277 | | } |
| | 278 | |
|
| | 279 | | /// <summary> |
| | 280 | | /// The description hash of the invoice |
| | 281 | | /// </summary> |
| | 282 | | /// <remarks> |
| | 283 | | /// The description hash is a 32-byte hash of the description |
| | 284 | | /// </remarks> |
| | 285 | | /// <seealso cref="uint256"/> |
| | 286 | | public uint256? DescriptionHash |
| | 287 | | { |
| | 288 | | get |
| | 289 | | { |
| 232 | 290 | | return _taggedFields |
| 232 | 291 | | .TryGet<DescriptionHashTaggedField>(TaggedFieldTypes.DescriptionHash, out var descriptionHash) |
| 232 | 292 | | ? descriptionHash.Value |
| 232 | 293 | | : null; |
| | 294 | | } |
| | 295 | | internal set |
| | 296 | | { |
| 32 | 297 | | if (value != null) |
| | 298 | | { |
| 32 | 299 | | _taggedFields.Add(new DescriptionHashTaggedField(value)); |
| | 300 | | } |
| | 301 | | else |
| | 302 | | { |
| | 303 | | // If the description hash is set to null, remove it from the tagged fields |
| 0 | 304 | | _taggedFields.RemoveAll(x => x.Type.Equals(TaggedFieldTypes.DescriptionHash)); |
| | 305 | | } |
| 0 | 306 | | } |
| | 307 | | } |
| | 308 | |
|
| | 309 | | /// <summary> |
| | 310 | | /// The min final cltv expiry of the invoice |
| | 311 | | /// </summary> |
| | 312 | | /// <remarks> |
| | 313 | | /// The min final cltv expiry is the minimum final cltv expiry the payer should use |
| | 314 | | /// </remarks> |
| | 315 | | [DisallowNull] |
| | 316 | | public ushort? MinFinalCltvExpiry |
| | 317 | | { |
| | 318 | | get |
| | 319 | | { |
| 4 | 320 | | return _taggedFields.TryGet<MinFinalCltvExpiryTaggedField>(TaggedFieldTypes.MinFinalCltvExpiry, |
| 4 | 321 | | out var minFinalCltvExpiry) |
| 4 | 322 | | ? minFinalCltvExpiry.Value |
| 4 | 323 | | : null; |
| | 324 | | } |
| | 325 | | set |
| | 326 | | { |
| 4 | 327 | | _taggedFields.Add(new MinFinalCltvExpiryTaggedField(value.Value)); |
| 4 | 328 | | } |
| | 329 | | } |
| | 330 | |
|
| | 331 | | /// <summary> |
| | 332 | | /// The metadata of the invoice |
| | 333 | | /// </summary> |
| | 334 | | /// <remarks> |
| | 335 | | /// The metadata is used to add additional information to the invoice |
| | 336 | | /// </remarks> |
| | 337 | | public byte[]? Metadata |
| | 338 | | { |
| | 339 | | get |
| | 340 | | { |
| 4 | 341 | | return _taggedFields.TryGet<MetadataTaggedField>(TaggedFieldTypes.Metadata, out var metadata) |
| 4 | 342 | | ? metadata.Value |
| 4 | 343 | | : null; |
| | 344 | | } |
| | 345 | | set |
| | 346 | | { |
| 4 | 347 | | if (value != null) |
| | 348 | | { |
| 4 | 349 | | _taggedFields.Add(new MetadataTaggedField(value)); |
| | 350 | | } |
| | 351 | | else |
| | 352 | | { |
| 0 | 353 | | _taggedFields.RemoveAll(x => x.Type.Equals(TaggedFieldTypes.Metadata)); |
| | 354 | | } |
| 0 | 355 | | } |
| | 356 | | } |
| | 357 | |
|
| | 358 | | #endregion |
| | 359 | |
|
| | 360 | | #region Constructors |
| | 361 | |
|
| | 362 | | /// <summary> |
| | 363 | | /// The base constructor for the invoice |
| | 364 | | /// </summary> |
| | 365 | | /// <param name="amount">The amount of the invoice</param> |
| | 366 | | /// <param name="description">The description of the invoice</param> |
| | 367 | | /// <param name="paymentHash">The payment hash of the invoice</param> |
| | 368 | | /// <param name="paymentSecret">The payment secret of the invoice</param> |
| | 369 | | /// <param name="bitcoinNetwork">The network the invoice is created for</param> |
| | 370 | | /// <param name="secureKeyManager">Secure key manager</param> |
| | 371 | | /// <remarks> |
| | 372 | | /// The invoice is created with the given amount of millisatoshis, a description, the payment hash and the |
| | 373 | | /// payment secret. |
| | 374 | | /// </remarks> |
| | 375 | | /// <seealso cref="BitcoinNetwork"/> |
| 48 | 376 | | public Invoice(LightningMoney amount, string description, uint256 paymentHash, uint256 paymentSecret, |
| 48 | 377 | | BitcoinNetwork bitcoinNetwork, ISecureKeyManager? secureKeyManager = null) |
| | 378 | | { |
| 48 | 379 | | _secureKeyManager = secureKeyManager; |
| | 380 | |
|
| 48 | 381 | | Amount = amount; |
| 48 | 382 | | BitcoinNetwork = bitcoinNetwork; |
| 48 | 383 | | HumanReadablePart = BuildHumanReadablePart(); |
| 48 | 384 | | Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); |
| 48 | 385 | | Signature = new CompactSignature(0, new byte[64]); |
| | 386 | |
|
| | 387 | | // Set Required Fields |
| 48 | 388 | | Description = description; |
| 48 | 389 | | PaymentHash = paymentHash; |
| 48 | 390 | | PaymentSecret = paymentSecret; |
| | 391 | |
|
| 48 | 392 | | _taggedFields.Changed += OnTaggedFieldsChanged; |
| 48 | 393 | | } |
| | 394 | |
|
| | 395 | | /// <summary> |
| | 396 | | /// The base constructor for the invoice |
| | 397 | | /// </summary> |
| | 398 | | /// <param name="amount">The amount of the invoice</param> |
| | 399 | | /// <param name="descriptionHash">The description hash of the invoice</param> |
| | 400 | | /// <param name="paymentHash">The payment hash of the invoice</param> |
| | 401 | | /// <param name="paymentSecret">The payment secret of the invoice</param> |
| | 402 | | /// <param name="bitcoinNetwork">The network the invoice is created for</param> |
| | 403 | | /// <param name="secureKeyManager">Secure key manager</param> |
| | 404 | | /// <remarks> |
| | 405 | | /// The invoice is created with the given amount of millisatoshis, a description hash, the payment hash and the |
| | 406 | | /// payment secret. |
| | 407 | | /// </remarks> |
| | 408 | | /// <seealso cref="BitcoinNetwork"/> |
| 0 | 409 | | public Invoice(LightningMoney amount, uint256 descriptionHash, uint256 paymentHash, uint256 paymentSecret, |
| 0 | 410 | | BitcoinNetwork bitcoinNetwork, ISecureKeyManager? secureKeyManager = null) |
| | 411 | | { |
| 0 | 412 | | _secureKeyManager = secureKeyManager; |
| | 413 | |
|
| 0 | 414 | | Amount = amount; |
| 0 | 415 | | BitcoinNetwork = bitcoinNetwork; |
| 0 | 416 | | HumanReadablePart = BuildHumanReadablePart(); |
| 0 | 417 | | Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); |
| 0 | 418 | | Signature = new CompactSignature(0, new byte[64]); |
| | 419 | |
|
| | 420 | | // Set Required Fields |
| 0 | 421 | | DescriptionHash = descriptionHash; |
| 0 | 422 | | PaymentHash = paymentHash; |
| 0 | 423 | | PaymentSecret = paymentSecret; |
| | 424 | |
|
| 0 | 425 | | _taggedFields.Changed += OnTaggedFieldsChanged; |
| 0 | 426 | | } |
| | 427 | |
|
| | 428 | | /// <summary> |
| | 429 | | /// This constructor is used by tests |
| | 430 | | /// </summary> |
| | 431 | | /// <param name="bitcoinNetwork">The network the invoice is created for</param> |
| | 432 | | /// <param name="amount">The amount of the invoice</param> |
| | 433 | | /// <param name="timestamp">The timestamp of the invoice</param> |
| | 434 | | /// <remarks> |
| | 435 | | /// The invoice is created with the given network, amount of millisatoshis and timestamp. |
| | 436 | | /// </remarks> |
| | 437 | | /// <seealso cref="BitcoinNetwork"/> |
| 204 | 438 | | internal Invoice(BitcoinNetwork bitcoinNetwork, LightningMoney? amount = null, long? timestamp = null) |
| | 439 | | { |
| 204 | 440 | | Amount = amount ?? LightningMoney.Zero; |
| 204 | 441 | | BitcoinNetwork = bitcoinNetwork; |
| 204 | 442 | | HumanReadablePart = BuildHumanReadablePart(); |
| 200 | 443 | | Timestamp = timestamp ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds(); |
| 200 | 444 | | Signature = new CompactSignature(0, new byte[64]); |
| | 445 | |
|
| 200 | 446 | | _taggedFields.Changed += OnTaggedFieldsChanged; |
| 200 | 447 | | } |
| | 448 | |
|
| | 449 | | /// <summary> |
| | 450 | | /// This constructor is used by Decode |
| | 451 | | /// </summary> |
| | 452 | | /// <param name="invoiceString">The invoice string</param> |
| | 453 | | /// <param name="humanReadablePart">The human-readable part of the invoice</param> |
| | 454 | | /// <param name="bitcoinNetwork">The network the invoice is created for</param> |
| | 455 | | /// <param name="amount">The amount of the invoice</param> |
| | 456 | | /// <param name="timestamp">The timestamp of the invoice</param> |
| | 457 | | /// <param name="taggedFields">The tagged fields of the invoice</param> |
| | 458 | | /// <param name="signature">The invoice signature</param> |
| | 459 | | /// <remarks> |
| | 460 | | /// The invoice is created with the given human-readable part, network, amount of millisatoshis, |
| | 461 | | /// timestamp and tagged fields. |
| | 462 | | /// </remarks> |
| | 463 | | /// <seealso cref="BitcoinNetwork"/> |
| 68 | 464 | | private Invoice(string invoiceString, string humanReadablePart, BitcoinNetwork bitcoinNetwork, |
| 68 | 465 | | LightningMoney amount, |
| 68 | 466 | | long timestamp, TaggedFieldList taggedFields, CompactSignature signature) |
| | 467 | | { |
| 68 | 468 | | _invoiceString = invoiceString; |
| | 469 | |
|
| 68 | 470 | | BitcoinNetwork = bitcoinNetwork; |
| 68 | 471 | | HumanReadablePart = humanReadablePart; |
| 68 | 472 | | Amount = amount; |
| 68 | 473 | | Timestamp = timestamp; |
| 68 | 474 | | _taggedFields = taggedFields; |
| 68 | 475 | | Signature = signature; |
| | 476 | |
|
| 68 | 477 | | _taggedFields.Changed += OnTaggedFieldsChanged; |
| 68 | 478 | | } |
| | 479 | |
|
| | 480 | | #endregion |
| | 481 | |
|
| | 482 | | #region Static Constructors |
| | 483 | |
|
| | 484 | | /// <summary> |
| | 485 | | /// Creates a new invoice with the given amount of satoshis |
| | 486 | | /// </summary> |
| | 487 | | /// <param name="amountSats">The amount of satoshis the invoice is for</param> |
| | 488 | | /// <param name="description">The description of the invoice</param> |
| | 489 | | /// <param name="paymentHash">The payment hash of the invoice</param> |
| | 490 | | /// <param name="paymentSecret">The payment secret of the invoice</param> |
| | 491 | | /// <param name="bitcoinNetwork">The network the invoice is created for</param> |
| | 492 | | /// <remarks> |
| | 493 | | /// The invoice is created with the given amount of satoshis, a description, the payment hash and the |
| | 494 | | /// payment secret. |
| | 495 | | /// </remarks> |
| | 496 | | /// <returns>The invoice</returns> |
| | 497 | | public static Invoice InSatoshis(ulong amountSats, string description, uint256 paymentHash, uint256 paymentSecret, |
| | 498 | | BitcoinNetwork bitcoinNetwork) |
| | 499 | | { |
| 44 | 500 | | return new Invoice(LightningMoney.Satoshis(amountSats), description, paymentHash, paymentSecret, |
| 44 | 501 | | bitcoinNetwork); |
| | 502 | | } |
| | 503 | |
|
| | 504 | | /// <summary> |
| | 505 | | /// Creates a new invoice with the given amount of satoshis |
| | 506 | | /// </summary> |
| | 507 | | /// <param name="amountSats">The amount of satoshis the invoice is for</param> |
| | 508 | | /// <param name="descriptionHash">The description hash of the invoice</param> |
| | 509 | | /// <param name="paymentHash">The payment hash of the invoice</param> |
| | 510 | | /// <param name="paymentSecret">The payment secret of the invoice</param> |
| | 511 | | /// <param name="bitcoinNetwork">The network the invoice is created for</param> |
| | 512 | | /// <remarks> |
| | 513 | | /// The invoice is created with the given amount of satoshis, a description hash, the payment hash and the |
| | 514 | | /// payment secret. |
| | 515 | | /// </remarks> |
| | 516 | | /// <returns>The invoice</returns> |
| | 517 | | public static Invoice InSatoshis(ulong amountSats, uint256 descriptionHash, uint256 paymentHash, |
| | 518 | | uint256 paymentSecret, BitcoinNetwork bitcoinNetwork) |
| | 519 | | { |
| 0 | 520 | | return new Invoice(LightningMoney.Satoshis(amountSats), descriptionHash, paymentHash, paymentSecret, |
| 0 | 521 | | bitcoinNetwork); |
| | 522 | | } |
| | 523 | |
|
| | 524 | | /// <summary> |
| | 525 | | /// Decodes an invoice from a string |
| | 526 | | /// </summary> |
| | 527 | | /// <param name="invoiceString">The invoice string</param> |
| | 528 | | /// <param name="expectedNetwork">The expected network of the invoice</param> |
| | 529 | | /// <returns>The invoice</returns> |
| | 530 | | /// <exception cref="InvoiceSerializationException">If something goes wrong in the decoding process</exception> |
| | 531 | | public static Invoice Decode(string? invoiceString, BitcoinNetwork? expectedNetwork = null) |
| | 532 | | { |
| 96 | 533 | | InvoiceSerializationException.ThrowIfNullOrWhiteSpace(invoiceString); |
| | 534 | |
|
| | 535 | | try |
| | 536 | | { |
| 92 | 537 | | Bech32Encoder.DecodeLightningInvoice(invoiceString, out var data, out var signature, out var hrp); |
| | 538 | |
|
| 76 | 539 | | var network = GetNetwork(invoiceString); |
| 76 | 540 | | if (expectedNetwork is not null && network != expectedNetwork) |
| 0 | 541 | | throw new InvoiceSerializationException("Expected network does not match"); |
| | 542 | |
|
| 76 | 543 | | var amount = ConvertHumanReadableToMilliSatoshis(hrp); |
| | 544 | |
|
| | 545 | | // Initialize the BitReader buffer |
| 68 | 546 | | var bitReader = new BitReader(data); |
| | 547 | |
|
| 68 | 548 | | var timestamp = bitReader.ReadInt64FromBits(35); |
| | 549 | |
|
| 68 | 550 | | var taggedFields = TaggedFieldList.FromBitReader(bitReader, network); |
| | 551 | |
|
| | 552 | | // TODO: Check feature bits |
| | 553 | |
|
| 68 | 554 | | var invoice = new Invoice(invoiceString, hrp, network, amount, timestamp, taggedFields, |
| 68 | 555 | | new CompactSignature(signature[^1], signature[..^1])); |
| | 556 | |
|
| 68 | 557 | | var validationResult = s_invoiceValidationService.ValidateInvoice(invoice); |
| 68 | 558 | | if (!validationResult.IsValid) |
| 4 | 559 | | throw new InvoiceSerializationException(string.Join(", ", validationResult.Errors)); |
| | 560 | |
|
| | 561 | | // Check Signature |
| 64 | 562 | | invoice.CheckSignature(data); |
| | 563 | |
|
| 60 | 564 | | return invoice; |
| | 565 | | } |
| 32 | 566 | | catch (Exception e) |
| | 567 | | { |
| 32 | 568 | | throw new InvoiceSerializationException("Error decoding invoice", e); |
| | 569 | | } |
| 60 | 570 | | } |
| | 571 | |
|
| | 572 | | #endregion |
| | 573 | |
|
| | 574 | | /// <summary> |
| | 575 | | /// Encodes the current invoice into a lightning-compatible invoice format as a string. |
| | 576 | | /// </summary> |
| | 577 | | /// <param name="nodeKey">The private key of the node used to sign the invoice.</param> |
| | 578 | | /// <returns>The encoded lightning invoice as a string.</returns> |
| | 579 | | /// <exception cref="InvoiceSerializationException"> |
| | 580 | | /// Thrown when an error occurs during the encoding process. |
| | 581 | | /// </exception> |
| | 582 | | public string Encode(Key nodeKey) |
| | 583 | | { |
| | 584 | | try |
| | 585 | | { |
| | 586 | | // Calculate the size needed for the buffer |
| 72 | 587 | | var sizeInBits = 35 + (_taggedFields.CalculateSizeInBits() * 5) + (_taggedFields.Count * 15); |
| | 588 | |
|
| | 589 | | // Initialize the BitWriter buffer |
| 72 | 590 | | var bitWriter = new BitWriter(sizeInBits); |
| | 591 | |
|
| | 592 | | // Write the timestamp |
| 72 | 593 | | bitWriter.WriteInt64AsBits(Timestamp, 35); |
| | 594 | |
|
| | 595 | | // Write the tagged fields |
| 72 | 596 | | _taggedFields.WriteToBitWriter(bitWriter); |
| | 597 | |
|
| | 598 | | // Sign the invoice |
| 72 | 599 | | var compactSignature = SignInvoice(HumanReadablePart, bitWriter, nodeKey); |
| 72 | 600 | | var signature = new byte[compactSignature.Signature.Length + 1]; |
| 72 | 601 | | compactSignature.Signature.CopyTo(signature, 0); |
| 72 | 602 | | signature[^1] = (byte)compactSignature.RecoveryId; |
| | 603 | |
|
| 72 | 604 | | var bech32Encoder = new Bech32Encoder(HumanReadablePart); |
| 72 | 605 | | _invoiceString = bech32Encoder.EncodeLightningInvoice(bitWriter, signature); |
| | 606 | |
|
| 72 | 607 | | return _invoiceString; |
| | 608 | | } |
| 0 | 609 | | catch (Exception e) |
| | 610 | | { |
| 0 | 611 | | throw new InvoiceSerializationException("Error encoding invoice", e); |
| | 612 | | } |
| 72 | 613 | | } |
| | 614 | |
|
| | 615 | | /// <summary> |
| | 616 | | /// Encodes the invoice into its string representation using the secure key manager. |
| | 617 | | /// </summary> |
| | 618 | | /// <returns>The encoded invoice string.</returns> |
| | 619 | | /// <exception cref="NullReferenceException">Thrown when the secure key manager is not set.</exception> |
| | 620 | | public string Encode() |
| | 621 | | { |
| 0 | 622 | | if (_secureKeyManager is null) |
| 0 | 623 | | throw new NullReferenceException("Secure key manager is not set, please use Encode(Key nodeKey) instead"); |
| | 624 | |
|
| 0 | 625 | | var nodeKey = _secureKeyManager.GetNodeKeyPair().PrivKey; |
| 0 | 626 | | return Encode(new Key(nodeKey)); |
| | 627 | | } |
| | 628 | |
|
| | 629 | | #region Overrides |
| | 630 | |
|
| | 631 | | public override string ToString() |
| | 632 | | { |
| 0 | 633 | | return string.IsNullOrWhiteSpace(_invoiceString) ? Encode() : _invoiceString; |
| | 634 | | } |
| | 635 | |
|
| | 636 | | /// <summary> |
| | 637 | | /// Converts the invoice object to its string representation. |
| | 638 | | /// </summary> |
| | 639 | | /// <remarks> |
| | 640 | | /// If the invoice string exists, it is returned directly. |
| | 641 | | /// Otherwise, the invoice is encoded using the provided node key. |
| | 642 | | /// </remarks> |
| | 643 | | /// <param name="nodeKey">The node key used for signing the invoice.</param> |
| | 644 | | /// <returns>A string representation of the invoice.</returns> |
| | 645 | | /// <exception cref="InvoiceSerializationException"> |
| | 646 | | /// Thrown when an error occurs during the encoding process. |
| | 647 | | /// </exception> |
| | 648 | | public string ToString(Key nodeKey) |
| | 649 | | { |
| 16 | 650 | | return string.IsNullOrWhiteSpace(_invoiceString) ? Encode(nodeKey) : _invoiceString; |
| | 651 | | } |
| | 652 | |
|
| | 653 | | #endregion |
| | 654 | |
|
| | 655 | | #region Private Methods |
| | 656 | |
|
| | 657 | | private string BuildHumanReadablePart() |
| | 658 | | { |
| 252 | 659 | | StringBuilder sb = new(InvoiceConstants.Prefix); |
| 252 | 660 | | sb.Append(GetPrefix(BitcoinNetwork)); |
| 248 | 661 | | if (!Amount.IsZero) |
| 168 | 662 | | ConvertAmountToHumanReadable(Amount, sb); |
| | 663 | |
|
| 248 | 664 | | return sb.ToString(); |
| | 665 | | } |
| | 666 | |
|
| | 667 | | private static string GetPrefix(BitcoinNetwork bitcoinNetwork) |
| | 668 | | { |
| 252 | 669 | | return bitcoinNetwork.Name switch |
| 252 | 670 | | { |
| 232 | 671 | | NetworkConstants.Mainnet => InvoiceConstants.PrefixMainet, |
| 8 | 672 | | NetworkConstants.Testnet => InvoiceConstants.PrefixTestnet, |
| 4 | 673 | | NetworkConstants.Regtest => InvoiceConstants.PrefixRegtest, |
| 4 | 674 | | NetworkConstants.Signet => InvoiceConstants.PrefixSignet, |
| 4 | 675 | | _ => throw new ArgumentException("Unsupported network type", nameof(bitcoinNetwork)), |
| 252 | 676 | | }; |
| | 677 | | } |
| | 678 | |
|
| | 679 | | private static void ConvertAmountToHumanReadable(LightningMoney amount, StringBuilder sb) |
| | 680 | | { |
| 168 | 681 | | var btcAmount = amount.ToUnit(LightningMoneyUnit.Btc); |
| | 682 | |
|
| | 683 | | // Start with the smallest multiplier |
| 168 | 684 | | var tempAmount = btcAmount * 1_000_000_000_000m; // Start with pico |
| 168 | 685 | | char? suffix = InvoiceConstants.MultiplierPico; |
| | 686 | |
|
| | 687 | | // Try nano |
| 168 | 688 | | if (amount.MilliSatoshi % 10 == 0) |
| | 689 | | { |
| 160 | 690 | | var nanoAmount = btcAmount * 1_000_000_000m; |
| 160 | 691 | | if (nanoAmount == decimal.Truncate(nanoAmount)) |
| | 692 | | { |
| 156 | 693 | | tempAmount = nanoAmount; |
| 156 | 694 | | suffix = InvoiceConstants.MultiplierNano; |
| | 695 | | } |
| | 696 | | } |
| | 697 | |
|
| | 698 | | // Try micro |
| 168 | 699 | | if (amount.MilliSatoshi % 1_000 == 0) |
| | 700 | | { |
| 152 | 701 | | var microAmount = btcAmount * 1_000_000m; |
| 152 | 702 | | if (microAmount == decimal.Truncate(microAmount)) |
| | 703 | | { |
| 136 | 704 | | tempAmount = microAmount; |
| 136 | 705 | | suffix = InvoiceConstants.MultiplierMicro; |
| | 706 | | } |
| | 707 | | } |
| | 708 | |
|
| | 709 | | // Try milli |
| 168 | 710 | | if (amount.MilliSatoshi % 1_000_000 == 0) |
| | 711 | | { |
| 128 | 712 | | var milliAmount = btcAmount * 1000m; |
| 128 | 713 | | if (milliAmount == decimal.Truncate(milliAmount)) |
| | 714 | | { |
| 100 | 715 | | tempAmount = milliAmount; |
| 100 | 716 | | suffix = InvoiceConstants.MultiplierMilli; |
| | 717 | | } |
| | 718 | | } |
| | 719 | |
|
| | 720 | | // Try full BTC |
| 168 | 721 | | if (amount.MilliSatoshi % 1_000_000_000 == 0) |
| | 722 | | { |
| 84 | 723 | | if (btcAmount == decimal.Truncate(btcAmount)) |
| | 724 | | { |
| 40 | 725 | | tempAmount = btcAmount; |
| 40 | 726 | | suffix = null; |
| | 727 | | } |
| | 728 | | } |
| | 729 | |
|
| 168 | 730 | | sb.Append(tempAmount.ToString("F0").TrimEnd('.')); |
| 168 | 731 | | sb.Append(suffix); |
| 168 | 732 | | } |
| | 733 | |
|
| | 734 | | private static ulong ConvertHumanReadableToMilliSatoshis(string humanReadablePart) |
| | 735 | | { |
| 76 | 736 | | var match = AmountRegex().Match(humanReadablePart); |
| 76 | 737 | | if (!match.Success) |
| 4 | 738 | | throw new ArgumentException("Invalid amount format in invoice", nameof(humanReadablePart)); |
| | 739 | |
|
| 72 | 740 | | var amountString = match.Groups[2].Value; |
| 72 | 741 | | var multiplier = match.Groups[3].Value; |
| 72 | 742 | | var millisatoshis = 0ul; |
| 72 | 743 | | if (!ulong.TryParse(amountString, out var amount)) |
| 8 | 744 | | return millisatoshis; |
| | 745 | |
|
| 64 | 746 | | if (multiplier == "p" && amount % 10 != 0) |
| 4 | 747 | | throw new ArgumentException("Invalid pico amount in invoice", nameof(humanReadablePart)); |
| | 748 | |
|
| | 749 | | // Calculate the millisatoshis |
| 60 | 750 | | millisatoshis = multiplier switch |
| 60 | 751 | | { |
| 44 | 752 | | "m" => amount * 100_000_000, |
| 12 | 753 | | "u" => amount * 100_000, |
| 0 | 754 | | "n" => amount * 100, |
| 4 | 755 | | "p" => amount / 10, |
| 0 | 756 | | _ => amount * 100_000_000_000 |
| 60 | 757 | | }; |
| | 758 | |
|
| 60 | 759 | | return millisatoshis; |
| | 760 | | } |
| | 761 | |
|
| | 762 | | private void CheckSignature(byte[] data) |
| | 763 | | { |
| | 764 | | // Assemble the message (hrp + data) |
| 64 | 765 | | var message = new byte[HumanReadablePart.Length + data.Length]; |
| 64 | 766 | | Encoding.UTF8.GetBytes(HumanReadablePart).CopyTo(message, 0); |
| 64 | 767 | | data.CopyTo(message, HumanReadablePart.Length); |
| | 768 | |
|
| | 769 | | // Get sha256 hash of the message |
| 64 | 770 | | var hash = new byte[CryptoConstants.Sha256HashLen]; |
| 64 | 771 | | using var sha256 = new Sha256(); |
| 64 | 772 | | sha256.AppendData(message); |
| 64 | 773 | | sha256.GetHashAndReset(hash); |
| | 774 | |
|
| 64 | 775 | | var nBitcoinHash = new uint256(hash); |
| | 776 | |
|
| | 777 | | // Check if recovery is necessary |
| 64 | 778 | | if (PayeePubKey is null) |
| | 779 | | { |
| 64 | 780 | | PayeePubKey = PubKey.RecoverCompact(nBitcoinHash, Signature); |
| 60 | 781 | | return; |
| | 782 | | } |
| | 783 | |
|
| 0 | 784 | | if (NBitcoin.Crypto.ECDSASignature.TryParseFromCompact(Signature.Signature, out var ecdsa) |
| 0 | 785 | | && PayeePubKey.Verify(nBitcoinHash, ecdsa)) |
| 0 | 786 | | return; |
| | 787 | |
|
| 0 | 788 | | throw new ArgumentException("Invalid signature in invoice"); |
| 60 | 789 | | } |
| | 790 | |
|
| | 791 | | private static CompactSignature SignInvoice(string hrp, BitWriter bitWriter, Key key) |
| | 792 | | { |
| | 793 | | // Assemble the message (hrp + data) |
| 72 | 794 | | var data = bitWriter.ToArray(); |
| 72 | 795 | | var message = new byte[hrp.Length + data.Length]; |
| 72 | 796 | | Encoding.UTF8.GetBytes(hrp).CopyTo(message, 0); |
| 72 | 797 | | data.CopyTo(message, hrp.Length); |
| | 798 | |
|
| | 799 | | // Get sha256 hash of the message |
| 72 | 800 | | var hash = new byte[CryptoConstants.Sha256HashLen]; |
| 72 | 801 | | using var sha256 = new Sha256(); |
| 72 | 802 | | sha256.AppendData(message); |
| 72 | 803 | | sha256.GetHashAndReset(hash); |
| 72 | 804 | | var nBitcoinHash = new uint256(hash); |
| | 805 | |
|
| | 806 | | // Sign the hash |
| 72 | 807 | | return key.SignCompact(nBitcoinHash, false); |
| 72 | 808 | | } |
| | 809 | |
|
| | 810 | | private static BitcoinNetwork GetNetwork(string? invoiceString) |
| | 811 | | { |
| 76 | 812 | | ArgumentException.ThrowIfNullOrWhiteSpace(invoiceString); |
| | 813 | |
|
| 76 | 814 | | if (invoiceString.Length < 6) |
| 0 | 815 | | throw new ArgumentException("Invoice string is too short to extract network prefix", nameof(invoiceString)); |
| | 816 | |
|
| 76 | 817 | | if (!s_supportedNetworks.TryGetValue(invoiceString.Substring(2, 4), out var network) |
| 76 | 818 | | && !s_supportedNetworks.TryGetValue(invoiceString.Substring(2, 3), out network) |
| 76 | 819 | | && !s_supportedNetworks.TryGetValue(invoiceString.Substring(2, 2), out network)) |
| 0 | 820 | | throw new ArgumentException("Unsupported prefix in invoice", nameof(invoiceString)); |
| | 821 | |
|
| 76 | 822 | | return network; |
| | 823 | | } |
| | 824 | |
|
| | 825 | | private void OnTaggedFieldsChanged(object? sender, EventArgs args) |
| | 826 | | { |
| 452 | 827 | | _invoiceString = null; |
| 452 | 828 | | } |
| | 829 | |
|
| | 830 | | #endregion |
| | 831 | | } |