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