LN Address - db schema fix method (#3638)

* LN Address - db schema fix method

* pr changes

* shorten
This commit is contained in:
Andrew Camilleri
2022-04-19 09:58:31 +02:00
committed by GitHub
parent 7e6a2d08e2
commit 7652d2c7e3
15 changed files with 646 additions and 227 deletions

View File

@@ -61,6 +61,7 @@ namespace BTCPayServer.Data
public DbSet<WalletTransactionData> WalletTransactions { get; set; } public DbSet<WalletTransactionData> WalletTransactions { get; set; }
public DbSet<WebhookDeliveryData> WebhookDeliveries { get; set; } public DbSet<WebhookDeliveryData> WebhookDeliveries { get; set; }
public DbSet<WebhookData> Webhooks { get; set; } public DbSet<WebhookData> Webhooks { get; set; }
public DbSet<LightningAddressData> LightningAddresses{ get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ {
@@ -106,6 +107,7 @@ namespace BTCPayServer.Data
//WalletData.OnModelCreating(builder); //WalletData.OnModelCreating(builder);
WalletTransactionData.OnModelCreating(builder); WalletTransactionData.OnModelCreating(builder);
WebhookDeliveryData.OnModelCreating(builder); WebhookDeliveryData.OnModelCreating(builder);
LightningAddressData.OnModelCreating(builder);
//WebhookData.OnModelCreating(builder); //WebhookData.OnModelCreating(builder);

View File

@@ -0,0 +1,31 @@
using Microsoft.EntityFrameworkCore;
namespace BTCPayServer.Data;
public class LightningAddressData
{
public string Username { get; set; }
public string StoreDataId { get; set; }
public byte[] Blob { get; set; }
public StoreData Store { get; set; }
internal static void OnModelCreating(ModelBuilder builder)
{
builder.Entity<LightningAddressData>()
.HasOne(o => o.Store)
.WithMany(a => a.LightningAddresses)
.HasForeignKey(data => data.StoreDataId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<LightningAddressData>().HasKey(o => o.Username);
}
}
public class LightningAddressDataBlob
{
public string CurrencyCode { get; set; }
public decimal? Min { get; set; }
public decimal? Max { get; set; }
}

View File

@@ -41,5 +41,6 @@ namespace BTCPayServer.Data
public List<PairedSINData> PairedSINs { get; set; } public List<PairedSINData> PairedSINs { get; set; }
public IEnumerable<APIKeyData> APIKeys { get; set; } public IEnumerable<APIKeyData> APIKeys { get; set; }
public IEnumerable<LightningAddressData> LightningAddresses { get; set; }
} }
} }

View File

@@ -0,0 +1,51 @@
// <auto-generated />
using System;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace BTCPayServer.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20220414132313_AddLightningAddress")]
public partial class AddLightningAddress : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "LightningAddresses",
columns: table => new
{
Username = table.Column<string>(type: "TEXT", nullable: false),
StoreDataId = table.Column<string>(type: "TEXT", nullable: false),
Blob = table.Column<byte[]>( nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_LightningAddresses", x => x.Username);
table.ForeignKey(
name: "FK_LightningAddresses_Stores_StoreDataId",
column: x => x.StoreDataId,
principalTable: "Stores",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_LightningAddresses_StoreDataId",
table: "LightningAddresses",
column: "StoreDataId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "LightningAddresses");
}
}
}

View File

@@ -6,6 +6,8 @@ using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace BTCPayServer.Migrations namespace BTCPayServer.Migrations
{ {
[DbContext(typeof(ApplicationDbContext))] [DbContext(typeof(ApplicationDbContext))]
@@ -14,40 +16,7 @@ namespace BTCPayServer.Migrations
protected override void BuildModel(ModelBuilder modelBuilder) protected override void BuildModel(ModelBuilder modelBuilder)
{ {
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder modelBuilder.HasAnnotation("ProductVersion", "6.0.1");
.HasAnnotation("ProductVersion", "3.1.19");
modelBuilder.Entity("BTCPayServer.Data.APIKeyData", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT")
.HasMaxLength(50);
b.Property<byte[]>("Blob")
.HasColumnType("BLOB");
b.Property<string>("Label")
.HasColumnType("TEXT");
b.Property<string>("StoreId")
.HasColumnType("TEXT")
.HasMaxLength(50);
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<string>("UserId")
.HasColumnType("TEXT")
.HasMaxLength(50);
b.HasKey("Id");
b.HasIndex("StoreId");
b.HasIndex("UserId");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("BTCPayServer.Data.AddressInvoiceData", b => modelBuilder.Entity("BTCPayServer.Data.AddressInvoiceData", b =>
{ {
@@ -67,6 +36,38 @@ namespace BTCPayServer.Migrations
b.ToTable("AddressInvoices"); b.ToTable("AddressInvoices");
}); });
modelBuilder.Entity("BTCPayServer.Data.APIKeyData", b =>
{
b.Property<string>("Id")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<byte[]>("Blob")
.HasColumnType("BLOB");
b.Property<string>("Label")
.HasColumnType("TEXT");
b.Property<string>("StoreId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<string>("UserId")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("StoreId");
b.HasIndex("UserId");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("BTCPayServer.Data.AppData", b => modelBuilder.Entity("BTCPayServer.Data.AppData", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
@@ -119,8 +120,8 @@ namespace BTCPayServer.Migrations
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("Email") b.Property<string>("Email")
.HasColumnType("TEXT") .HasMaxLength(256)
.HasMaxLength(256); .HasColumnType("TEXT");
b.Property<bool>("EmailConfirmed") b.Property<bool>("EmailConfirmed")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@@ -132,12 +133,12 @@ namespace BTCPayServer.Migrations
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("NormalizedEmail") b.Property<string>("NormalizedEmail")
.HasColumnType("TEXT") .HasMaxLength(256)
.HasMaxLength(256); .HasColumnType("TEXT");
b.Property<string>("NormalizedUserName") b.Property<string>("NormalizedUserName")
.HasColumnType("TEXT") .HasMaxLength(256)
.HasMaxLength(256); .HasColumnType("TEXT");
b.Property<string>("PasswordHash") b.Property<string>("PasswordHash")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@@ -158,19 +159,19 @@ namespace BTCPayServer.Migrations
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<string>("UserName") b.Property<string>("UserName")
.HasColumnType("TEXT") .HasMaxLength(256)
.HasMaxLength(256); .HasColumnType("TEXT");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("NormalizedEmail") b.HasIndex("NormalizedEmail")
.HasName("EmailIndex"); .HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName") b.HasIndex("NormalizedUserName")
.IsUnique() .IsUnique()
.HasName("UserNameIndex"); .HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers"); b.ToTable("AspNetUsers", (string)null);
}); });
modelBuilder.Entity("BTCPayServer.Data.Fido2Credential", b => modelBuilder.Entity("BTCPayServer.Data.Fido2Credential", b =>
@@ -331,16 +332,35 @@ namespace BTCPayServer.Migrations
b.ToTable("InvoiceWebhookDeliveries"); b.ToTable("InvoiceWebhookDeliveries");
}); });
modelBuilder.Entity("BTCPayServer.Data.LightningAddressData", b =>
{
b.Property<string>("Username")
.HasColumnType("TEXT");
b.Property<byte[]>("Blob")
.HasColumnType("BLOB");
b.Property<string>("StoreDataId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Username");
b.HasIndex("StoreDataId");
b.ToTable("LightningAddresses");
});
modelBuilder.Entity("BTCPayServer.Data.NotificationData", b => modelBuilder.Entity("BTCPayServer.Data.NotificationData", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
.HasColumnType("TEXT") .HasMaxLength(36)
.HasMaxLength(36); .HasColumnType("TEXT");
b.Property<string>("ApplicationUserId") b.Property<string>("ApplicationUserId")
.IsRequired() .IsRequired()
.HasColumnType("TEXT") .HasMaxLength(50)
.HasMaxLength(50); .HasColumnType("TEXT");
b.Property<byte[]>("Blob") b.Property<byte[]>("Blob")
.HasColumnType("BLOB"); .HasColumnType("BLOB");
@@ -350,8 +370,8 @@ namespace BTCPayServer.Migrations
b.Property<string>("NotificationType") b.Property<string>("NotificationType")
.IsRequired() .IsRequired()
.HasColumnType("TEXT") .HasMaxLength(100)
.HasMaxLength(100); .HasColumnType("TEXT");
b.Property<bool>("Seen") b.Property<bool>("Seen")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@@ -366,8 +386,8 @@ namespace BTCPayServer.Migrations
modelBuilder.Entity("BTCPayServer.Data.OffchainTransactionData", b => modelBuilder.Entity("BTCPayServer.Data.OffchainTransactionData", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
.HasColumnType("TEXT") .HasMaxLength(64)
.HasMaxLength(64); .HasColumnType("TEXT");
b.Property<byte[]>("Blob") b.Property<byte[]>("Blob")
.HasColumnType("BLOB"); .HasColumnType("BLOB");
@@ -437,8 +457,8 @@ namespace BTCPayServer.Migrations
modelBuilder.Entity("BTCPayServer.Data.PayjoinLock", b => modelBuilder.Entity("BTCPayServer.Data.PayjoinLock", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
.HasColumnType("TEXT") .HasMaxLength(100)
.HasMaxLength(100); .HasColumnType("TEXT");
b.HasKey("Id"); b.HasKey("Id");
@@ -500,8 +520,8 @@ namespace BTCPayServer.Migrations
modelBuilder.Entity("BTCPayServer.Data.PayoutData", b => modelBuilder.Entity("BTCPayServer.Data.PayoutData", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
.HasColumnType("TEXT") .HasMaxLength(30)
.HasMaxLength(30); .HasColumnType("TEXT");
b.Property<byte[]>("Blob") b.Property<byte[]>("Blob")
.HasColumnType("BLOB"); .HasColumnType("BLOB");
@@ -514,8 +534,8 @@ namespace BTCPayServer.Migrations
b.Property<string>("PaymentMethodId") b.Property<string>("PaymentMethodId")
.IsRequired() .IsRequired()
.HasColumnType("TEXT") .HasMaxLength(20)
.HasMaxLength(20); .HasColumnType("TEXT");
b.Property<byte[]>("Proof") b.Property<byte[]>("Proof")
.HasColumnType("BLOB"); .HasColumnType("BLOB");
@@ -525,8 +545,8 @@ namespace BTCPayServer.Migrations
b.Property<string>("State") b.Property<string>("State")
.IsRequired() .IsRequired()
.HasColumnType("TEXT") .HasMaxLength(20)
.HasMaxLength(20); .HasColumnType("TEXT");
b.HasKey("Id"); b.HasKey("Id");
@@ -552,8 +572,8 @@ namespace BTCPayServer.Migrations
modelBuilder.Entity("BTCPayServer.Data.PlannedTransaction", b => modelBuilder.Entity("BTCPayServer.Data.PlannedTransaction", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
.HasColumnType("TEXT") .HasMaxLength(100)
.HasMaxLength(100); .HasColumnType("TEXT");
b.Property<byte[]>("Blob") b.Property<byte[]>("Blob")
.HasColumnType("BLOB"); .HasColumnType("BLOB");
@@ -569,8 +589,8 @@ namespace BTCPayServer.Migrations
modelBuilder.Entity("BTCPayServer.Data.PullPaymentData", b => modelBuilder.Entity("BTCPayServer.Data.PullPaymentData", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
.HasColumnType("TEXT") .HasMaxLength(30)
.HasMaxLength(30); .HasColumnType("TEXT");
b.Property<bool>("Archived") b.Property<bool>("Archived")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@@ -588,8 +608,8 @@ namespace BTCPayServer.Migrations
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("StoreId") b.Property<string>("StoreId")
.HasColumnType("TEXT") .HasMaxLength(50)
.HasMaxLength(50); .HasColumnType("TEXT");
b.HasKey("Id"); b.HasKey("Id");
@@ -604,8 +624,8 @@ namespace BTCPayServer.Migrations
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("PullPaymentDataId") b.Property<string>("PullPaymentDataId")
.HasColumnType("TEXT") .HasMaxLength(30)
.HasMaxLength(30); .HasColumnType("TEXT");
b.HasKey("InvoiceDataId", "PullPaymentDataId"); b.HasKey("InvoiceDataId", "PullPaymentDataId");
@@ -661,25 +681,6 @@ namespace BTCPayServer.Migrations
b.ToTable("Stores"); b.ToTable("Stores");
}); });
modelBuilder.Entity("BTCPayServer.Data.StoreWebhookData", b =>
{
b.Property<string>("StoreId")
.HasColumnType("TEXT");
b.Property<string>("WebhookId")
.HasColumnType("TEXT");
b.HasKey("StoreId", "WebhookId");
b.HasIndex("StoreId")
.IsUnique();
b.HasIndex("WebhookId")
.IsUnique();
b.ToTable("StoreWebhooks");
});
modelBuilder.Entity("BTCPayServer.Data.StoredFile", b => modelBuilder.Entity("BTCPayServer.Data.StoredFile", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
@@ -705,6 +706,25 @@ namespace BTCPayServer.Migrations
b.ToTable("Files"); b.ToTable("Files");
}); });
modelBuilder.Entity("BTCPayServer.Data.StoreWebhookData", b =>
{
b.Property<string>("StoreId")
.HasColumnType("TEXT");
b.Property<string>("WebhookId")
.HasColumnType("TEXT");
b.HasKey("StoreId", "WebhookId");
b.HasIndex("StoreId")
.IsUnique();
b.HasIndex("WebhookId")
.IsUnique();
b.ToTable("StoreWebhooks");
});
modelBuilder.Entity("BTCPayServer.Data.U2FDevice", b => modelBuilder.Entity("BTCPayServer.Data.U2FDevice", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
@@ -791,8 +811,8 @@ namespace BTCPayServer.Migrations
modelBuilder.Entity("BTCPayServer.Data.WebhookData", b => modelBuilder.Entity("BTCPayServer.Data.WebhookData", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
.HasColumnType("TEXT") .HasMaxLength(25)
.HasMaxLength(25); .HasColumnType("TEXT");
b.Property<byte[]>("Blob") b.Property<byte[]>("Blob")
.IsRequired() .IsRequired()
@@ -806,8 +826,8 @@ namespace BTCPayServer.Migrations
modelBuilder.Entity("BTCPayServer.Data.WebhookDeliveryData", b => modelBuilder.Entity("BTCPayServer.Data.WebhookDeliveryData", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
.HasColumnType("TEXT") .HasMaxLength(25)
.HasMaxLength(25); .HasColumnType("TEXT");
b.Property<byte[]>("Blob") b.Property<byte[]>("Blob")
.IsRequired() .IsRequired()
@@ -818,8 +838,8 @@ namespace BTCPayServer.Migrations
b.Property<string>("WebhookId") b.Property<string>("WebhookId")
.IsRequired() .IsRequired()
.HasColumnType("TEXT") .HasMaxLength(25)
.HasMaxLength(25); .HasColumnType("TEXT");
b.HasKey("Id"); b.HasKey("Id");
@@ -838,20 +858,20 @@ namespace BTCPayServer.Migrations
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("Name") b.Property<string>("Name")
.HasColumnType("TEXT") .HasMaxLength(256)
.HasMaxLength(256); .HasColumnType("TEXT");
b.Property<string>("NormalizedName") b.Property<string>("NormalizedName")
.HasColumnType("TEXT") .HasMaxLength(256)
.HasMaxLength(256); .HasColumnType("TEXT");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("NormalizedName") b.HasIndex("NormalizedName")
.IsUnique() .IsUnique()
.HasName("RoleNameIndex"); .HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles"); b.ToTable("AspNetRoles", (string)null);
}); });
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
@@ -874,7 +894,7 @@ namespace BTCPayServer.Migrations
b.HasIndex("RoleId"); b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims"); b.ToTable("AspNetRoleClaims", (string)null);
}); });
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
@@ -897,7 +917,7 @@ namespace BTCPayServer.Migrations
b.HasIndex("UserId"); b.HasIndex("UserId");
b.ToTable("AspNetUserClaims"); b.ToTable("AspNetUserClaims", (string)null);
}); });
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
@@ -919,7 +939,7 @@ namespace BTCPayServer.Migrations
b.HasIndex("UserId"); b.HasIndex("UserId");
b.ToTable("AspNetUserLogins"); b.ToTable("AspNetUserLogins", (string)null);
}); });
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
@@ -934,7 +954,7 @@ namespace BTCPayServer.Migrations
b.HasIndex("RoleId"); b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles"); b.ToTable("AspNetUserRoles", (string)null);
}); });
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
@@ -953,7 +973,17 @@ namespace BTCPayServer.Migrations
b.HasKey("UserId", "LoginProvider", "Name"); b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens"); b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("BTCPayServer.Data.AddressInvoiceData", b =>
{
b.HasOne("BTCPayServer.Data.InvoiceData", "InvoiceData")
.WithMany("AddressInvoices")
.HasForeignKey("InvoiceDataId")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("InvoiceData");
}); });
modelBuilder.Entity("BTCPayServer.Data.APIKeyData", b => modelBuilder.Entity("BTCPayServer.Data.APIKeyData", b =>
@@ -967,14 +997,10 @@ namespace BTCPayServer.Migrations
.WithMany("APIKeys") .WithMany("APIKeys")
.HasForeignKey("UserId") .HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("BTCPayServer.Data.AddressInvoiceData", b => b.Navigation("StoreData");
{
b.HasOne("BTCPayServer.Data.InvoiceData", "InvoiceData") b.Navigation("User");
.WithMany("AddressInvoices")
.HasForeignKey("InvoiceDataId")
.OnDelete(DeleteBehavior.Cascade);
}); });
modelBuilder.Entity("BTCPayServer.Data.AppData", b => modelBuilder.Entity("BTCPayServer.Data.AppData", b =>
@@ -983,6 +1009,8 @@ namespace BTCPayServer.Migrations
.WithMany("Apps") .WithMany("Apps")
.HasForeignKey("StoreDataId") .HasForeignKey("StoreDataId")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
b.Navigation("StoreData");
}); });
modelBuilder.Entity("BTCPayServer.Data.Fido2Credential", b => modelBuilder.Entity("BTCPayServer.Data.Fido2Credential", b =>
@@ -991,6 +1019,8 @@ namespace BTCPayServer.Migrations
.WithMany("Fido2Credentials") .WithMany("Fido2Credentials")
.HasForeignKey("ApplicationUserId") .HasForeignKey("ApplicationUserId")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
b.Navigation("ApplicationUser");
}); });
modelBuilder.Entity("BTCPayServer.Data.HistoricalAddressInvoiceData", b => modelBuilder.Entity("BTCPayServer.Data.HistoricalAddressInvoiceData", b =>
@@ -1000,6 +1030,8 @@ namespace BTCPayServer.Migrations
.HasForeignKey("InvoiceDataId") .HasForeignKey("InvoiceDataId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("InvoiceData");
}); });
modelBuilder.Entity("BTCPayServer.Data.InvoiceData", b => modelBuilder.Entity("BTCPayServer.Data.InvoiceData", b =>
@@ -1012,6 +1044,10 @@ namespace BTCPayServer.Migrations
b.HasOne("BTCPayServer.Data.RefundData", "CurrentRefund") b.HasOne("BTCPayServer.Data.RefundData", "CurrentRefund")
.WithMany() .WithMany()
.HasForeignKey("Id", "CurrentRefundId"); .HasForeignKey("Id", "CurrentRefundId");
b.Navigation("CurrentRefund");
b.Navigation("StoreData");
}); });
modelBuilder.Entity("BTCPayServer.Data.InvoiceEventData", b => modelBuilder.Entity("BTCPayServer.Data.InvoiceEventData", b =>
@@ -1021,6 +1057,8 @@ namespace BTCPayServer.Migrations
.HasForeignKey("InvoiceDataId") .HasForeignKey("InvoiceDataId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("InvoiceData");
}); });
modelBuilder.Entity("BTCPayServer.Data.InvoiceSearchData", b => modelBuilder.Entity("BTCPayServer.Data.InvoiceSearchData", b =>
@@ -1029,6 +1067,8 @@ namespace BTCPayServer.Migrations
.WithMany("InvoiceSearchData") .WithMany("InvoiceSearchData")
.HasForeignKey("InvoiceDataId") .HasForeignKey("InvoiceDataId")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
b.Navigation("InvoiceData");
}); });
modelBuilder.Entity("BTCPayServer.Data.InvoiceWebhookDeliveryData", b => modelBuilder.Entity("BTCPayServer.Data.InvoiceWebhookDeliveryData", b =>
@@ -1044,6 +1084,21 @@ namespace BTCPayServer.Migrations
.HasForeignKey("BTCPayServer.Data.InvoiceWebhookDeliveryData", "InvoiceId") .HasForeignKey("BTCPayServer.Data.InvoiceWebhookDeliveryData", "InvoiceId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("Delivery");
b.Navigation("Invoice");
});
modelBuilder.Entity("BTCPayServer.Data.LightningAddressData", b =>
{
b.HasOne("BTCPayServer.Data.StoreData", "Store")
.WithMany("LightningAddresses")
.HasForeignKey("StoreDataId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Store");
}); });
modelBuilder.Entity("BTCPayServer.Data.NotificationData", b => modelBuilder.Entity("BTCPayServer.Data.NotificationData", b =>
@@ -1053,6 +1108,8 @@ namespace BTCPayServer.Migrations
.HasForeignKey("ApplicationUserId") .HasForeignKey("ApplicationUserId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("ApplicationUser");
}); });
modelBuilder.Entity("BTCPayServer.Data.PairedSINData", b => modelBuilder.Entity("BTCPayServer.Data.PairedSINData", b =>
@@ -1061,6 +1118,8 @@ namespace BTCPayServer.Migrations
.WithMany("PairedSINs") .WithMany("PairedSINs")
.HasForeignKey("StoreDataId") .HasForeignKey("StoreDataId")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
b.Navigation("StoreData");
}); });
modelBuilder.Entity("BTCPayServer.Data.PaymentData", b => modelBuilder.Entity("BTCPayServer.Data.PaymentData", b =>
@@ -1069,6 +1128,8 @@ namespace BTCPayServer.Migrations
.WithMany("Payments") .WithMany("Payments")
.HasForeignKey("InvoiceDataId") .HasForeignKey("InvoiceDataId")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
b.Navigation("InvoiceData");
}); });
modelBuilder.Entity("BTCPayServer.Data.PaymentRequestData", b => modelBuilder.Entity("BTCPayServer.Data.PaymentRequestData", b =>
@@ -1077,6 +1138,8 @@ namespace BTCPayServer.Migrations
.WithMany("PaymentRequests") .WithMany("PaymentRequests")
.HasForeignKey("StoreDataId") .HasForeignKey("StoreDataId")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
b.Navigation("StoreData");
}); });
modelBuilder.Entity("BTCPayServer.Data.PayoutData", b => modelBuilder.Entity("BTCPayServer.Data.PayoutData", b =>
@@ -1085,6 +1148,8 @@ namespace BTCPayServer.Migrations
.WithMany("Payouts") .WithMany("Payouts")
.HasForeignKey("PullPaymentDataId") .HasForeignKey("PullPaymentDataId")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
b.Navigation("PullPaymentData");
}); });
modelBuilder.Entity("BTCPayServer.Data.PendingInvoiceData", b => modelBuilder.Entity("BTCPayServer.Data.PendingInvoiceData", b =>
@@ -1094,6 +1159,8 @@ namespace BTCPayServer.Migrations
.HasForeignKey("Id") .HasForeignKey("Id")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("InvoiceData");
}); });
modelBuilder.Entity("BTCPayServer.Data.PullPaymentData", b => modelBuilder.Entity("BTCPayServer.Data.PullPaymentData", b =>
@@ -1102,6 +1169,8 @@ namespace BTCPayServer.Migrations
.WithMany("PullPayments") .WithMany("PullPayments")
.HasForeignKey("StoreId") .HasForeignKey("StoreId")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
b.Navigation("StoreData");
}); });
modelBuilder.Entity("BTCPayServer.Data.RefundData", b => modelBuilder.Entity("BTCPayServer.Data.RefundData", b =>
@@ -1117,6 +1186,19 @@ namespace BTCPayServer.Migrations
.HasForeignKey("PullPaymentDataId") .HasForeignKey("PullPaymentDataId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("InvoiceData");
b.Navigation("PullPaymentData");
});
modelBuilder.Entity("BTCPayServer.Data.StoredFile", b =>
{
b.HasOne("BTCPayServer.Data.ApplicationUser", "ApplicationUser")
.WithMany("StoredFiles")
.HasForeignKey("ApplicationUserId");
b.Navigation("ApplicationUser");
}); });
modelBuilder.Entity("BTCPayServer.Data.StoreWebhookData", b => modelBuilder.Entity("BTCPayServer.Data.StoreWebhookData", b =>
@@ -1132,13 +1214,10 @@ namespace BTCPayServer.Migrations
.HasForeignKey("BTCPayServer.Data.StoreWebhookData", "WebhookId") .HasForeignKey("BTCPayServer.Data.StoreWebhookData", "WebhookId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
});
modelBuilder.Entity("BTCPayServer.Data.StoredFile", b => b.Navigation("Store");
{
b.HasOne("BTCPayServer.Data.ApplicationUser", "ApplicationUser") b.Navigation("Webhook");
.WithMany("StoredFiles")
.HasForeignKey("ApplicationUserId");
}); });
modelBuilder.Entity("BTCPayServer.Data.U2FDevice", b => modelBuilder.Entity("BTCPayServer.Data.U2FDevice", b =>
@@ -1147,6 +1226,8 @@ namespace BTCPayServer.Migrations
.WithMany("U2FDevices") .WithMany("U2FDevices")
.HasForeignKey("ApplicationUserId") .HasForeignKey("ApplicationUserId")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
b.Navigation("ApplicationUser");
}); });
modelBuilder.Entity("BTCPayServer.Data.UserStore", b => modelBuilder.Entity("BTCPayServer.Data.UserStore", b =>
@@ -1162,6 +1243,10 @@ namespace BTCPayServer.Migrations
.HasForeignKey("StoreDataId") .HasForeignKey("StoreDataId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("ApplicationUser");
b.Navigation("StoreData");
}); });
modelBuilder.Entity("BTCPayServer.Data.WalletTransactionData", b => modelBuilder.Entity("BTCPayServer.Data.WalletTransactionData", b =>
@@ -1171,6 +1256,8 @@ namespace BTCPayServer.Migrations
.HasForeignKey("WalletDataId") .HasForeignKey("WalletDataId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("WalletData");
}); });
modelBuilder.Entity("BTCPayServer.Data.WebhookDeliveryData", b => modelBuilder.Entity("BTCPayServer.Data.WebhookDeliveryData", b =>
@@ -1180,6 +1267,8 @@ namespace BTCPayServer.Migrations
.HasForeignKey("WebhookId") .HasForeignKey("WebhookId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("Webhook");
}); });
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
@@ -1218,7 +1307,7 @@ namespace BTCPayServer.Migrations
.IsRequired(); .IsRequired();
b.HasOne("BTCPayServer.Data.ApplicationUser", null) b.HasOne("BTCPayServer.Data.ApplicationUser", null)
.WithMany() .WithMany("UserRoles")
.HasForeignKey("UserId") .HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
@@ -1232,6 +1321,74 @@ namespace BTCPayServer.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
}); });
modelBuilder.Entity("BTCPayServer.Data.ApplicationUser", b =>
{
b.Navigation("APIKeys");
b.Navigation("Fido2Credentials");
b.Navigation("Notifications");
b.Navigation("StoredFiles");
b.Navigation("U2FDevices");
b.Navigation("UserRoles");
b.Navigation("UserStores");
});
modelBuilder.Entity("BTCPayServer.Data.InvoiceData", b =>
{
b.Navigation("AddressInvoices");
b.Navigation("Events");
b.Navigation("HistoricalAddressInvoices");
b.Navigation("InvoiceSearchData");
b.Navigation("Payments");
b.Navigation("PendingInvoices");
b.Navigation("Refunds");
});
modelBuilder.Entity("BTCPayServer.Data.PullPaymentData", b =>
{
b.Navigation("Payouts");
});
modelBuilder.Entity("BTCPayServer.Data.StoreData", b =>
{
b.Navigation("APIKeys");
b.Navigation("Apps");
b.Navigation("Invoices");
b.Navigation("LightningAddresses");
b.Navigation("PairedSINs");
b.Navigation("PaymentRequests");
b.Navigation("PullPayments");
b.Navigation("UserStores");
});
modelBuilder.Entity("BTCPayServer.Data.WalletData", b =>
{
b.Navigation("WalletTransactions");
});
modelBuilder.Entity("BTCPayServer.Data.WebhookData", b =>
{
b.Navigation("Deliveries");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

@@ -23,7 +23,7 @@
<PackageReference Include="Newtonsoft.Json.Schema" Version="3.0.14" /> <PackageReference Include="Newtonsoft.Json.Schema" Version="3.0.14" />
<PackageReference Include="Selenium.Support" Version="3.141.0" /> <PackageReference Include="Selenium.Support" Version="3.141.0" />
<PackageReference Include="Selenium.WebDriver" Version="3.141.0" /> <PackageReference Include="Selenium.WebDriver" Version="3.141.0" />
<PackageReference Include="Selenium.WebDriver.ChromeDriver" Version="98.0.4758.10200" /> <PackageReference Include="Selenium.WebDriver.ChromeDriver" Version="100.0.4896.6000" />
<PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3"> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>

View File

@@ -1713,11 +1713,6 @@ namespace BTCPayServer.Tests
s.FindAlertMessage(StatusMessageModel.StatusSeverity.Success); s.FindAlertMessage(StatusMessageModel.StatusSeverity.Success);
s.Driver.ToggleCollapse("AddAddress"); s.Driver.ToggleCollapse("AddAddress");
s.Driver.FindElement(By.Id("Add_Username")).SendKeys(lnaddress1);
s.Driver.FindElement(By.CssSelector("button[value='add']")).Click();
s.Driver.FindElement(By.ClassName("text-danger"));
s.Driver.FindElement(By.Id("Add_Username")).Clear();
var lnaddress2 = "EUR" + Guid.NewGuid().ToString(); var lnaddress2 = "EUR" + Guid.NewGuid().ToString();
s.Driver.FindElement(By.Id("Add_Username")).SendKeys(lnaddress2); s.Driver.FindElement(By.Id("Add_Username")).SendKeys(lnaddress2);

View File

@@ -0,0 +1,119 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
namespace BTCPayServer;
public class LightningAddressService
{
private readonly ApplicationDbContextFactory _applicationDbContextFactory;
private readonly IMemoryCache _memoryCache;
public LightningAddressService(ApplicationDbContextFactory applicationDbContextFactory, IMemoryCache memoryCache)
{
_applicationDbContextFactory = applicationDbContextFactory;
_memoryCache = memoryCache;
}
public async Task<List<LightningAddressData>> Get(LightningAddressQuery query)
{
await using var context = _applicationDbContextFactory.CreateContext();
return await GetCore(context, query);
}
private async Task<List<LightningAddressData>> GetCore(ApplicationDbContext context, LightningAddressQuery query)
{
IQueryable<LightningAddressData?> queryable = context.LightningAddresses.AsQueryable();
query.Usernames = query.Usernames?.Select(NormalizeUsername)?.ToArray();
if (query.Usernames is not null)
{
queryable = queryable.Where(data => query.Usernames.Contains(data.Username));
}
if (query.StoreIds is not null)
{
queryable = queryable.Where(data => query.StoreIds.Contains(data.StoreDataId));
}
return await queryable.ToListAsync();
}
public async Task<LightningAddressData?> ResolveByAddress(string username)
{
return await _memoryCache.GetOrCreateAsync(GetKey(username), async entry =>
{
var result = await Get(new LightningAddressQuery() {Usernames = new[] {username}});
return result.FirstOrDefault();
});
}
private string NormalizeUsername(string username)
{
return username.ToLowerInvariant();
}
public async Task<bool> Set(LightningAddressData data)
{
await using var context = _applicationDbContextFactory.CreateContext();
var result = (await GetCore(context, new LightningAddressQuery() {Usernames = new[] {data.Username}}))
.FirstOrDefault();
if (result is not null)
{
if (result.StoreDataId != data.StoreDataId)
{
return false;
}
context.Remove(result);
}
data.Username = NormalizeUsername(data.Username);
await context.AddAsync(data);
await context.SaveChangesAsync();
_memoryCache.Remove(GetKey(data.Username));
return true;
}
public async Task<bool> Remove(string username, string storeId = null)
{
await using var context = _applicationDbContextFactory.CreateContext();
var x = (await GetCore(context, new LightningAddressQuery() {Usernames = new[] {username}})).FirstOrDefault();
if (x is null) return true;
if (storeId is not null && x.StoreDataId != storeId)
{
return false;
}
context.Remove(x);
await context.SaveChangesAsync();
_memoryCache.Remove(GetKey(username));
return true;
}
public async Task Set(LightningAddressData data, ApplicationDbContext context)
{
var result = (await GetCore(context, new LightningAddressQuery() {Usernames = new[] {data.Username}}))
.FirstOrDefault();
if (result is not null)
{
if (result.StoreDataId != data.StoreDataId)
{
return;
}
context.Remove(result);
}
await context.AddAsync(data);
}
private string GetKey(string username)
{
username = NormalizeUsername(username);
return $"{nameof(LightningAddressService)}_{username}";
}
}

View File

@@ -1,3 +1,4 @@
#nullable enable
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
@@ -144,4 +145,11 @@ namespace BTCPayServer
return await context.Fido2Credentials.Where(fDevice => fDevice.ApplicationUserId == userId && fDevice.Type == Fido2Credential.CredentialType.LNURLAuth).AnyAsync(); return await context.Fido2Credentials.Where(fDevice => fDevice.ApplicationUserId == userId && fDevice.Type == Fido2Credential.CredentialType.LNURLAuth).AnyAsync();
} }
} }
public class LightningAddressQuery
{
public string[]? StoreIds { get; set; }
public string[]? Usernames { get; set; }
}
} }

View File

@@ -2,7 +2,6 @@ using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -18,7 +17,6 @@ using BTCPayServer.Lightning;
using BTCPayServer.Models.AppViewModels; using BTCPayServer.Models.AppViewModels;
using BTCPayServer.Payments; using BTCPayServer.Payments;
using BTCPayServer.Payments.Lightning; using BTCPayServer.Payments.Lightning;
using BTCPayServer.Services;
using BTCPayServer.Services.Apps; using BTCPayServer.Services.Apps;
using BTCPayServer.Services.Invoices; using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Rates; using BTCPayServer.Services.Rates;
@@ -26,7 +24,6 @@ using BTCPayServer.Services.Stores;
using LNURL; using LNURL;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing;
using NBitcoin; using NBitcoin;
using NBitcoin.Crypto; using NBitcoin.Crypto;
@@ -44,9 +41,10 @@ namespace BTCPayServer
private readonly LightningLikePaymentHandler _lightningLikePaymentHandler; private readonly LightningLikePaymentHandler _lightningLikePaymentHandler;
private readonly StoreRepository _storeRepository; private readonly StoreRepository _storeRepository;
private readonly AppService _appService; private readonly AppService _appService;
private readonly UIInvoiceController _invoiceController; private readonly UIInvoiceController _invoiceController;
private readonly SettingsRepository _settingsRepository;
private readonly LinkGenerator _linkGenerator; private readonly LinkGenerator _linkGenerator;
private readonly LightningAddressService _lightningAddressService;
public UILNURLController(InvoiceRepository invoiceRepository, public UILNURLController(InvoiceRepository invoiceRepository,
EventAggregator eventAggregator, EventAggregator eventAggregator,
@@ -55,8 +53,8 @@ namespace BTCPayServer
StoreRepository storeRepository, StoreRepository storeRepository,
AppService appService, AppService appService,
UIInvoiceController invoiceController, UIInvoiceController invoiceController,
SettingsRepository settingsRepository, LinkGenerator linkGenerator,
LinkGenerator linkGenerator) LightningAddressService lightningAddressService)
{ {
_invoiceRepository = invoiceRepository; _invoiceRepository = invoiceRepository;
_eventAggregator = eventAggregator; _eventAggregator = eventAggregator;
@@ -65,8 +63,8 @@ namespace BTCPayServer
_storeRepository = storeRepository; _storeRepository = storeRepository;
_appService = appService; _appService = appService;
_invoiceController = invoiceController; _invoiceController = invoiceController;
_settingsRepository = settingsRepository;
_linkGenerator = linkGenerator; _linkGenerator = linkGenerator;
_lightningAddressService = lightningAddressService;
} }
@@ -90,6 +88,7 @@ namespace BTCPayServer
{ {
return NotFound(); return NotFound();
} }
if (string.IsNullOrEmpty(itemCode)) if (string.IsNullOrEmpty(itemCode))
{ {
return NotFound(); return NotFound();
@@ -133,7 +132,7 @@ namespace BTCPayServer
} }
return await GetLNURL(cryptoCode, app.StoreDataId, currencyCode, null, null, return await GetLNURL(cryptoCode, app.StoreDataId, currencyCode, null, null,
() => (null, new List<string> { AppService.GetAppInternalTag(appId) }, item.Price.Value, true)); () => (null, new List<string> {AppService.GetAppInternalTag(appId)}, item.Price.Value, true));
} }
public class EditLightningAddressVM public class EditLightningAddressVM
@@ -146,7 +145,7 @@ namespace BTCPayServer
} }
public EditLightningAddressItem Add { get; set; } public EditLightningAddressItem Add { get; set; }
public List<EditLightningAddressItem> Items { get; set; } = new List<EditLightningAddressItem>(); public List<EditLightningAddressItem> Items { get; set; } = new();
} }
public class LightningAddressSettings public class LightningAddressSettings
@@ -154,8 +153,7 @@ namespace BTCPayServer
public class LightningAddressItem public class LightningAddressItem
{ {
public string StoreId { get; set; } public string StoreId { get; set; }
[Display(Name = "Invoice currency")] [Display(Name = "Invoice currency")] public string CurrencyCode { get; set; }
public string CurrencyCode { get; set; }
[Display(Name = "Min sats")] [Display(Name = "Min sats")]
[Range(1, double.PositiveInfinity)] [Range(1, double.PositiveInfinity)]
@@ -178,22 +176,18 @@ namespace BTCPayServer
} }
} }
private async Task<LightningAddressSettings> GetSettings()
{
return await _settingsRepository.GetSettingAsync<LightningAddressSettings>(nameof(LightningAddressSettings)) ??
new LightningAddressSettings();
}
[HttpGet("~/.well-known/lnurlp/{username}")] [HttpGet("~/.well-known/lnurlp/{username}")]
public async Task<IActionResult> ResolveLightningAddress(string username) public async Task<IActionResult> ResolveLightningAddress(string username)
{ {
var lightningAddressSettings = await GetSettings(); var lightningAddressSettings = await _lightningAddressService.ResolveByAddress(username);
if (!lightningAddressSettings.Items.TryGetValue(username.ToLowerInvariant(), out var item)) if (lightningAddressSettings is null)
{ {
return NotFound("Unknown username"); return NotFound("Unknown username");
} }
return await GetLNURL("BTC", item.StoreId, item.CurrencyCode, item.Min, item.Max, var blob = lightningAddressSettings.Blob.GetBlob<LightningAddressDataBlob>();
return await GetLNURL("BTC", lightningAddressSettings.StoreDataId, blob.CurrencyCode, blob.Min, blob.Max,
() => (username, null, null, true)); () => (username, null, null, true));
} }
@@ -250,7 +244,7 @@ namespace BTCPayServer
Amount = invoiceAmount, Amount = invoiceAmount,
Checkout = new InvoiceDataBase.CheckoutOptions Checkout = new InvoiceDataBase.CheckoutOptions
{ {
PaymentMethods = new[] { pmi.ToStringNormalized() }, PaymentMethods = new[] {pmi.ToStringNormalized()},
Expiration = blob.InvoiceExpiration < TimeSpan.FromMinutes(2) Expiration = blob.InvoiceExpiration < TimeSpan.FromMinutes(2)
? blob.InvoiceExpiration ? blob.InvoiceExpiration
: TimeSpan.FromMinutes(2) : TimeSpan.FromMinutes(2)
@@ -273,10 +267,10 @@ namespace BTCPayServer
await _invoiceRepository.UpdateInvoicePaymentMethod(i.Id, pm); await _invoiceRepository.UpdateInvoicePaymentMethod(i.Id, pm);
} }
lnurlMetadata.Add(new[] { "text/plain", i.Id }); lnurlMetadata.Add(new[] {"text/plain", i.Id});
if (!string.IsNullOrEmpty(username)) if (!string.IsNullOrEmpty(username))
{ {
lnurlMetadata.Add(new[] { "text/identifier", lnAddress }); lnurlMetadata.Add(new[] {"text/identifier", lnAddress});
} }
return Ok(new LNURLPayRequest return Ok(new LNURLPayRequest
@@ -292,7 +286,7 @@ namespace BTCPayServer
Callback = new Uri(_linkGenerator.GetUriByAction( Callback = new Uri(_linkGenerator.GetUriByAction(
action: nameof(GetLNURLForInvoice), action: nameof(GetLNURLForInvoice),
controller: "UILNURL", controller: "UILNURL",
values: new { cryptoCode, invoiceId = i.Id }, Request.Scheme, Request.Host, Request.PathBase)) values: new {cryptoCode, invoiceId = i.Id}, Request.Scheme, Request.Host, Request.PathBase))
}); });
} }
@@ -306,6 +300,7 @@ namespace BTCPayServer
{ {
return NotFound(); return NotFound();
} }
if (comment is not null) if (comment is not null)
comment = comment.Truncate(2000); comment = comment.Truncate(2000);
@@ -337,20 +332,16 @@ namespace BTCPayServer
List<string[]> lnurlMetadata = new List<string[]>(); List<string[]> lnurlMetadata = new List<string[]>();
lnurlMetadata.Add(new[] { "text/plain", i.Id }); lnurlMetadata.Add(new[] {"text/plain", i.Id});
if (!string.IsNullOrEmpty(paymentMethodDetails.ConsumedLightningAddress)) if (!string.IsNullOrEmpty(paymentMethodDetails.ConsumedLightningAddress))
{ {
lnurlMetadata.Add(new[] { "text/identifier", paymentMethodDetails.ConsumedLightningAddress }); lnurlMetadata.Add(new[] {"text/identifier", paymentMethodDetails.ConsumedLightningAddress});
} }
var metadata = JsonConvert.SerializeObject(lnurlMetadata); var metadata = JsonConvert.SerializeObject(lnurlMetadata);
if (amount.HasValue && (amount < min || amount > max)) if (amount.HasValue && (amount < min || amount > max))
{ {
return BadRequest(new LNUrlStatusResponse return BadRequest(new LNUrlStatusResponse {Status = "ERROR", Reason = "Amount is out of bounds."});
{
Status = "ERROR",
Reason = "Amount is out of bounds."
});
} }
if (amount.HasValue && string.IsNullOrEmpty(paymentMethodDetails.BOLT11) || if (amount.HasValue && string.IsNullOrEmpty(paymentMethodDetails.BOLT11) ||
@@ -379,7 +370,7 @@ namespace BTCPayServer
descriptionHash, descriptionHash,
i.ExpirationTime.ToUniversalTime() - DateTimeOffset.UtcNow)); i.ExpirationTime.ToUniversalTime() - DateTimeOffset.UtcNow));
if (!BOLT11PaymentRequest.Parse(invoice.BOLT11, network.NBitcoinNetwork) if (!BOLT11PaymentRequest.Parse(invoice.BOLT11, network.NBitcoinNetwork)
.VerifyDescriptionHash(metadata)) .VerifyDescriptionHash(metadata))
{ {
return BadRequest(new LNUrlStatusResponse return BadRequest(new LNUrlStatusResponse
{ {
@@ -413,9 +404,7 @@ namespace BTCPayServer
paymentMethodDetails, pmi)); paymentMethodDetails, pmi));
return Ok(new LNURLPayRequest.LNURLPayRequestCallbackResponse return Ok(new LNURLPayRequest.LNURLPayRequestCallbackResponse
{ {
Disposable = true, Disposable = true, Routes = Array.Empty<string>(), Pr = paymentMethodDetails.BOLT11
Routes = Array.Empty<string>(),
Pr = paymentMethodDetails.BOLT11
}); });
} }
@@ -430,9 +419,7 @@ namespace BTCPayServer
return Ok(new LNURLPayRequest.LNURLPayRequestCallbackResponse return Ok(new LNURLPayRequest.LNURLPayRequestCallbackResponse
{ {
Disposable = true, Disposable = true, Routes = Array.Empty<string>(), Pr = paymentMethodDetails.BOLT11
Routes = Array.Empty<string>(),
Pr = paymentMethodDetails.BOLT11
}); });
} }
@@ -452,8 +439,7 @@ namespace BTCPayServer
return BadRequest(new LNUrlStatusResponse return BadRequest(new LNUrlStatusResponse
{ {
Status = "ERROR", Status = "ERROR", Reason = "Invoice not in a valid payable state"
Reason = "Invoice not in a valid payable state"
}); });
} }
@@ -463,37 +449,39 @@ namespace BTCPayServer
[HttpGet("~/stores/{storeId}/integrations/lightning-address")] [HttpGet("~/stores/{storeId}/integrations/lightning-address")]
public async Task<IActionResult> EditLightningAddress(string storeId) public async Task<IActionResult> EditLightningAddress(string storeId)
{ {
if (ControllerContext.HttpContext.GetStoreData().GetEnabledPaymentIds(_btcPayNetworkProvider).All(id => id.PaymentType != LNURLPayPaymentType.Instance)) if (ControllerContext.HttpContext.GetStoreData().GetEnabledPaymentIds(_btcPayNetworkProvider)
.All(id => id.PaymentType != LNURLPayPaymentType.Instance))
{ {
TempData.SetStatusMessageModel(new StatusMessageModel TempData.SetStatusMessageModel(new StatusMessageModel
{ {
Message = "LNURL is required for lightning addresses but has not yet been enabled.", Message = "LNURL is required for lightning addresses but has not yet been enabled.",
Severity = StatusMessageModel.StatusSeverity.Error Severity = StatusMessageModel.StatusSeverity.Error
}); });
return RedirectToAction(nameof(UIStoresController.GeneralSettings), "UIStores", new { storeId }); return RedirectToAction(nameof(UIStoresController.GeneralSettings), "UIStores", new {storeId});
}
var lightningAddressSettings = await GetSettings();
if (lightningAddressSettings.StoreToItemMap.TryGetValue(storeId, out var addresses))
{
return View(new EditLightningAddressVM
{
Items = addresses.Select(s => new EditLightningAddressVM.EditLightningAddressItem
{
Max = lightningAddressSettings.Items[s].Max,
Min = lightningAddressSettings.Items[s].Min,
CurrencyCode = lightningAddressSettings.Items[s].CurrencyCode,
StoreId = lightningAddressSettings.Items[s].StoreId,
Username = s,
}).ToList()
});
} }
var addresses =
await _lightningAddressService.Get(new LightningAddressQuery() {StoreIds = new[] {storeId}});
return View(new EditLightningAddressVM return View(new EditLightningAddressVM
{ {
Items = new List<EditLightningAddressVM.EditLightningAddressItem>() Items = addresses.Select(s =>
{
var blob = s.Blob.GetBlob<LightningAddressDataBlob>();
return new EditLightningAddressVM.EditLightningAddressItem
{
Max = blob.Max,
Min = blob.Min,
CurrencyCode = blob.CurrencyCode,
StoreId = storeId,
Username = s.Username,
};
}
).ToList()
}); });
} }
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)] [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)] [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[HttpPost("~/stores/{storeId}/integrations/lightning-address")] [HttpPost("~/stores/{storeId}/integrations/lightning-address")]
@@ -502,69 +490,71 @@ namespace BTCPayServer
{ {
if (command == "add") if (command == "add")
{ {
if (!string.IsNullOrEmpty(vm.Add.CurrencyCode) && currencyNameTable.GetCurrencyData(vm.Add.CurrencyCode, false) is null) if (!string.IsNullOrEmpty(vm.Add.CurrencyCode) &&
currencyNameTable.GetCurrencyData(vm.Add.CurrencyCode, false) is null)
{ {
vm.AddModelError(addressVm => addressVm.Add.CurrencyCode, "Currency is invalid", this); vm.AddModelError(addressVm => addressVm.Add.CurrencyCode, "Currency is invalid", this);
} }
if (!ModelState.IsValid)
{
return View(vm);
}
var lightningAddressSettings = await GetSettings();
if (lightningAddressSettings.Items.ContainsKey(vm.Add.Username.ToLowerInvariant()))
{
vm.AddModelError(addressVm => addressVm.Add.Username, "Username is already taken", this);
}
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return View(vm); return View(vm);
} }
if (lightningAddressSettings.StoreToItemMap.TryGetValue(storeId, out var ids)) if (await _lightningAddressService.Set(new LightningAddressData()
{
StoreDataId = storeId,
Username = vm.Add.Username,
Blob = new LightningAddressDataBlob()
{
Max = vm.Add.Max, Min = vm.Add.Min, CurrencyCode = vm.Add.CurrencyCode
}.SerializeBlob()
}))
{ {
ids = ids.Concat(new[] { vm.Add.Username.ToLowerInvariant() }).ToArray(); TempData.SetStatusMessageModel(new StatusMessageModel
{
Severity = StatusMessageModel.StatusSeverity.Success,
Message = "Lightning address added successfully."
});
} }
else else
{ {
ids = new[] { vm.Add.Username.ToLowerInvariant() }; vm.AddModelError(addressVm => addressVm.Add.Username, "Username is already taken", this);
if (!ModelState.IsValid)
{
return View(vm);
}
} }
lightningAddressSettings.StoreToItemMap.AddOrReplace(storeId, ids);
vm.Add.StoreId = storeId;
lightningAddressSettings.Items.TryAdd(vm.Add.Username.ToLowerInvariant(), vm.Add);
await _settingsRepository.UpdateSetting(lightningAddressSettings, nameof(LightningAddressSettings));
TempData.SetStatusMessageModel(new StatusMessageModel
{
Severity = StatusMessageModel.StatusSeverity.Success,
Message = "Lightning address added successfully."
});
return RedirectToAction("EditLightningAddress"); return RedirectToAction("EditLightningAddress");
} }
if (command.StartsWith("remove", StringComparison.InvariantCultureIgnoreCase)) if (command.StartsWith("remove", StringComparison.InvariantCultureIgnoreCase))
{ {
var lightningAddressSettings = await GetSettings(); var index = command.Substring(command.IndexOf(":", StringComparison.InvariantCultureIgnoreCase) + 1);
var index = int.Parse( if (await _lightningAddressService.Remove(index, storeId))
command.Substring(command.IndexOf(":", StringComparison.InvariantCultureIgnoreCase) + 1),
CultureInfo.InvariantCulture);
if (lightningAddressSettings.StoreToItemMap.TryGetValue(storeId, out var addresses))
{ {
var addressToRemove = addresses[index];
addresses = addresses.Where(s => s != addressToRemove).ToArray();
lightningAddressSettings.StoreToItemMap.AddOrReplace(storeId, addresses);
lightningAddressSettings.Items.TryRemove(addressToRemove, out _);
await _settingsRepository.UpdateSetting(lightningAddressSettings, nameof(LightningAddressSettings));
TempData.SetStatusMessageModel(new StatusMessageModel TempData.SetStatusMessageModel(new StatusMessageModel
{ {
Severity = StatusMessageModel.StatusSeverity.Success, Severity = StatusMessageModel.StatusSeverity.Success,
Message = $"Lightning address {addressToRemove} removed successfully." Message = $"Lightning address {index} removed successfully."
}); });
return RedirectToAction("EditLightningAddress");
}
else
{
vm.AddModelError(addressVm => addressVm.Add.Username, "Username could not be removed", this);
if (!ModelState.IsValid)
{
return View(vm);
}
} }
} }
return View(vm);
return RedirectToAction("EditLightningAddress");
} }
} }
} }

View File

@@ -1,3 +1,4 @@
using System.Linq;
using NBXplorer; using NBXplorer;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@@ -7,20 +8,30 @@ namespace BTCPayServer.Data
{ {
public static APIKeyBlob GetBlob(this APIKeyData apiKeyData) public static APIKeyBlob GetBlob(this APIKeyData apiKeyData)
{ {
var result = apiKeyData.Blob == null return GetBlob<APIKeyBlob>(apiKeyData.Blob);
? new APIKeyBlob()
: JObject.Parse(ZipUtils.Unzip(apiKeyData.Blob)).ToObject<APIKeyBlob>();
return result;
} }
public static bool SetBlob(this APIKeyData apiKeyData, APIKeyBlob blob) public static bool SetBlob(this APIKeyData apiKeyData, APIKeyBlob blob)
{ {
var original = new Serializer(null).ToString(apiKeyData.GetBlob()); var newBlob = SerializeBlob(blob);
var newBlob = new Serializer(null).ToString(blob); if (apiKeyData?.Blob?.SequenceEqual(newBlob) is true)
if (original == newBlob)
return false; return false;
apiKeyData.Blob = ZipUtils.Zip(newBlob); apiKeyData.Blob = newBlob;
return true; return true;
} }
public static T GetBlob<T>(this byte[] data)
{
var result = data == null
? default
: JObject.Parse(ZipUtils.Unzip(data)).ToObject<T>();
return result;
}
public static byte[] SerializeBlob<T>(this T blob)
{
var newBlob = new Serializer(null).ToString(blob);
return ZipUtils.Zip(newBlob);
}
} }
} }

View File

@@ -40,6 +40,7 @@ namespace BTCPayServer.Hosting
private readonly AppService _appService; private readonly AppService _appService;
private readonly IEnumerable<IPayoutHandler> _payoutHandlers; private readonly IEnumerable<IPayoutHandler> _payoutHandlers;
private readonly BTCPayNetworkJsonSerializerSettings _btcPayNetworkJsonSerializerSettings; private readonly BTCPayNetworkJsonSerializerSettings _btcPayNetworkJsonSerializerSettings;
private readonly LightningAddressService _lightningAddressService;
private readonly UserManager<ApplicationUser> _userManager; private readonly UserManager<ApplicationUser> _userManager;
public IOptions<LightningNetworkOptions> LightningOptions { get; } public IOptions<LightningNetworkOptions> LightningOptions { get; }
@@ -54,6 +55,7 @@ namespace BTCPayServer.Hosting
AppService appService, AppService appService,
IEnumerable<IPayoutHandler> payoutHandlers, IEnumerable<IPayoutHandler> payoutHandlers,
BTCPayNetworkJsonSerializerSettings btcPayNetworkJsonSerializerSettings, BTCPayNetworkJsonSerializerSettings btcPayNetworkJsonSerializerSettings,
LightningAddressService lightningAddressService,
Logs logs) Logs logs)
{ {
Logs = logs; Logs = logs;
@@ -64,6 +66,7 @@ namespace BTCPayServer.Hosting
_appService = appService; _appService = appService;
_payoutHandlers = payoutHandlers; _payoutHandlers = payoutHandlers;
_btcPayNetworkJsonSerializerSettings = btcPayNetworkJsonSerializerSettings; _btcPayNetworkJsonSerializerSettings = btcPayNetworkJsonSerializerSettings;
_lightningAddressService = lightningAddressService;
_userManager = userManager; _userManager = userManager;
LightningOptions = lightningOptions; LightningOptions = lightningOptions;
} }
@@ -175,6 +178,12 @@ namespace BTCPayServer.Hosting
settings.LighingAddressSettingRename = true; settings.LighingAddressSettingRename = true;
await _Settings.UpdateSetting(settings); await _Settings.UpdateSetting(settings);
} }
if (!settings.LighingAddressDatabaseMigration)
{
await MigrateLighingAddressDatabaseMigration();
settings.LighingAddressDatabaseMigration = true;
await _Settings.UpdateSetting(settings);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -183,6 +192,49 @@ namespace BTCPayServer.Hosting
} }
} }
private async Task MigrateLighingAddressDatabaseMigration()
{
await using var ctx = _DBContextFactory.CreateContext();
var lightningAddressSettings =
await _Settings.GetSettingAsync<UILNURLController.LightningAddressSettings>(
nameof(UILNURLController.LightningAddressSettings));
if (lightningAddressSettings is null)
{
return;
}
var storeids = lightningAddressSettings.StoreToItemMap.Keys.ToArray();
var existingStores = (await ctx.Stores.Where(data => storeids.Contains(data.Id)).Select(data => data.Id ).ToArrayAsync()).ToHashSet();
foreach (var storeMap in lightningAddressSettings.StoreToItemMap)
{
if (!existingStores.Contains(storeMap.Key)) continue;
foreach (var storeitem in storeMap.Value)
{
if (lightningAddressSettings.Items.TryGetValue(storeitem, out var val))
{
await _lightningAddressService.Set(
new LightningAddressData()
{
StoreDataId = storeMap.Key,
Username = storeitem,
Blob = new LightningAddressDataBlob()
{
Max = val.Max,
Min = val.Min,
CurrencyCode = val.CurrencyCode
}.SerializeBlob()
}, ctx);
}
}
}
await ctx.SaveChangesAsync();
await _Settings.UpdateSetting<object>(null, nameof(UILNURLController.LightningAddressSettings));
}
private async Task MigrateLighingAddressSettingRename() private async Task MigrateLighingAddressSettingRename()
{ {
var old = await _Settings.GetSettingAsync<UILNURLController.LightningAddressSettings>("BTCPayServer.LNURLController+LightningAddressSettings"); var old = await _Settings.GetSettingAsync<UILNURLController.LightningAddressSettings>("BTCPayServer.LNURLController+LightningAddressSettings");

View File

@@ -113,6 +113,7 @@ namespace BTCPayServer.Hosting
services.AddScoped<Fido2Service>(); services.AddScoped<Fido2Service>();
services.AddSingleton<UserLoginCodeService>(); services.AddSingleton<UserLoginCodeService>();
services.AddSingleton<LnurlAuthService>(); services.AddSingleton<LnurlAuthService>();
services.AddSingleton<LightningAddressService>();
var mvcBuilder = services.AddMvc(o => var mvcBuilder = services.AddMvc(o =>
{ {
o.Filters.Add(new XFrameOptionsAttribute("DENY")); o.Filters.Add(new XFrameOptionsAttribute("DENY"));

View File

@@ -29,5 +29,6 @@ namespace BTCPayServer.Services
public bool MigratePayoutDestinationId { get; set; } public bool MigratePayoutDestinationId { get; set; }
public bool AddInitialUserBlob { get; set; } public bool AddInitialUserBlob { get; set; }
public bool LighingAddressSettingRename { get; set; } public bool LighingAddressSettingRename { get; set; }
public bool LighingAddressDatabaseMigration { get; set; }
} }
} }

View File

@@ -134,7 +134,7 @@
} }
</td> </td>
<td class="text-end"> <td class="text-end">
<button type="submit" title="Remove" name="command" value="@($"remove:{index}")" <button type="submit" title="Remove" name="command" value="@($"remove:{Model.Items[index].Username}")"
class="btn btn-link px-0 remove" data-bs-toggle="modal" data-bs-target="#ConfirmModal" data-description="The Lightning Address <strong>@address</strong> will be removed." data-confirm-input="REMOVE"> class="btn btn-link px-0 remove" data-bs-toggle="modal" data-bs-target="#ConfirmModal" data-description="The Lightning Address <strong>@address</strong> will be removed." data-confirm-input="REMOVE">
Remove Remove
</button> </button>