Merge pull request #7781 from NicolasDorier/cleanup-pre-1.12-migrations
What changed, and why it matters
This commit removes old database upgrade scripts (migrations) from before BTCPay Server version 1.12.0 and replaces them with a single consolidated starting schema. It also trims the startup migration task by deleting obsolete data-conversion helpers. The change is primarily a code-maintenance cleanup. It is not a security patch, but it does carry operational risk: if the consolidated schema does not exactly match what the removed migrations produced, fresh installs or restored databases could behave differently. Several tests that exercised the deleted migrations were also removed or rewritten.
Treat this as a high-risk maintenance change rather than a vulnerability fix. Before deploying, verify that 000.Init.sql produces a schema identical to running the deleted migrations on a fresh database, especially for PostgreSQL. Run integration tests on a fresh database and on a database that has already been migrated to the latest pre-1.12 state. Review the remaining MigrationStartupTask logic to ensure no runtime conversion paths are accidentally dropped for production data still on older formats. No immediate patching for a security flaw is indicated.
Security signals we found
Large-scale deletion of database migration history
Consolidation of cumulative schema into a single init SQL script
Removal of legacy data-migration logic from startup task
Removal of tests covering historical migrations
Dependency moved from runtime project to test project (YamlDotNet)
Evidence from the diff
The PR deletes 30+ EF Core migration classes dated 2020-2023 and folds their cumulative schema into BTCPayServer.Data/DBScripts/000.Init.sql. Tables such as PullPayments, Payouts, Refunds, Webhooks, WalletObjects, StoreRoles, Forms, LightningAddresses, CustodianAccount, Fido2Credentials, boltcards, etc. are now created directly by the init script. MigrationStartupTask.cs is refactored to a smaller primary constructor and many legacy migration helpers (ParsePOSYML, rate-source migration, app-type mapping fix, invoice/label/lightning derivation migrations) are removed. Tests that relied on those helpers were updated to use TestUtils.ParsePOSYML or were deleted. YamlDotNet is moved from the main project to the test project. The remaining migration class AddBoltcardsTable is converted to a DBScriptsMigration that references 000.Init.sql.
Changed components
BTCPayServer.Data/DBScripts/000.Init.sqlBTCPayServer.Data/Migrations/*BTCPayServer/Hosting/MigrationStartupTask.csBTCPayServer/Services/MigrationSettings.csBTCPayServer.Tests/*BTCPayServer/BTCPayServer.csprojBTCPayServer.Tests/BTCPayServer.Tests.csprojInspect captured patch +542 / −2752
### BTCPayServer.Data/DBScripts/000.Init.sql
@@ -1,3 +1,4 @@
+-- Consolidated schema and seed data through 20231020135844_AddBoltcardsTable.
CREATE TABLE "AddressInvoices" (
"Address" text NOT NULL,
"InvoiceDataId" text,
@@ -6,10 +7,11 @@ CREATE TABLE "AddressInvoices" (
CREATE TABLE "ApiKeys" (
"Id" character varying(50) NOT NULL,
"StoreId" character varying(50),
- "Permissions" text,
"Type" integer DEFAULT 0 NOT NULL,
"UserId" character varying(50),
- "Label" text
+ "Label" text,
+ "Blob" bytea,
+ "Blob2" jsonb
);
CREATE TABLE "Apps" (
"Id" text NOT NULL,
@@ -18,7 +20,8 @@ CREATE TABLE "Apps" (
"Name" text,
"Settings" text,
"StoreDataId" text,
- "TagAllInvoices" boolean DEFAULT false NOT NULL
+ "TagAllInvoices" boolean DEFAULT false NOT NULL,
+ "Archived" boolean DEFAULT false NOT NULL
);
CREATE TABLE "AspNetRoleClaims" (
"Id" integer NOT NULL,
@@ -70,7 +73,27 @@ CREATE TABLE "AspNetUsers" (
"SecurityStamp" text,
"TwoFactorEnabled" boolean NOT NULL,
"UserName" character varying(256),
- "RequiresEmailConfirmation" boolean DEFAULT false NOT NULL
+ "RequiresEmailConfirmation" boolean DEFAULT false NOT NULL,
+ "Created" timestamp with time zone,
+ "DisabledNotifications" text,
+ "Blob" bytea,
+ "Blob2" jsonb
+);
+CREATE TABLE "CustodianAccount" (
+ "Id" character varying(50) NOT NULL,
+ "StoreId" character varying(50) NOT NULL,
+ "CustodianCode" character varying(50) NOT NULL,
+ "Name" character varying(50),
+ "Blob" bytea,
+ "Blob2" jsonb
+);
+CREATE TABLE "Fido2Credentials" (
+ "Id" text NOT NULL,
+ "Name" text,
+ "ApplicationUserId" text,
+ "Blob" bytea,
+ "Type" integer NOT NULL,
+ "Blob2" jsonb
);
CREATE TABLE "Files" (
"Id" text NOT NULL,
@@ -79,18 +102,36 @@ CREATE TABLE "Files" (
"Timestamp" timestamp with time zone NOT NULL,
"ApplicationUserId" text
);
-CREATE TABLE "HistoricalAddressInvoices" (
- "InvoiceDataId" text NOT NULL,
- "Address" text NOT NULL,
- "Assigned" timestamp with time zone NOT NULL,
- "UnAssigned" timestamp with time zone,
- "CryptoCode" text
+CREATE TABLE "Forms" (
+ "Id" text NOT NULL,
+ "Name" text,
+ "StoreId" text,
+ "Config" jsonb,
+ "Public" boolean NOT NULL
);
CREATE TABLE "InvoiceEvents" (
"InvoiceDataId" text NOT NULL,
"UniqueId" text NOT NULL,
"Message" text,
- "Timestamp" timestamp with time zone NOT NULL
+ "Timestamp" timestamp with time zone NOT NULL,
+ "Severity" integer DEFAULT 0 NOT NULL
+);
+CREATE TABLE "InvoiceSearches" (
+ "Id" integer NOT NULL,
+ "InvoiceDataId" character varying(255),
+ "Value" text
+);
+CREATE SEQUENCE "InvoiceSearches_Id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ALTER SEQUENCE "InvoiceSearches_Id_seq" OWNED BY "InvoiceSearches"."Id";
+CREATE TABLE "InvoiceWebhookDeliveries" (
+ "InvoiceId" text NOT NULL,
+ "DeliveryId" text NOT NULL
);
CREATE TABLE "Invoices" (
"Id" text NOT NULL,
@@ -101,7 +142,29 @@ CREATE TABLE "Invoices" (
"ItemCode" text,
"OrderId" text,
"Status" text,
- "StoreDataId" text
+ "StoreDataId" text,
+ "Archived" boolean DEFAULT false NOT NULL,
+ "CurrentRefundId" text,
+ "Blob2" jsonb
+);
+CREATE TABLE "LightningAddresses" (
+ "Username" text NOT NULL,
+ "StoreDataId" text NOT NULL,
+ "Blob" bytea,
+ "Blob2" jsonb
+);
+CREATE TABLE "Notifications" (
+ "Id" character varying(36) NOT NULL,
+ "Created" timestamp with time zone NOT NULL,
+ "ApplicationUserId" character varying(50) NOT NULL,
+ "NotificationType" character varying(100) NOT NULL,
+ "Seen" boolean NOT NULL,
+ "Blob" bytea,
+ "Blob2" jsonb
+);
+CREATE TABLE "OffchainTransactions" (
+ "Id" character varying(64) NOT NULL,
+ "Blob" bytea
);
CREATE TABLE "PairedSINData" (
"Id" text NOT NULL,
@@ -120,30 +183,84 @@ CREATE TABLE "PairingCodes" (
"StoreDataId" text,
"TokenValue" text
);
+CREATE TABLE "PayjoinLocks" (
+ "Id" character varying(100) NOT NULL
+);
CREATE TABLE "PaymentRequests" (
"Id" text NOT NULL,
"StoreDataId" text,
"Status" integer NOT NULL,
"Blob" bytea,
- "Created" timestamp with time zone DEFAULT '1970-01-01 00:00:00+00'::timestamp with time zone NOT NULL
+ "Created" timestamp with time zone DEFAULT '1970-01-01 00:00:00+00'::timestamp with time zone NOT NULL,
+ "Archived" boolean DEFAULT false NOT NULL,
+ "Blob2" jsonb
);
CREATE TABLE "Payments" (
"Id" text NOT NULL,
"Blob" bytea,
"InvoiceDataId" text,
- "Accounted" boolean DEFAULT false NOT NULL
+ "Accounted" boolean DEFAULT false NOT NULL,
+ "Blob2" jsonb,
+ "Type" text
+);
+CREATE TABLE "PayoutProcessors" (
+ "Id" text NOT NULL,
+ "StoreId" text,
+ "PaymentMethod" text,
+ "Processor" text,
+ "Blob" bytea,
+ "Blob2" jsonb
+);
+CREATE TABLE "Payouts" (
+ "Id" character varying(30) NOT NULL,
+ "Date" timestamp with time zone NOT NULL,
+ "PullPaymentDataId" character varying(30),
+ "State" character varying(20) NOT NULL,
+ "PaymentMethodId" character varying(20) NOT NULL,
+ "Destination" text,
+ "Blob" bytea,
+ "Proof" bytea,
+ "StoreDataId" text
);
CREATE TABLE "PendingInvoices" (
"Id" text NOT NULL
);
-CREATE TABLE "RefundAddresses" (
- "Id" text NOT NULL,
- "Blob" bytea,
- "InvoiceDataId" text
+CREATE TABLE "PlannedTransactions" (
+ "Id" character varying(100) NOT NULL,
+ "BroadcastAt" timestamp with time zone NOT NULL,
+ "Blob" bytea
+);
+CREATE TABLE "PullPayments" (
+ "Id" character varying(30) NOT NULL,
+ "StoreId" character varying(50),
+ "Period" bigint,
+ "StartDate" timestamp with time zone NOT NULL,
+ "EndDate" timestamp with time zone,
+ "Archived" boolean NOT NULL,
+ "Blob" bytea
+);
+CREATE TABLE "Refunds" (
+ "InvoiceDataId" text NOT NULL,
+ "PullPaymentDataId" text NOT NULL
);
CREATE TABLE "Settings" (
"Id" text NOT NULL,
- "Value" text
+ "Value" jsonb
+);
+CREATE TABLE "StoreRoles" (
+ "Id" text NOT NULL,
+ "StoreDataId" text,
+ "Role" text NOT NULL,
+ "Permissions" text[] NOT NULL
+);
+CREATE TABLE "StoreSettings" (
+ "Name" text NOT NULL,
+ "StoreId" text NOT NULL,
+ "Value" jsonb
+);
+CREATE TABLE "StoreWebhooks" (
+ "StoreId" character varying(50) NOT NULL,
+ "WebhookId" character varying(25) NOT NULL
);
CREATE TABLE "Stores" (
"Id" text NOT NULL,
@@ -152,9 +269,10 @@ CREATE TABLE "Stores" (
"StoreCertificate" bytea,
"StoreName" text,
"StoreWebsite" text,
- "StoreBlob" bytea,
- "DerivationStrategies" text,
- "DefaultCrypto" text
+ "StoreBlob" jsonb,
+ "DerivationStrategies" jsonb,
+ "DefaultCrypto" text,
+ "Archived" boolean DEFAULT false NOT NULL
);
CREATE TABLE "U2FDevices" (
"Id" text NOT NULL,
@@ -170,6 +288,20 @@ CREATE TABLE "UserStore" (
"StoreDataId" text NOT NULL,
"Role" text
);
+CREATE TABLE "WalletObjectLinks" (
+ "WalletId" text NOT NULL,
+ "AType" text NOT NULL,
+ "AId" text NOT NULL,
+ "BType" text NOT NULL,
+ "BId" text NOT NULL,
+ "Data" jsonb
+);
+CREATE TABLE "WalletObjects" (
+ "WalletId" text NOT NULL,
+ "Type" text NOT NULL,
+ "Id" text NOT NULL,
+ "Data" jsonb
+);
CREATE TABLE "WalletTransactions" (
"WalletDataId" text NOT NULL,
"TransactionId" text NOT NULL,
@@ -180,6 +312,25 @@ CREATE TABLE "Wallets" (
"Id" text NOT NULL,
"Blob" bytea
);
+CREATE TABLE "WebhookDeliveries" (
+ "Id" text NOT NULL,
+ "WebhookId" text NOT NULL,
+ "Timestamp" timestamp with time zone NOT NULL,
+ "Pruned" boolean NOT NULL,
+ "Blob" jsonb NOT NULL
+);
+CREATE TABLE "Webhooks" (
+ "Id" character varying(25) NOT NULL,
+ "Blob" bytea NOT NULL,
+ "Blob2" jsonb
+);
+CREATE TABLE boltcards (
+ id character varying(32) NOT NULL,
+ counter integer DEFAULT 0 NOT NULL,
+ ppid character varying(30),
+ version integer DEFAULT 0 NOT NULL
+);
+ALTER TABLE ONLY "InvoiceSearches" ALTER COLUMN "Id" SET DEFAULT nextval('"InvoiceSearches_Id_seq"'::regclass);
ALTER TABLE ONLY "AddressInvoices"
ADD CONSTRAINT "PK_AddressInvoices" PRIMARY KEY ("Address");
ALTER TABLE ONLY "ApiKeys"
@@ -200,38 +351,78 @@ ALTER TABLE ONLY "AspNetUserTokens"
ADD CONSTRAINT "PK_AspNetUserTokens" PRIMARY KEY ("UserId", "LoginProvider", "Name");
ALTER TABLE ONLY "AspNetUsers"
ADD CONSTRAINT "PK_AspNetUsers" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "CustodianAccount"
+ ADD CONSTRAINT "PK_CustodianAccount" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "Fido2Credentials"
+ ADD CONSTRAINT "PK_Fido2Credentials" PRIMARY KEY ("Id");
ALTER TABLE ONLY "Files"
ADD CONSTRAINT "PK_Files" PRIMARY KEY ("Id");
-ALTER TABLE ONLY "HistoricalAddressInvoices"
- ADD CONSTRAINT "PK_HistoricalAddressInvoices" PRIMARY KEY ("InvoiceDataId", "Address");
+ALTER TABLE ONLY "Forms"
+ ADD CONSTRAINT "PK_Forms" PRIMARY KEY ("Id");
ALTER TABLE ONLY "InvoiceEvents"
ADD CONSTRAINT "PK_InvoiceEvents" PRIMARY KEY ("InvoiceDataId", "UniqueId");
+ALTER TABLE ONLY "InvoiceSearches"
+ ADD CONSTRAINT "PK_InvoiceSearches" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "InvoiceWebhookDeliveries"
+ ADD CONSTRAINT "PK_InvoiceWebhookDeliveries" PRIMARY KEY ("InvoiceId", "DeliveryId");
ALTER TABLE ONLY "Invoices"
ADD CONSTRAINT "PK_Invoices" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "LightningAddresses"
+ ADD CONSTRAINT "PK_LightningAddresses" PRIMARY KEY ("Username");
+ALTER TABLE ONLY "Notifications"
+ ADD CONSTRAINT "PK_Notifications" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "OffchainTransactions"
+ ADD CONSTRAINT "PK_OffchainTransactions" PRIMARY KEY ("Id");
ALTER TABLE ONLY "PairedSINData"
ADD CONSTRAINT "PK_PairedSINData" PRIMARY KEY ("Id");
ALTER TABLE ONLY "PairingCodes"
ADD CONSTRAINT "PK_PairingCodes" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "PayjoinLocks"
+ ADD CONSTRAINT "PK_PayjoinLocks" PRIMARY KEY ("Id");
ALTER TABLE ONLY "PaymentRequests"
ADD CONSTRAINT "PK_PaymentRequests" PRIMARY KEY ("Id");
ALTER TABLE ONLY "Payments"
ADD CONSTRAINT "PK_Payments" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "PayoutProcessors"
+ ADD CONSTRAINT "PK_PayoutProcessors" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "Payouts"
+ ADD CONSTRAINT "PK_Payouts" PRIMARY KEY ("Id");
ALTER TABLE ONLY "PendingInvoices"
ADD CONSTRAINT "PK_PendingInvoices" PRIMARY KEY ("Id");
-ALTER TABLE ONLY "RefundAddresses"
- ADD CONSTRAINT "PK_RefundAddresses" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "PlannedTransactions"
+ ADD CONSTRAINT "PK_PlannedTransactions" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "PullPayments"
+ ADD CONSTRAINT "PK_PullPayments" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "Refunds"
+ ADD CONSTRAINT "PK_Refunds" PRIMARY KEY ("InvoiceDataId", "PullPaymentDataId");
ALTER TABLE ONLY "Settings"
ADD CONSTRAINT "PK_Settings" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "StoreRoles"
+ ADD CONSTRAINT "PK_StoreRoles" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "StoreSettings"
+ ADD CONSTRAINT "PK_StoreSettings" PRIMARY KEY ("StoreId", "Name");
+ALTER TABLE ONLY "StoreWebhooks"
+ ADD CONSTRAINT "PK_StoreWebhooks" PRIMARY KEY ("StoreId", "WebhookId");
ALTER TABLE ONLY "Stores"
ADD CONSTRAINT "PK_Stores" PRIMARY KEY ("Id");
ALTER TABLE ONLY "U2FDevices"
ADD CONSTRAINT "PK_U2FDevices" PRIMARY KEY ("Id");
ALTER TABLE ONLY "UserStore"
ADD CONSTRAINT "PK_UserStore" PRIMARY KEY ("ApplicationUserId", "StoreDataId");
+ALTER TABLE ONLY "WalletObjectLinks"
+ ADD CONSTRAINT "PK_WalletObjectLinks" PRIMARY KEY ("WalletId", "AType", "AId", "BType", "BId");
+ALTER TABLE ONLY "WalletObjects"
+ ADD CONSTRAINT "PK_WalletObjects" PRIMARY KEY ("WalletId", "Type", "Id");
ALTER TABLE ONLY "WalletTransactions"
ADD CONSTRAINT "PK_WalletTransactions" PRIMARY KEY ("WalletDataId", "TransactionId");
ALTER TABLE ONLY "Wallets"
ADD CONSTRAINT "PK_Wallets" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "WebhookDeliveries"
+ ADD CONSTRAINT "PK_WebhookDeliveries" PRIMARY KEY ("Id");
+ALTER TABLE ONLY "Webhooks"
+ ADD CONSTRAINT "PK_Webhooks" PRIMARY KEY ("Id");
+ALTER TABLE ONLY boltcards
+ ADD CONSTRAINT "PK_id" PRIMARY KEY (id);
CREATE INDEX "EmailIndex" ON "AspNetUsers" USING btree ("NormalizedEmail");
CREATE INDEX "IX_AddressInvoices_InvoiceDataId" ON "AddressInvoices" USING btree ("InvoiceDataId");
CREATE INDEX "IX_ApiKeys_StoreId" ON "ApiKeys" USING btree ("StoreId");
@@ -241,16 +432,37 @@ CREATE INDEX "IX_AspNetRoleClaims_RoleId" ON "AspNetRoleClaims" USING btree ("Ro
CREATE INDEX "IX_AspNetUserClaims_UserId" ON "AspNetUserClaims" USING btree ("UserId");
CREATE INDEX "IX_AspNetUserLogins_UserId" ON "AspNetUserLogins" USING btree ("UserId");
CREATE INDEX "IX_AspNetUserRoles_RoleId" ON "AspNetUserRoles" USING btree ("RoleId");
+CREATE INDEX "IX_CustodianAccount_StoreId" ON "CustodianAccount" USING btree ("StoreId");
+CREATE INDEX "IX_Fido2Credentials_ApplicationUserId" ON "Fido2Credentials" USING btree ("ApplicationUserId");
CREATE INDEX "IX_Files_ApplicationUserId" ON "Files" USING btree ("ApplicationUserId");
+CREATE INDEX "IX_Forms_StoreId" ON "Forms" USING btree ("StoreId");
+CREATE INDEX "IX_InvoiceSearches_InvoiceDataId" ON "InvoiceSearches" USING btree ("InvoiceDataId");
+CREATE INDEX "IX_InvoiceSearches_Value" ON "InvoiceSearches" USING btree ("Value");
+CREATE INDEX "IX_Invoices_Created" ON "Invoices" USING btree ("Created");
+CREATE INDEX "IX_Invoices_Id_CurrentRefundId" ON "Invoices" USING btree ("Id", "CurrentRefundId");
+CREATE INDEX "IX_Invoices_OrderId" ON "Invoices" USING btree ("OrderId");
CREATE INDEX "IX_Invoices_StoreDataId" ON "Invoices" USING btree ("StoreDataId");
+CREATE INDEX "IX_LightningAddresses_StoreDataId" ON "LightningAddresses" USING btree ("StoreDataId");
+CREATE INDEX "IX_Notifications_ApplicationUserId" ON "Notifications" USING btree ("ApplicationUserId");
CREATE INDEX "IX_PairedSINData_SIN" ON "PairedSINData" USING btree ("SIN");
CREATE INDEX "IX_PairedSINData_StoreDataId" ON "PairedSINData" USING btree ("StoreDataId");
CREATE INDEX "IX_PaymentRequests_Status" ON "PaymentRequests" USING btree ("Status");
CREATE INDEX "IX_PaymentRequests_StoreDataId" ON "PaymentRequests" USING btree ("StoreDataId");
CREATE INDEX "IX_Payments_InvoiceDataId" ON "Payments" USING btree ("InvoiceDataId");
-CREATE INDEX "IX_RefundAddresses_InvoiceDataId" ON "RefundAddresses" USING btree ("InvoiceDataId");
+CREATE INDEX "IX_PayoutProcessors_StoreId" ON "PayoutProcessors" USING btree ("StoreId");
+CREATE INDEX "IX_Payouts_Destination_State" ON "Payouts" USING btree ("Destination", "State");
+CREATE INDEX "IX_Payouts_PullPaymentDataId" ON "Payouts" USING btree ("PullPaymentDataId");
+CREATE INDEX "IX_Payouts_State" ON "Payouts" USING btree ("State");
+CREATE INDEX "IX_Payouts_StoreDataId" ON "Payouts" USING btree ("StoreDataId");
+CREATE INDEX "IX_PullPayments_StoreId" ON "PullPayments" USING btree ("StoreId");
+CREATE INDEX "IX_Refunds_PullPaymentDataId" ON "Refunds" USING btree ("PullPaymentDataId");
+CREATE UNIQUE INDEX "IX_StoreRoles_StoreDataId_Role" ON "StoreRoles" USING btree ("StoreDataId", "Role");
CREATE INDEX "IX_U2FDevices_ApplicationUserId" ON "U2FDevices" USING btree ("ApplicationUserId");
CREATE INDEX "IX_UserStore_StoreDataId" ON "UserStore" USING btree ("StoreDataId");
+CREATE INDEX "IX_WalletObjectLinks_WalletId_BType_BId" ON "WalletObjectLinks" USING btree ("WalletId", "BType", "BId");
+CREATE INDEX "IX_WalletObjects_Type_Id" ON "WalletObjects" USING btree ("Type", "Id");
+CREATE INDEX "IX_WebhookDeliveries_Timestamp" ON "WebhookDeliveries" USING btree ("Timestamp") WHERE ("Pruned" IS FALSE);
+CREATE INDEX "IX_WebhookDeliveries_WebhookId" ON "WebhookDeliveries" USING btree ("WebhookId");
CREATE UNIQUE INDEX "RoleNameIndex" ON "AspNetRoles" USING btree ("NormalizedName");
CREATE UNIQUE INDEX "UserNameIndex" ON "AspNetUsers" USING btree ("NormalizedUserName");
ALTER TABLE ONLY "AddressInvoices"
@@ -273,29 +485,75 @@ ALTER TABLE ONLY "AspNetUserRoles"
ADD CONSTRAINT "FK_AspNetUserRoles_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE;
ALTER TABLE ONLY "AspNetUserTokens"
ADD CONSTRAINT "FK_AspNetUserTokens_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "CustodianAccount"
+ ADD CONSTRAINT "FK_CustodianAccount_Stores_StoreId" FOREIGN KEY ("StoreId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "Fido2Credentials"
+ ADD CONSTRAINT "FK_Fido2Credentials_AspNetUsers_ApplicationUserId" FOREIGN KEY ("ApplicationUserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE;
ALTER TABLE ONLY "Files"
ADD CONSTRAINT "FK_Files_AspNetUsers_ApplicationUserId" FOREIGN KEY ("ApplicationUserId") REFERENCES "AspNetUsers"("Id") ON DELETE RESTRICT;
-ALTER TABLE ONLY "HistoricalAddressInvoices"
- ADD CONSTRAINT "FK_HistoricalAddressInvoices_Invoices_InvoiceDataId" FOREIGN KEY ("InvoiceDataId") REFERENCES "Invoices"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "Forms"
+ ADD CONSTRAINT "FK_Forms_Stores_StoreId" FOREIGN KEY ("StoreId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
ALTER TABLE ONLY "InvoiceEvents"
ADD CONSTRAINT "FK_InvoiceEvents_Invoices_InvoiceDataId" FOREIGN KEY ("InvoiceDataId") REFERENCES "Invoices"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "InvoiceSearches"
+ ADD CONSTRAINT "FK_InvoiceSearches_Invoices_InvoiceDataId" FOREIGN KEY ("InvoiceDataId") REFERENCES "Invoices"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "InvoiceWebhookDeliveries"
+ ADD CONSTRAINT "FK_InvoiceWebhookDeliveries_Invoices_InvoiceId" FOREIGN KEY ("InvoiceId") REFERENCES "Invoices"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "InvoiceWebhookDeliveries"
+ ADD CONSTRAINT "FK_InvoiceWebhookDeliveries_WebhookDeliveries_DeliveryId" FOREIGN KEY ("DeliveryId") REFERENCES "WebhookDeliveries"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "Invoices"
+ ADD CONSTRAINT "FK_Invoices_Refunds_Id_CurrentRefundId" FOREIGN KEY ("Id", "CurrentRefundId") REFERENCES "Refunds"("InvoiceDataId", "PullPaymentDataId") ON DELETE RESTRICT;
ALTER TABLE ONLY "Invoices"
ADD CONSTRAINT "FK_Invoices_Stores_StoreDataId" FOREIGN KEY ("StoreDataId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "LightningAddresses"
+ ADD CONSTRAINT "FK_LightningAddresses_Stores_StoreDataId" FOREIGN KEY ("StoreDataId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "Notifications"
+ ADD CONSTRAINT "FK_Notifications_AspNetUsers_ApplicationUserId" FOREIGN KEY ("ApplicationUserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE;
ALTER TABLE ONLY "PairedSINData"
ADD CONSTRAINT "FK_PairedSINData_Stores_StoreDataId" FOREIGN KEY ("StoreDataId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
ALTER TABLE ONLY "PaymentRequests"
ADD CONSTRAINT "FK_PaymentRequests_Stores_StoreDataId" FOREIGN KEY ("StoreDataId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
ALTER TABLE ONLY "Payments"
ADD CONSTRAINT "FK_Payments_Invoices_InvoiceDataId" FOREIGN KEY ("InvoiceDataId") REFERENCES "Invoices"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "PayoutProcessors"
+ ADD CONSTRAINT "FK_PayoutProcessors_Stores_StoreId" FOREIGN KEY ("StoreId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "Payouts"
+ ADD CONSTRAINT "FK_Payouts_PullPayments_PullPaymentDataId" FOREIGN KEY ("PullPaymentDataId") REFERENCES "PullPayments"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "Payouts"
+ ADD CONSTRAINT "FK_Payouts_Stores_StoreDataId" FOREIGN KEY ("StoreDataId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
ALTER TABLE ONLY "PendingInvoices"
ADD CONSTRAINT "FK_PendingInvoices_Invoices_Id" FOREIGN KEY ("Id") REFERENCES "Invoices"("Id") ON DELETE CASCADE;
-ALTER TABLE ONLY "RefundAddresses"
- ADD CONSTRAINT "FK_RefundAddresses_Invoices_InvoiceDataId" FOREIGN KEY ("InvoiceDataId") REFERENCES "Invoices"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "PullPayments"
+ ADD CONSTRAINT "FK_PullPayments_Stores_StoreId" FOREIGN KEY ("StoreId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "Refunds"
+ ADD CONSTRAINT "FK_Refunds_Invoices_InvoiceDataId" FOREIGN KEY ("InvoiceDataId") REFERENCES "Invoices"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "Refunds"
+ ADD CONSTRAINT "FK_Refunds_PullPayments_PullPaymentDataId" FOREIGN KEY ("PullPaymentDataId") REFERENCES "PullPayments"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "StoreRoles"
+ ADD CONSTRAINT "FK_StoreRoles_Stores_StoreDataId" FOREIGN KEY ("StoreDataId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "StoreSettings"
+ ADD CONSTRAINT "FK_StoreSettings_Stores_StoreId" FOREIGN KEY ("StoreId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "StoreWebhooks"
+ ADD CONSTRAINT "FK_StoreWebhooks_Stores_StoreId" FOREIGN KEY ("StoreId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "StoreWebhooks"
+ ADD CONSTRAINT "FK_StoreWebhooks_Webhooks_WebhookId" FOREIGN KEY ("WebhookId") REFERENCES "Webhooks"("Id") ON DELETE CASCADE;
ALTER TABLE ONLY "U2FDevices"
- ADD CONSTRAINT "FK_U2FDevices_AspNetUsers_ApplicationUserId" FOREIGN KEY ("ApplicationUserId") REFERENCES "AspNetUsers"("Id") ON DELETE RESTRICT;
+ ADD CONSTRAINT "FK_U2FDevices_AspNetUsers_ApplicationUserId" FOREIGN KEY ("ApplicationUserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE;
ALTER TABLE ONLY "UserStore"
ADD CONSTRAINT "FK_UserStore_AspNetUsers_ApplicationUserId" FOREIGN KEY ("ApplicationUserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "UserStore"
+ ADD CONSTRAINT "FK_UserStore_StoreRoles_Role" FOREIGN KEY ("Role") REFERENCES "StoreRoles"("Id");
ALTER TABLE ONLY "UserStore"
ADD CONSTRAINT "FK_UserStore_Stores_StoreDataId" FOREIGN KEY ("StoreDataId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "WalletObjectLinks"
+ ADD CONSTRAINT "FK_WalletObjectLinks_WalletObjects_WalletId_AType_AId" FOREIGN KEY ("WalletId", "AType", "AId") REFERENCES "WalletObjects"("WalletId", "Type", "Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "WalletObjectLinks"
+ ADD CONSTRAINT "FK_WalletObjectLinks_WalletObjects_WalletId_BType_BId" FOREIGN KEY ("WalletId", "BType", "BId") REFERENCES "WalletObjects"("WalletId", "Type", "Id") ON DELETE CASCADE;
ALTER TABLE ONLY "WalletTransactions"
ADD CONSTRAINT "FK_WalletTransactions_Wallets_WalletDataId" FOREIGN KEY ("WalletDataId") REFERENCES "Wallets"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY "WebhookDeliveries"
+ ADD CONSTRAINT "FK_WebhookDeliveries_Webhooks_WebhookId" FOREIGN KEY ("WebhookId") REFERENCES "Webhooks"("Id") ON DELETE CASCADE;
+ALTER TABLE ONLY boltcards
+ ADD CONSTRAINT "FK_boltcards_PullPayments" FOREIGN KEY (ppid) REFERENCES "PullPayments"("Id") ON DELETE SET NULL;
+INSERT INTO "StoreRoles" ("Id", "StoreDataId", "Role", "Permissions") VALUES ('Owner', NULL, 'Owner', '{btcpay.store.canmodifystoresettings,btcpay.store.cantradecustodianaccount,btcpay.store.canwithdrawfromcustodianaccount,btcpay.store.candeposittocustodianaccount}');
+INSERT INTO "StoreRoles" ("Id", "StoreDataId", "Role", "Permissions") VALUES ('Guest', NULL, 'Guest', '{btcpay.store.canviewstoresettings,btcpay.store.canmodifyinvoices,btcpay.store.canviewcustodianaccounts,btcpay.store.candeposittocustodianaccount}');
### BTCPayServer.Data/Migrations/20200225133433_AddApiKeyLabel.cs
@@ -1,14 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20200225133433_AddApiKeyLabel")]
- [DBScript("000.Init.sql")]
- public partial class AddApiKeyLabel : DBScriptsMigration
- {
-
- }
-}
### BTCPayServer.Data/Migrations/20200402065615_AddApiKeyBlob.cs
@@ -1,36 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20200402065615_AddApiKeyBlob")]
- public partial class AddApiKeyBlob : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Permissions",
- table: "ApiKeys");
-
- migrationBuilder.AddColumn<byte[]>(
- name: "Blob",
- table: "ApiKeys",
- nullable: true);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Blob",
- table: "ApiKeys");
-
- migrationBuilder.AddColumn<string>(
- name: "Permissions",
- table: "ApiKeys",
- type: "TEXT",
- nullable: true);
- }
- }
-}
### BTCPayServer.Data/Migrations/20200413052418_PlannedTransactions.cs
@@ -1,59 +0,0 @@
-using System;
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20200413052418_PlannedTransactions")]
- public partial class PlannedTransactions : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "PlannedTransactions",
- columns: table => new
- {
- Id = table.Column<string>(maxLength: 100, nullable: false),
- BroadcastAt = table.Column<DateTimeOffset>(nullable: false),
- Blob = table.Column<byte[]>(nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_PlannedTransactions", x => x.Id);
- });
- migrationBuilder.CreateTable(
- name: "PayjoinLocks",
- columns: table => new
- {
- Id = table.Column<string>(maxLength: 100, nullable: false),
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_PayjoinLocks", x => x.Id);
- });
- migrationBuilder.CreateTable(
- name: "OffchainTransactions",
- columns: table => new
- {
- Id = table.Column<string>(maxLength: 64, nullable: false),
- Blob = table.Column<byte[]>(nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_OffchainTransactions", x => x.Id);
- });
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable(
- name: "PayjoinLocks");
- migrationBuilder.DropTable(
- name: "PlannedTransactions");
- migrationBuilder.DropTable(
- name: "OffchainTransactions");
- }
- }
-}
### BTCPayServer.Data/Migrations/20200507092343_AddArchivedToInvoice.cs
@@ -1,35 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20200507092343_AddArchivedToInvoice")]
- public class AddArchivedToInvoice : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<bool>(
- name: "Archived",
- table: "Invoices",
- nullable: false,
- defaultValue: false);
- migrationBuilder.AddColumn<bool>(
- name: "Archived",
- table: "PaymentRequests",
- nullable: false,
- defaultValue: false);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Archived",
- table: "Invoices");
- migrationBuilder.DropColumn(
- name: "Archived",
- table: "PaymentRequests");
- }
- }
-}
### BTCPayServer.Data/Migrations/20200625064111_refundnotificationpullpayments.cs
@@ -1,213 +0,0 @@
-using System;
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20200625064111_refundnotificationpullpayments")]
- public partial class refundnotificationpullpayments : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
-
- migrationBuilder.DropTable(
- name: "RefundAddresses");
-
- migrationBuilder.AddColumn<string>(
- name: "CurrentRefundId",
- table: "Invoices",
- nullable: true,
- maxLength: null);
-
- migrationBuilder.CreateTable(
- name: "Notifications",
- columns: table => new
- {
- Id = table.Column<string>(maxLength: 36, nullable: false),
- Created = table.Column<DateTimeOffset>(nullable: false),
- ApplicationUserId = table.Column<string>(maxLength: 50, nullable: false),
- NotificationType = table.Column<string>(maxLength: 100, nullable: false),
- Seen = table.Column<bool>(nullable: false),
- Blob = table.Column<byte[]>(nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_Notifications", x => x.Id);
- table.ForeignKey(
- name: "FK_Notifications_AspNetUsers_ApplicationUserId",
- column: x => x.ApplicationUserId,
- principalTable: "AspNetUsers",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateTable(
- name: "PullPayments",
- columns: table => new
- {
- Id = table.Column<string>(maxLength: 30, nullable: false),
- StoreId = table.Column<string>(maxLength: 50, nullable: true),
- Period = table.Column<long>(nullable: true),
- StartDate = table.Column<DateTimeOffset>(nullable: false),
- EndDate = table.Column<DateTimeOffset>(nullable: true),
- Archived = table.Column<bool>(nullable: false),
- Blob = table.Column<byte[]>(nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_PullPayments", x => x.Id);
- table.ForeignKey(
- name: "FK_PullPayments_Stores_StoreId",
- column: x => x.StoreId,
- principalTable: "Stores",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateTable(
- name: "Payouts",
- columns: table => new
- {
- Id = table.Column<string>(maxLength: 30, nullable: false),
- Date = table.Column<DateTimeOffset>(nullable: false),
- PullPaymentDataId = table.Column<string>(maxLength: 30, nullable: true),
- State = table.Column<string>(maxLength: 20, nullable: false),
- PaymentMethodId = table.Column<string>(maxLength: 20, nullable: false),
- Destination = table.Column<string>(maxLength: null, nullable: true),
- Blob = table.Column<byte[]>(nullable: true),
- Proof = table.Column<byte[]>(nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_Payouts", x => x.Id);
- table.ForeignKey(
- name: "FK_Payouts_PullPayments_PullPaymentDataId",
- column: x => x.PullPaymentDataId,
- principalTable: "PullPayments",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateTable(
- name: "Refunds",
- columns: table => new
- {
- InvoiceDataId = table.Column<string>(maxLength: null, nullable: false),
- PullPaymentDataId = table.Column<string>(maxLength: null, nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_Refunds", x => new { x.InvoiceDataId, x.PullPaymentDataId });
- table.ForeignKey(
- name: "FK_Refunds_Invoices_InvoiceDataId",
- column: x => x.InvoiceDataId,
- principalTable: "Invoices",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- table.ForeignKey(
- name: "FK_Refunds_PullPayments_PullPaymentDataId",
- column: x => x.PullPaymentDataId,
- principalTable: "PullPayments",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateIndex(
- name: "IX_Invoices_Id_CurrentRefundId",
- table: "Invoices",
- columns: new[] { "Id", "CurrentRefundId" });
-
- migrationBuilder.CreateIndex(
- name: "IX_Notifications_ApplicationUserId",
- table: "Notifications",
- column: "ApplicationUserId");
-
- migrationBuilder.CreateIndex(
- name: "IX_Payouts_Destination",
- table: "Payouts",
- column: "Destination",
- unique: true);
-
- migrationBuilder.CreateIndex(
- name: "IX_Payouts_PullPaymentDataId",
- table: "Payouts",
- column: "PullPaymentDataId");
-
- migrationBuilder.CreateIndex(
- name: "IX_Payouts_State",
- table: "Payouts",
- column: "State");
-
- migrationBuilder.CreateIndex(
- name: "IX_PullPayments_StoreId",
- table: "PullPayments",
- column: "StoreId");
-
- migrationBuilder.CreateIndex(
- name: "IX_Refunds_PullPaymentDataId",
- table: "Refunds",
- column: "PullPaymentDataId");
-
- migrationBuilder.AddForeignKey(
- name: "FK_Invoices_Refunds_Id_CurrentRefundId",
- table: "Invoices",
- columns: new[] { "Id", "CurrentRefundId" },
- principalTable: "Refunds",
- principalColumns: new[] { "InvoiceDataId", "PullPaymentDataId" },
- onDelete: ReferentialAction.Restrict);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropForeignKey(
- name: "FK_Invoices_Refunds_Id_CurrentRefundId",
- table: "Invoices");
-
- migrationBuilder.DropTable(
- name: "Notifications");
-
- migrationBuilder.DropTable(
- name: "Payouts");
-
- migrationBuilder.DropTable(
- name: "Refunds");
-
- migrationBuilder.DropTable(
- name: "PullPayments");
-
- migrationBuilder.DropIndex(
- name: "IX_Invoices_Id_CurrentRefundId",
- table: "Invoices");
-
- migrationBuilder.DropColumn(
- name: "CurrentRefundId",
- table: "Invoices");
-
- migrationBuilder.CreateTable(
- name: "RefundAddresses",
- columns: table => new
- {
- Id = table.Column<string>(type: "TEXT", nullable: false),
- Blob = table.Column<byte[]>(type: "BLOB", nullable: true),
- InvoiceDataId = table.Column<string>(type: "TEXT", nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_RefundAddresses", x => x.Id);
- table.ForeignKey(
- name: "FK_RefundAddresses_Invoices_InvoiceDataId",
- column: x => x.InvoiceDataId,
- principalTable: "Invoices",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateIndex(
- name: "IX_RefundAddresses_InvoiceDataId",
- table: "RefundAddresses",
- column: "InvoiceDataId");
- }
- }
-}
### BTCPayServer.Data/Migrations/20200901161733_AddInvoiceEventLogSeverity.cs
@@ -1,28 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
-
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20200901161733_AddInvoiceEventLogSeverity")]
- public partial class AddInvoiceEventLogSeverity : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<int>(
- name: "Severity",
- table: "InvoiceEvents",
- nullable: false,
- defaultValue: 0);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Severity",
- table: "InvoiceEvents");
- }
- }
-}
### BTCPayServer.Data/Migrations/20201002145033_AddCreateDateToUser.cs
@@ -1,27 +0,0 @@
-using System;
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20201002145033_AddCreateDateToUser")]
- public partial class AddCreateDateToUser : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<DateTimeOffset>(
- name: "Created",
- table: "AspNetUsers",
- nullable: true);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Created",
- table: "AspNetUsers");
- }
- }
-}
### BTCPayServer.Data/Migrations/20201007090617_u2fDeviceCascade.cs
@@ -1,41 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20201007090617_u2fDeviceCascade")]
- public partial class u2fDeviceCascade : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropForeignKey(
- name: "FK_U2FDevices_AspNetUsers_ApplicationUserId",
- table: "U2FDevices");
-
- migrationBuilder.AddForeignKey(
- name: "FK_U2FDevices_AspNetUsers_ApplicationUserId",
- table: "U2FDevices",
- column: "ApplicationUserId",
- principalTable: "AspNetUsers",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropForeignKey(
- name: "FK_U2FDevices_AspNetUsers_ApplicationUserId",
- table: "U2FDevices");
-
- migrationBuilder.AddForeignKey(
- name: "FK_U2FDevices_AspNetUsers_ApplicationUserId",
- table: "U2FDevices",
- column: "ApplicationUserId",
- principalTable: "AspNetUsers",
- principalColumn: "Id",
- onDelete: ReferentialAction.Restrict);
- }
- }
-}
### BTCPayServer.Data/Migrations/20201015151438_AddDisabledNotificationsToUser.cs
@@ -1,26 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20201015151438_AddDisabledNotificationsToUser")]
- public partial class AddDisabledNotificationsToUser : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<string>(
- name: "DisabledNotifications",
- table: "AspNetUsers",
- nullable: true);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "DisabledNotifications",
- table: "AspNetUsers");
- }
- }
-}
### BTCPayServer.Data/Migrations/20201108054749_webhooks.cs
@@ -1,115 +0,0 @@
-using System;
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20201108054749_webhooks")]
- public partial class webhooks : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "Webhooks",
- columns: table => new
- {
- Id = table.Column<string>(maxLength: 25, nullable: false),
- Blob = table.Column<byte[]>(nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_Webhooks", x => x.Id);
- });
-
- migrationBuilder.CreateTable(
- name: "StoreWebhooks",
- columns: table => new
- {
- StoreId = table.Column<string>(maxLength: 50, nullable: false),
- WebhookId = table.Column<string>(maxLength: 25, nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_StoreWebhooks", x => new { x.StoreId, x.WebhookId });
- table.ForeignKey(
- name: "FK_StoreWebhooks_Stores_StoreId",
- column: x => x.StoreId,
- principalTable: "Stores",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- table.ForeignKey(
- name: "FK_StoreWebhooks_Webhooks_WebhookId",
- column: x => x.WebhookId,
- principalTable: "Webhooks",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateTable(
- name: "WebhookDeliveries",
- columns: table => new
- {
- Id = table.Column<string>(maxLength: 25, nullable: false),
- WebhookId = table.Column<string>(maxLength: 25, nullable: false),
- Timestamp = table.Column<DateTimeOffset>(nullable: false),
- Blob = table.Column<byte[]>(nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_WebhookDeliveries", x => x.Id);
- table.ForeignKey(
- name: "FK_WebhookDeliveries_Webhooks_WebhookId",
- column: x => x.WebhookId,
- principalTable: "Webhooks",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateTable(
- name: "InvoiceWebhookDeliveries",
- columns: table => new
- {
- InvoiceId = table.Column<string>(maxLength: 255, nullable: false),
- DeliveryId = table.Column<string>(maxLength: 100, nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_InvoiceWebhookDeliveries", x => new { x.InvoiceId, x.DeliveryId });
- table.ForeignKey(
- name: "FK_InvoiceWebhookDeliveries_WebhookDeliveries_DeliveryId",
- column: x => x.DeliveryId,
- principalTable: "WebhookDeliveries",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- table.ForeignKey(
- name: "FK_InvoiceWebhookDeliveries_Invoices_InvoiceId",
- column: x => x.InvoiceId,
- principalTable: "Invoices",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateIndex(
- name: "IX_WebhookDeliveries_WebhookId",
- table: "WebhookDeliveries",
- column: "WebhookId");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable(
- name: "InvoiceWebhookDeliveries");
-
- migrationBuilder.DropTable(
- name: "StoreWebhooks");
-
- migrationBuilder.DropTable(
- name: "WebhookDeliveries");
-
- migrationBuilder.DropTable(
- name: "Webhooks");
- }
- }
-}
### BTCPayServer.Data/Migrations/20201208054211_invoicesorderindex.cs
@@ -1,33 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20201208054211_invoicesorderindex")]
- public partial class invoicesorderindex : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AlterColumn<string>(
- name: "OrderId",
- table: "Invoices",
- maxLength: 100,
- nullable: true,
- oldClrType: typeof(string));
-
- migrationBuilder.CreateIndex(
- name: "IX_Invoices_OrderId",
- table: "Invoices",
- column: "OrderId");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropIndex(
- name: "IX_Invoices_OrderId",
- table: "Invoices");
- }
- }
-}
### BTCPayServer.Data/Migrations/20201228225040_AddingInvoiceSearchesTable.cs
@@ -1,55 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20201228225040_AddingInvoiceSearchesTable")]
- public partial class AddingInvoiceSearchesTable : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "InvoiceSearches",
- columns: table => new
- {
- Id = table.Column<int>(nullable: false)
- // manually added
- .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
- .Annotation("MySql:ValueGeneratedOnAdd", true)
- .Annotation("Sqlite:Autoincrement", true),
- // eof manually added
- InvoiceDataId = table.Column<string>(maxLength: 255, nullable: true),
- Value = table.Column<string>(maxLength: 512, nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_InvoiceSearches", x => x.Id);
- table.ForeignKey(
- name: "FK_InvoiceSearches_Invoices_InvoiceDataId",
- column: x => x.InvoiceDataId,
- principalTable: "Invoices",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateIndex(
- name: "IX_InvoiceSearches_InvoiceDataId",
- table: "InvoiceSearches",
- column: "InvoiceDataId");
-
- migrationBuilder.CreateIndex(
- name: "IX_InvoiceSearches_Value",
- table: "InvoiceSearches",
- column: "Value");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable(
- name: "InvoiceSearches");
- }
- }
-}
### BTCPayServer.Data/Migrations/20210314092253_Fido2Credentials.cs
@@ -1,47 +0,0 @@
-using System;
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20210314092253_Fido2Credentials")]
- public partial class Fido2Credentials : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "Fido2Credentials",
- columns: table => new
- {
- Id = table.Column<string>(nullable: false, maxLength: null),
- Name = table.Column<string>(nullable: true),
- ApplicationUserId = table.Column<string>(nullable: true, maxLength: null),
- Blob = table.Column<byte[]>(nullable: true),
- Type = table.Column<int>(nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_Fido2Credentials", x => x.Id);
- table.ForeignKey(
- name: "FK_Fido2Credentials_AspNetUsers_ApplicationUserId",
- column: x => x.ApplicationUserId,
- principalTable: "AspNetUsers",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateIndex(
- name: "IX_Fido2Credentials_ApplicationUserId",
- table: "Fido2Credentials",
- column: "ApplicationUserId");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable(
- name: "Fido2Credentials");
- }
- }
-}
### BTCPayServer.Data/Migrations/20211021085011_RemovePayoutDestinationConstraint.cs
@@ -1,41 +0,0 @@
-// <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;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20211021085011_RemovePayoutDestinationConstraint")]
- public partial class RemovePayoutDestinationConstraint : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropIndex(
- name: "IX_Payouts_Destination",
- table: "Payouts");
-
- migrationBuilder.CreateIndex(
- name: "IX_Payouts_Destination_State",
- table: "Payouts",
- columns: new[] { "Destination", "State" });
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropIndex(
- name: "IX_Payouts_Destination_State",
- table: "Payouts");
-
- migrationBuilder.CreateIndex(
- name: "IX_Payouts_Destination",
- table: "Payouts",
- column: "Destination",
- unique: true);
- }
- }
-}
### BTCPayServer.Data/Migrations/20211125081400_AddUserBlob.cs
@@ -1,29 +0,0 @@
-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;
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20211125081400_AddUserBlob")]
- public partial class AddUserBlob : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<byte[]>(
- name: "Blob",
- table: "AspNetUsers",
- nullable: true);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Blob",
- table: "AspNetUsers");
- }
- }
-}
### BTCPayServer.Data/Migrations/20220115184620_AddCustodianAccountData.cs
@@ -1,50 +0,0 @@
-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;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20220115184620_AddCustodianAccountData")]
- public partial class AddCustodianAccountData : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "CustodianAccount",
- columns: table => new
- {
- Id = table.Column<string>(maxLength: 50, nullable: false),
- StoreId = table.Column<string>(maxLength: 50, nullable: false),
- CustodianCode = table.Column<string>(maxLength: 50, nullable: false),
- Name = table.Column<string>(maxLength: 50, nullable: true),
- Blob = table.Column<byte[]>(nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_CustodianAccount", x => x.Id);
- table.ForeignKey(
- name: "FK_CustodianAccount_Stores_StoreId",
- column: x => x.StoreId,
- principalTable: "Stores",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateIndex(
- name: "IX_CustodianAccount_StoreId",
- table: "CustodianAccount",
- column: "StoreId");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable(
- name: "CustodianAccount");
- }
- }
-}
### BTCPayServer.Data/Migrations/20220311135252_AddPayoutProcessors.cs
@@ -1,83 +0,0 @@
-// <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("20220311135252_AddPayoutProcessors")]
- public partial class AddPayoutProcessors : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<string>(
- name: "StoreDataId",
- table: "Payouts",
- nullable: true,
- maxLength: null);
-
- migrationBuilder.CreateTable(
- name: "PayoutProcessors",
- columns: table => new
- {
- Id = table.Column<string>(nullable: false, maxLength: null),
- StoreId = table.Column<string>(nullable: true, maxLength: null),
- PaymentMethod = table.Column<string>(nullable: true),
- Processor = table.Column<string>(nullable: true),
- Blob = table.Column<byte[]>(nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_PayoutProcessors", x => x.Id);
- table.ForeignKey(
- name: "FK_PayoutProcessors_Stores_StoreId",
- column: x => x.StoreId,
- principalTable: "Stores",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateIndex(
- name: "IX_Payouts_StoreDataId",
- table: "Payouts",
- column: "StoreDataId");
-
- migrationBuilder.CreateIndex(
- name: "IX_PayoutProcessors_StoreId",
- table: "PayoutProcessors",
- column: "StoreId");
-
- migrationBuilder.AddForeignKey(
- name: "FK_Payouts_Stores_StoreDataId",
- table: "Payouts",
- column: "StoreDataId",
- principalTable: "Stores",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropForeignKey(
- name: "FK_Payouts_Stores_StoreDataId",
- table: "Payouts");
-
- migrationBuilder.DropTable(
- name: "PayoutProcessors");
-
- migrationBuilder.DropIndex(
- name: "IX_Payouts_StoreDataId",
- table: "Payouts");
- migrationBuilder.DropColumn(
- name: "StoreDataId",
- table: "Payouts");
- }
- }
-}
### BTCPayServer.Data/Migrations/20220414132313_AddLightningAddress.cs
@@ -1,51 +0,0 @@
-// <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>(nullable: false, maxLength: null),
- StoreDataId = table.Column<string>(nullable: false, maxLength: null),
- 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");
- }
- }
-}
### BTCPayServer.Data/Migrations/20220518061525_invoice_created_idx.cs
@@ -1,28 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20220518061525_invoice_created_idx")]
- public partial class invoice_created_idx : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateIndex(
- name: "IX_Invoices_Created",
- table: "Invoices",
- column: "Created");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropIndex(
- name: "IX_Invoices_Created",
- table: "Invoices");
- }
- }
-}
### BTCPayServer.Data/Migrations/20220523022603_remove_historical_addresses.cs
@@ -1,44 +0,0 @@
-using System;
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20220523022603_remove_historical_addresses")]
- public partial class remove_historical_addresses : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable(
- name: "HistoricalAddressInvoices");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "HistoricalAddressInvoices",
- columns: table => new
- {
- InvoiceDataId = table.Column<string>(type: "TEXT", nullable: false),
- Address = table.Column<string>(type: "TEXT", nullable: false),
- Assigned = table.Column<DateTimeOffset>(type: "TEXT", nullable: false),
- CryptoCode = table.Column<string>(type: "TEXT", nullable: true),
- UnAssigned = table.Column<DateTimeOffset>(type: "TEXT", nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_HistoricalAddressInvoices", x => new { x.InvoiceDataId, x.Address });
- table.ForeignKey(
- name: "FK_HistoricalAddressInvoices_Invoices_InvoiceDataId",
- column: x => x.InvoiceDataId,
- principalTable: "Invoices",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
- }
- }
-}
### BTCPayServer.Data/Migrations/20220610090843_AddSettingsToStore.cs
@@ -1,43 +0,0 @@
-using System;
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20220610090843_AddSettingsToStore")]
- public partial class AddSettingsToStore : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "StoreSettings",
- columns: table => new
- {
- Name = table.Column<string>(nullable: false, maxLength: null),
- StoreId = table.Column<string>(nullable: false, maxLength: null),
- Value = table.Column<string>(type: "JSONB", nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_StoreSettings", x => new { x.StoreId, x.Name });
- table.ForeignKey(
- name: "FK_StoreSettings_Stores_StoreId",
- column: x => x.StoreId,
- principalTable: "Stores",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable(
- name: "StoreSettings");
- }
- }
-}
### BTCPayServer.Data/Migrations/20220929132704_label.cs
@@ -1,81 +0,0 @@
-// <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("20220929132704_label")]
- public partial class label : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "WalletObjects",
- columns: table => new
- {
- WalletId = table.Column<string>(nullable: false, maxLength: null),
- Type = table.Column<string>(nullable: false, maxLength: null),
- Id = table.Column<string>(nullable: false, maxLength: null),
- Data = table.Column<string>(type: "JSONB", nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_WalletObjects", x => new { x.WalletId, x.Type, x.Id });
- });
- migrationBuilder.CreateIndex(
- name: "IX_WalletObjects_Type_Id",
- table: "WalletObjects",
- columns: new[] { "Type", "Id" });
-
- migrationBuilder.CreateTable(
- name: "WalletObjectLinks",
- columns: table => new
- {
- WalletId = table.Column<string>(nullable: false, maxLength: null),
- AType = table.Column<string>(nullable: false, maxLength: null),
- AId = table.Column<string>(nullable: false, maxLength: null),
- BType = table.Column<string>(nullable: false, maxLength: null),
- BId = table.Column<string>(nullable: false, maxLength: null),
- Data = table.Column<string>(type: "JSONB", nullable: true)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_WalletObjectLinks", x => new { x.WalletId, x.AType, x.AId, x.BType, x.BId });
- table.ForeignKey(
- name: "FK_WalletObjectLinks_WalletObjects_WalletId_BType_BId",
- columns: x => new { x.WalletId, x.BType, x.BId },
- principalTable: "WalletObjects",
- principalColumns: new[] { "WalletId", "Type", "Id" },
- onDelete: ReferentialAction.Cascade);
- table.ForeignKey(
- name: "FK_WalletObjectLinks_WalletObjects_WalletId_AType_AId",
- columns: x => new { x.WalletId, x.AType, x.AId },
- principalTable: "WalletObjects",
- principalColumns: new[] { "WalletId", "Type", "Id" },
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateIndex(
- name: "IX_WalletObjectLinks_WalletId_BType_BId",
- table: "WalletObjectLinks",
- columns: new[] { "WalletId", "BType", "BId" });
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable(
- name: "WalletObjectLinks");
-
- migrationBuilder.DropTable(
- name: "WalletObjects");
- }
- }
-}
### BTCPayServer.Data/Migrations/20221128062447_jsonb.cs
@@ -1,28 +0,0 @@
-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("20221128062447_jsonb")]
- public partial class jsonb : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql("ALTER TABLE \"Settings\" ALTER COLUMN \"Value\" TYPE JSONB USING \"Value\"::JSONB");
- migrationBuilder.Sql("ALTER TABLE \"Stores\" ALTER COLUMN \"StoreBlob\" TYPE JSONB USING regexp_replace(convert_from(\"StoreBlob\",'UTF8'), '\\\\u0000', '', 'g')::JSONB");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- // Not supported
- }
- }
-}
### BTCPayServer.Data/Migrations/20230123062447_migrateoldratesource.cs
@@ -1,27 +0,0 @@
-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("20230123062447_migrateoldratesource")]
- public partial class migrateoldratesource : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql("UPDATE \"Stores\" SET \"StoreBlob\"=jsonb_set(\"StoreBlob\", \'{preferredExchange}\', \'{\"oasis_trade\": \"oasisdev\", \"gdax\":\"coinbasepro\", \"coinaverage\":\"kraken\"}\'::jsonb->(\"StoreBlob\"->>\'preferredExchange\')) WHERE \"StoreBlob\"->>\'preferredExchange\' = ANY (ARRAY[\'oasis_trade\', \'gdax\', \'coinaverage\']);");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- // Not supported
- }
- }
-}
### BTCPayServer.Data/Migrations/20230125085242_AddForms.cs
@@ -1,53 +0,0 @@
-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("20230125085242_AddForms")]
- public partial class AddForms : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "Forms",
- columns: table => new
- {
- Id = table.Column<string>(type: "TEXT", nullable: false, maxLength: null),
- Name = table.Column<string>(type: "TEXT", nullable: true, maxLength: null),
- StoreId = table.Column<string>(type: "TEXT", nullable: true, maxLength: null),
- Config = table.Column<string>(type: "JSONB", nullable: true),
- Public = table.Column<bool>(nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_Forms", x => x.Id);
- table.ForeignKey(
- name: "FK_Forms_Stores_StoreId",
- column: x => x.StoreId,
- principalTable: "Stores",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateIndex(
- name: "IX_Forms_StoreId",
- table: "Forms",
- column: "StoreId");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable(
- name: "Forms");
-
- }
- }
-}
### BTCPayServer.Data/Migrations/20230130040047_blob2.cs
@@ -1,149 +0,0 @@
-using System;
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20230130040047_blob2")]
- public partial class blob2 : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "Webhooks",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "WebhookDeliveries",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "PaymentRequests",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "Notifications",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "LightningAddresses",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "Fido2Credentials",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "AspNetUsers",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "ApiKeys",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "Invoices",
- type: "JSONB",
- nullable: true);
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "Payments",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "PayoutProcessors",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Blob2",
- table: "CustodianAccount",
- type: "JSONB",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Type",
- table: "Payments",
- type: "TEXT",
- nullable: true);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "Webhooks");
-
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "WebhookDeliveries");
-
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "PaymentRequests");
-
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "Notifications");
-
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "LightningAddresses");
-
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "Fido2Credentials");
-
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "AspNetUsers");
-
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "ApiKeys");
-
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "Invoices");
-
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "Payments");
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "PayoutProcessors");
-
- migrationBuilder.DropColumn(
- name: "Blob2",
- table: "CustodianAccount");
-
- migrationBuilder.DropColumn(
- name: "Type",
- table: "Payments");
- }
- }
-}
### BTCPayServer.Data/Migrations/20230130062447_jsonb2.cs
@@ -1,27 +0,0 @@
-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("20230130062447_jsonb2")]
- public partial class jsonb2 : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql("ALTER TABLE \"Stores\" ALTER COLUMN \"DerivationStrategies\" TYPE JSONB USING \"DerivationStrategies\"::JSONB");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- // Not supported
- }
- }
-}
### BTCPayServer.Data/Migrations/20230315062447_fixmaxlength.cs
@@ -1,28 +0,0 @@
-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("20230315062447_fixmaxlength")]
- public partial class fixmaxlength : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql("ALTER TABLE \"InvoiceSearches\" ALTER COLUMN \"Value\" TYPE TEXT USING \"Value\"::TEXT;");
- migrationBuilder.Sql("ALTER TABLE \"Invoices\" ALTER COLUMN \"OrderId\" TYPE TEXT USING \"OrderId\"::TEXT;");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- // Not supported
- }
- }
-}
### BTCPayServer.Data/Migrations/20230504125505_StoreRoles.cs
@@ -1,90 +0,0 @@
-using System;
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
-using NBitcoin;
-using Newtonsoft.Json;
-using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20230504125505_StoreRoles")]
- public partial class StoreRoles : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "StoreRoles",
- columns: table => new
- {
- Id = table.Column<string>(type: "TEXT", nullable: false),
- StoreDataId = table.Column<string>(type: "TEXT", nullable: true),
- Role = table.Column<string>(type: "TEXT", nullable: false),
- Permissions = table.Column<string>(type: "TEXT[]", nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_StoreRoles", x => x.Id);
- table.ForeignKey(
- name: "FK_StoreRoles_Stores_StoreDataId",
- column: x => x.StoreDataId,
- principalTable: "Stores",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
- migrationBuilder.CreateIndex(
- name: "IX_StoreRoles_StoreDataId_Role",
- table: "StoreRoles",
- columns: new[] { "StoreDataId", "Role" },
- unique: true);
-
- migrationBuilder.InsertData(
- "StoreRoles",
- columns: new[] { "Id", "Role", "Permissions" },
- columnTypes: new[] { "TEXT", "TEXT", "TEXT[]" },
- values: new object[,]
- {
- {
- "Owner", "Owner", new[]
- {
- "btcpay.store.canmodifystoresettings",
- "btcpay.store.cantradecustodianaccount",
- "btcpay.store.canwithdrawfromcustodianaccount",
- "btcpay.store.candeposittocustodianaccount"
- }
- },
- {
- "Guest", "Guest", new[]
- {
- "btcpay.store.canviewstoresettings",
- "btcpay.store.canmodifyinvoices",
- "btcpay.store.canviewcustodianaccounts",
- "btcpay.store.candeposittocustodianaccount"
- }
- }
- });
-
- migrationBuilder.AddForeignKey(
- name: "FK_UserStore_StoreRoles_Role",
- table: "UserStore",
- column: "Role",
- principalTable: "StoreRoles",
- principalColumn: "Id");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropForeignKey(
- name: "FK_UserStore_StoreRoles_Role",
- table: "UserStore");
-
- migrationBuilder.DropTable(
- name: "StoreRoles");
- }
- }
-}
### BTCPayServer.Data/Migrations/20230529135505_WebhookDeliveriesCleanup.cs
@@ -1,80 +0,0 @@
-using System;
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
-using NBitcoin;
-using Newtonsoft.Json;
-using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20230529135505_WebhookDeliveriesCleanup")]
- public partial class WebhookDeliveriesCleanup : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql("DROP TABLE IF EXISTS \"InvoiceWebhookDeliveries\", \"WebhookDeliveries\";");
-
- migrationBuilder.CreateTable(
- name: "WebhookDeliveries",
- columns: table => new
- {
- Id = table.Column<string>(type: "TEXT", nullable: false),
- WebhookId = table.Column<string>(type: "TEXT", nullable: false),
- Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
- Pruned = table.Column<bool>(type: "BOOLEAN", nullable: false),
- Blob = table.Column<string>(type: "JSONB", nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_WebhookDeliveries", x => x.Id);
- table.ForeignKey(
- name: "FK_WebhookDeliveries_Webhooks_WebhookId",
- column: x => x.WebhookId,
- principalTable: "Webhooks",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
-
-
- migrationBuilder.CreateIndex(
- name: "IX_WebhookDeliveries_WebhookId",
- table: "WebhookDeliveries",
- column: "WebhookId");
- migrationBuilder.Sql("CREATE INDEX \"IX_WebhookDeliveries_Timestamp\" ON \"WebhookDeliveries\"(\"Timestamp\") WHERE \"Pruned\" IS FALSE");
-
- migrationBuilder.CreateTable(
- name: "InvoiceWebhookDeliveries",
- columns: table => new
- {
- InvoiceId = table.Column<string>(type: "TEXT", nullable: false),
- DeliveryId = table.Column<string>(type: "TEXT", nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_InvoiceWebhookDeliveries", x => new { x.InvoiceId, x.DeliveryId });
- table.ForeignKey(
- name: "FK_InvoiceWebhookDeliveries_WebhookDeliveries_DeliveryId",
- column: x => x.DeliveryId,
- principalTable: "WebhookDeliveries",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- table.ForeignKey(
- name: "FK_InvoiceWebhookDeliveries_Invoices_InvoiceId",
- column: x => x.InvoiceId,
- principalTable: "Invoices",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
-
- }
- }
-}
### BTCPayServer.Data/Migrations/20230906135844_AddArchivedFlagForStoresAndApps.cs
@@ -1,39 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20230906135844_AddArchivedFlagForStoresAndApps")]
- public partial class AddArchivedFlagForStoresAndApps : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<bool>(
- name: "Archived",
- table: "Stores",
- nullable: false,
- defaultValue: false);
-
- migrationBuilder.AddColumn<bool>(
- name: "Archived",
- table: "Apps",
- nullable: false,
- defaultValue: false);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Archived",
- table: "Stores");
-
- migrationBuilder.DropColumn(
- name: "Archived",
- table: "Apps");
- }
- }
-}
### BTCPayServer.Data/Migrations/20231020135844_AddBoltcardsTable.cs
@@ -1,38 +1,13 @@
-using System.Security.Permissions;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Migrations;
-#nullable disable
-
namespace BTCPayServer.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20231020135844_AddBoltcardsTable")]
- public partial class AddBoltcardsTable : Migration
+ [DBScript("000.Init.sql")]
+ public partial class AddBoltcardsTable : DBScriptsMigration
{
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "boltcards",
- columns: table => new
- {
- id = table.Column<string>(maxLength: 32, nullable: false),
- counter = table.Column<int>(type: "INT", nullable: false, defaultValue: 0),
- ppid = table.Column<string>(maxLength: 30, nullable: true),
- version = table.Column<int>(nullable: false, defaultValue: 0)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_id", x => x.id);
- table.ForeignKey("FK_boltcards_PullPayments", x => x.ppid, "PullPayments", "Id", onDelete: ReferentialAction.SetNull);
- });
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable("boltcards");
- }
}
}
### BTCPayServer.Tests/AltcoinTests/AltcoinTests.cs
@@ -612,7 +612,7 @@ public async Task CanUsePoSApp()
price: 1.02
custom: true
";
- vmpos.Template = AppService.SerializeTemplate(MigrationStartupTask.ParsePOSYML(vmpos.Template));
+ vmpos.Template = AppService.SerializeTemplate(TestUtils.ParsePOSYML(vmpos.Template));
Assert.IsType<RedirectToActionResult>(pos.UpdatePointOfSale(app.Id, vmpos).Result);
vmpos = await pos.UpdatePointOfSale(app.Id).AssertViewModelAsync<UpdatePointOfSaleViewModel>();
Assert.Equal("hello", vmpos.Title);
@@ -684,7 +684,7 @@ public async Task CanUsePoSApp()
price: 1.02
custom: true
";
- vmpos.Template = AppService.SerializeTemplate(MigrationStartupTask.ParsePOSYML(vmpos.Template));
+ vmpos.Template = AppService.SerializeTemplate(TestUtils.ParsePOSYML(vmpos.Template));
Assert.IsType<RedirectToActionResult>(pos.UpdatePointOfSale(app.Id, vmpos).Result);
publicApps = user.GetController<UIPointOfSaleController>();
vmview = await publicApps.ViewPointOfSale(app.Id, PosViewType.Cart).AssertViewModelAsync<ViewPointOfSaleViewModel>();
@@ -713,7 +713,7 @@ public async Task CanUsePoSApp()
noninventoryitem:
price: 10.0";
- vmpos.Template = AppService.SerializeTemplate(MigrationStartupTask.ParsePOSYML(vmpos.Template));
+ vmpos.Template = AppService.SerializeTemplate(TestUtils.ParsePOSYML(vmpos.Template));
Assert.IsType<RedirectToActionResult>(pos.UpdatePointOfSale(app.Id, vmpos).Result);
async Task AssertCanBuy(string choiceKey, bool expected)
@@ -779,7 +779,7 @@ await TestUtils.EventuallyAsync(async () =>
custom: topup
";
- vmpos.Template = AppService.SerializeTemplate(MigrationStartupTask.ParsePOSYML(vmpos.Template));
+ vmpos.Template = AppService.SerializeTemplate(TestUtils.ParsePOSYML(vmpos.Template));
Assert.IsType<RedirectToActionResult>(pos.UpdatePointOfSale(app.Id, vmpos).Result);
vmpos = await pos.UpdatePointOfSale(app.Id).AssertViewModelAsync<UpdatePointOfSaleViewModel>();
Assert.DoesNotContain("custom", vmpos.Template);
### BTCPayServer.Tests/BTCPayServer.Tests.csproj
@@ -46,6 +46,7 @@
<PackageReference Include="Newtonsoft.Json.Schema" Version="4.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="10.0.14" />
<PackageReference Include="xunit.v3" Version="4.0.2" />
+ <PackageReference Include="YamlDotNet" Version="18.1.0" />
</ItemGroup>
<ItemGroup>
<None Update=".dockerignore">
### BTCPayServer.Tests/LightningTests.cs
@@ -971,7 +971,7 @@ public async Task CanSetPaymentMethodLimitsLightning()
[Trait("Integration", "Integration")]
[Fact]
- public async Task CanDoLightningInternalNodeMigration()
+ public async Task CanMigratePaymentMethodConfigs()
{
using var tester = CreateServerTester(newDb: true);
tester.ActivateLightning(LightningTestImplementation.CoreLightning);
@@ -980,34 +980,15 @@ public async Task CanDoLightningInternalNodeMigration()
await acc.GrantAccessAsync(true);
await acc.CreateStoreAsync();
- // Test if legacy DerivationStrategy column is converted to DerivationStrategies
- var store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
- var xpub = "tpubDDmH1briYfZcTDMEc7uMEA5hinzjUTzR9yMC1drxTMeiWyw1VyCqTuzBke6df2sqbfw9QG6wbgTLF5yLjcXsZNaXvJMZLwNEwyvmiFWcLav";
- var derivation = $"{xpub}-[legacy]";
- Assert.NotNull(store);
-#pragma warning disable CS0618 // Type or member is obsolete
- store.DerivationStrategy = derivation;
-
- await tester.PayTester.StoreRepository.UpdateStore(store);
- await tester.RestartMigration();
- store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
- Assert.NotNull(store);
- Assert.True(string.IsNullOrEmpty(store.DerivationStrategy));
var handlers = tester.PayTester.GetService<PaymentMethodHandlerDictionary>();
- var pmi = PaymentTypes.CHAIN.GetPaymentMethodId("BTC");
- var v = store.GetPaymentMethodConfig<DerivationSchemeSettings>(pmi, handlers);
- Assert.NotNull(v);
- Assert.Equal(derivation, v.AccountDerivation.ToString());
- Assert.Equal(derivation, v.AccountOriginal);
- Assert.Equal(xpub, v.GetFirstAccountKeySettings().AccountKey.ToString());
-
await acc.RegisterLightningNodeAsync("BTC", LightningTestImplementation.CoreLightning);
- store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
+ var store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
- pmi = PaymentTypes.LN.GetPaymentMethodId("BTC");
+ var pmi = PaymentTypes.LN.GetPaymentMethodId("BTC");
Assert.NotNull(store);
var lnMethod = store.GetPaymentMethodConfig<LightningPaymentMethodConfig>(pmi, handlers);
- Assert.NotNull(lnMethod?.GetExternalLightningUrl());
+ var originalConnectionString = lnMethod?.GetExternalLightningUrl();
+ Assert.NotNull(originalConnectionString);
var conf = store.GetPaymentMethodConfig(pmi);
Assert.NotNull(conf);
conf["LightningConnectionString"] = conf["connectionString"]!.Value<string>();
@@ -1020,30 +1001,14 @@ public async Task CanDoLightningInternalNodeMigration()
store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
Assert.NotNull(store);
lnMethod = store.GetPaymentMethodConfig<LightningPaymentMethodConfig>(pmi, handlers);
- Assert.Null(lnMethod?.GetExternalLightningUrl());
- Assert.True(lnMethod?.IsInternalNode);
+ Assert.Equal(originalConnectionString, lnMethod?.GetExternalLightningUrl());
+ Assert.False(lnMethod?.IsInternalNode);
conf = store.GetPaymentMethodConfig(pmi);
Assert.NotNull(conf);
Assert.Null(conf["CryptoCode"]); // Osolete
- Assert.Null(conf["connectionString"]); // Null, so should be stripped
+ Assert.Equal(originalConnectionString, conf["connectionString"]?.Value<string>());
Assert.Null(conf["DisableBOLT11PaymentOption"]); // Old garbage cleaned
- // Test if lightning connection strings get migrated to internal
- store.DerivationStrategies = new JObject()
- {
- new JProperty("BTC_LightningLike", new JObject()
- {
- new JProperty("CryptoCode", "BTC"),
- new JProperty("LightningConnectionString", tester.PayTester.IntegratedLightning),
- })
- }.ToString();
- await tester.PayTester.StoreRepository.UpdateStore(store);
- await tester.RestartMigration();
- store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
- Assert.NotNull(store);
- lnMethod = store.GetPaymentMethodConfig<LightningPaymentMethodConfig>(pmi, handlers);
- Assert.True(lnMethod?.IsInternalNode);
-
store.SetPaymentMethodConfig(PaymentMethodId.Parse("BTC-LNURL"),
new JObject()
{
@@ -1060,7 +1025,20 @@ public async Task CanDoLightningInternalNodeMigration()
Assert.Null(conf["CryptoCode"]);
Assert.True(conf["lud12Enabled"]?.Value<bool>());
Assert.Null(conf["useBech32Scheme"]); // default stripped
-#pragma warning restore CS0618 // Type or member is obsolete
+
+ // String-valued derivation schemes still need the newer store-config migration.
+ var xpub = "tpubDDmH1briYfZcTDMEc7uMEA5hinzjUTzR9yMC1drxTMeiWyw1VyCqTuzBke6df2sqbfw9QG6wbgTLF5yLjcXsZNaXvJMZLwNEwyvmiFWcLav";
+ var derivation = $"{xpub}-[legacy]";
+ pmi = PaymentTypes.CHAIN.GetPaymentMethodId("BTC");
+ store.DerivationStrategies = new JObject { [pmi.ToString()] = derivation }.ToString();
+ await tester.PayTester.StoreRepository.UpdateStore(store);
+ await tester.RestartMigration();
+ store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
+ var scheme = store.GetPaymentMethodConfig<DerivationSchemeSettings>(pmi, handlers);
+ Assert.NotNull(scheme);
+ Assert.Equal(derivation, scheme.AccountDerivation.ToString());
+ Assert.Null(scheme.AccountOriginal); // The parser omits the original for legacy derivations.
+ Assert.Equal(xpub, scheme.GetFirstAccountKeySettings().AccountKey.ToString());
}
[Fact(Timeout = 60 * 20 * 1000)]
### BTCPayServer.Tests/POSTests.cs
@@ -86,7 +86,7 @@ public void CanParseOldYmlCorrectly()
inventory: 5
custom: true
";
- var parsedDefault = MigrationStartupTask.ParsePOSYML(testOriginalDefaultYmlTemplate);
+ var parsedDefault = TestUtils.ParsePOSYML(testOriginalDefaultYmlTemplate);
Assert.Equal(6, parsedDefault.Length);
Assert.Equal( "Green Tea" ,parsedDefault[0].Title);
Assert.Equal( "green tea" ,parsedDefault[0].Id);
@@ -335,7 +335,7 @@ public async Task CanUsePoSApp1()
price: 0
";
vmpos.Currency = "EUR";
- vmpos.Template = AppService.SerializeTemplate(MigrationStartupTask.ParsePOSYML(vmpos.Template));
+ vmpos.Template = AppService.SerializeTemplate(TestUtils.ParsePOSYML(vmpos.Template));
Assert.IsType<RedirectToActionResult>(pos.UpdatePointOfSale(app.Id, vmpos).Result);
await pos.UpdatePointOfSale(app.Id).AssertViewModelAsync<UpdatePointOfSaleViewModel>();
var publicApps = user.GetController<UIPointOfSaleController>();
### BTCPayServer.Tests/TestUtils.cs
@@ -7,15 +7,116 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using BTCPayServer.Client.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Sdk;
+using YamlDotNet.RepresentationModel;
namespace BTCPayServer.Tests
{
public static class TestUtils
{
+ // Convert legacy YAML fixtures; production apps already store JSON templates.
+ public static AppItem[] ParsePOSYML(string yaml)
+ {
+ var items = new List<AppItem>();
+ var stream = new YamlStream();
+ if (string.IsNullOrEmpty(yaml))
+ return items.ToArray();
+
+ stream.Load(new StringReader(yaml));
+
+ if (stream.Documents.FirstOrDefault()?.RootNode is not YamlMappingNode root)
+ return items.ToArray();
+ foreach (var posItem in root.Children)
+ {
+ var trimmedKey = ((YamlScalarNode)posItem.Key).Value?.Trim();
+ if (string.IsNullOrEmpty(trimmedKey))
+ {
+ continue;
+ }
+
+ var currentItem = new AppItem
+ {
+ Id = trimmedKey,
+ Title = trimmedKey,
+ PriceType = AppItemPriceType.Fixed
+ };
+ var itemSpecs = (YamlMappingNode)posItem.Value;
+ foreach (var spec in itemSpecs)
+ {
+ if (spec.Key is not YamlScalarNode { Value: string keyString } || string.IsNullOrEmpty(keyString))
+ continue;
+ var scalarValue = spec.Value as YamlScalarNode;
+ switch (keyString)
+ {
+ case "title":
+ currentItem.Title = scalarValue?.Value ?? trimmedKey;
+ break;
+ case "inventory":
+ if (int.TryParse(scalarValue?.Value, out var inv))
+ {
+ currentItem.Inventory = inv;
+ }
+ break;
+ case "description":
+ currentItem.Description = scalarValue?.Value;
+ break;
+ case "image":
+ currentItem.Image = scalarValue?.Value;
+ break;
+ case "price_type":
+ case "custom":
+ if (bool.TryParse(scalarValue?.Value, out var customBoolValue))
+ {
+ if (customBoolValue)
+ {
+ currentItem.PriceType = currentItem.Price is null or 0
+ ? AppItemPriceType.Topup
+ : AppItemPriceType.Minimum;
+ }
+ else
+ {
+ currentItem.PriceType = AppItemPriceType.Fixed;
+ }
+ }
+ else if (Enum.TryParse<AppItemPriceType>(scalarValue?.Value, true,
+ out var customPriceType))
+ {
+ currentItem.PriceType = customPriceType;
+ }
+
+ break;
+ case "price":
+ if (decimal.TryParse(scalarValue?.Value, out var price))
+ {
+ currentItem.Price = price;
+ }
+
+ break;
+
+ case "buybuttontext":
+ currentItem.BuyButtonText = scalarValue?.Value;
+ break;
+
+ case "disabled":
+ if (bool.TryParse(scalarValue?.Value, out var disabled))
+ {
+ currentItem.Disabled = disabled;
+ }
+
+ break;
+ }
+ }
+
+ items.Add(currentItem);
+ }
+
+ return items.ToArray();
+ }
+
public const int LongRunningTestTimeout = 60_000; // 60s
#if DEBUG && !SHORT_TIMEOUT
public const int TestTimeout = 600_000;
### BTCPayServer.Tests/UnitTest1.cs
@@ -2196,35 +2196,6 @@ public async Task CanCheckForNewVersion()
Assert.False(fn.Seen);
}
- [Fact(Timeout = LongRunningTestTimeout)]
- [Trait("Integration", "Integration")]
- public async Task CanFixMappedDomainAppType()
- {
- using var tester = CreateServerTester(newDb: true);
- await tester.StartAsync();
- var f = tester.PayTester.GetService<ApplicationDbContextFactory>();
- const string id = "BTCPayServer.Services.PoliciesSettings";
- using (var ctx = f.CreateContext())
- {
- // remove existing policies setting
- var setting = await ctx.Settings.FirstOrDefaultAsync(c => c.Id == id);
- if (setting != null) ctx.Settings.Remove(setting);
- // create legacy policies setting that needs migration
- setting = new SettingData { Id = id, Value = JObject.Parse("{\"RootAppId\": null, \"RootAppType\": 1, \"Experimental\": false, \"PluginSource\": null, \"LockSubscription\": false, \"DisableSSHService\": false, \"PluginPreReleases\": false, \"BlockExplorerLinks\": [],\"DomainToAppMapping\": [{\"AppId\": \"87kj5yKay8mB4UUZcJhZH5TqDKMD3CznjwLjiu1oYZXe\", \"Domain\": \"donate.nicolas-dorier.com\", \"AppType\": 0}], \"CheckForNewVersions\": false, \"AllowHotWalletForAll\": false, \"RequiresConfirmedEmail\": false, \"DiscourageSearchEngines\": false, \"DisableNonAdminCreateUserApi\": false, \"AllowHotWalletRPCImportForAll\": false, \"AllowLightningInternalNodeForAll\": false, \"DisableStoresToUseServerEmailSettings\": false}").ToString() };
- ctx.Settings.Add(setting);
- await ctx.SaveChangesAsync();
- }
- await tester.RestartMigration();
- using (var ctx = f.CreateContext())
- {
- var setting = await ctx.Settings.FirstOrDefaultAsync(c => c.Id == id);
- var o = JObject.Parse(setting.Value);
- Assert.Equal("Crowdfund", o["RootAppType"].Value<string>());
- o = (JObject)((JArray)o["DomainToAppMapping"])[0];
- Assert.Equal("PointOfSale", o["AppType"].Value<string>());
- }
- }
-
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanMigrateFileIds()
@@ -2323,9 +2294,17 @@ public async Task CanDoLabelMigrations()
{
for (int i = 0; i < walletCount; i++)
{
- var walletData = new WalletData() { Id = $"S-{wallet}{i}-BTC" };
- walletData.Blob = ZipUtils.Zip("{\"LabelColors\": { \"label1\" : \"black\", \"payout\":\"green\" }}");
- db.Wallets.Add(walletData);
+ db.Wallets.Add(new WalletData { Id = $"S-{wallet}{i}-BTC" });
+ foreach (var (label, color) in new[] { ("label1", "black"), ("payout", "green") })
+ {
+ db.WalletObjects.Add(new WalletObjectData
+ {
+ WalletId = $"S-{wallet}{i}-BTC",
+ Type = WalletObjectData.Types.Label,
+ Id = label,
+ Data = new JObject { ["color"] = color }.ToString()
+ });
+ }
}
await db.SaveChangesAsync();
}
@@ -2382,28 +2361,6 @@ public async Task CanDoLabelMigrations()
Assert.Single(payoutLabel.PullPaymentPayouts["pp2"]);
}
- [Fact(Timeout = LongRunningTestTimeout)]
- [Trait("Integration", "Integration")]
- public async Task CanDoRateSourceMigration()
- {
- using var tester = CreateServerTester(newDb: true);
- await tester.StartAsync();
- var acc = tester.NewAccount();
- await acc.CreateStoreAsync();
- var db = tester.PayTester.GetService<ApplicationDbContextFactory>();
- using var ctx = db.CreateContext();
- var store = (await ctx.Stores.AsNoTracking().ToListAsync())[0];
- var b = store.GetStoreBlob();
- b.GetOrCreateRateSettings(false).PreferredExchange = "coinaverage";
- store.SetStoreBlob(b);
- await ctx.SaveChangesAsync();
- await ctx.Database.ExecuteSqlRawAsync("DELETE FROM \"__EFMigrationsHistory\" WHERE \"MigrationId\"='20230123062447_migrateoldratesource'");
- await ctx.Database.MigrateAsync();
- store = (await ctx.Stores.AsNoTracking().ToListAsync())[0];
- b = store.GetStoreBlob();
- Assert.Equal("coingecko", b.GetOrCreateRateSettings(false).PreferredExchange);
- }
-
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CreateStoreDoesNotTrustCanEditPreferredExchange()
@@ -2770,46 +2727,6 @@ public async Task CanDoInvoiceMigrations()
await acc.GrantAccessAsync(true);
await acc.CreateStoreAsync();
await acc.RegisterDerivationSchemeAsync("BTC");
- var store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
-
- var blob = store.GetStoreBlob();
- var serializer = new Serializer(null);
-
- blob.AdditionalData = new Dictionary<string, JToken>();
- blob.AdditionalData.Add("rateRules", JToken.Parse(
- serializer.ToString(new List<MigrationStartupTask.RateRule_Obsolete>()
- {
- new MigrationStartupTask.RateRule_Obsolete()
- {
- Multiplier = 2
- }
- })));
-
- blob.AdditionalData.Add("onChainMinValue", JToken.Parse(
- serializer.ToString(new CurrencyValue()
- {
- Currency = "USD",
- Value = 5m
- }.ToString())));
- blob.AdditionalData.Add("lightningMaxValue", JToken.Parse(
- serializer.ToString(new CurrencyValue()
- {
- Currency = "USD",
- Value = 5m
- }.ToString())));
-
- store.SetStoreBlob(blob);
- await tester.PayTester.StoreRepository.UpdateStore(store);
- await tester.RestartMigration();
-
- store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
-
- blob = store.GetStoreBlob();
- Assert.Empty(blob.AdditionalData);
- Assert.Single(blob.PaymentMethodCriteria);
- Assert.Contains(blob.PaymentMethodCriteria,
- criteria => criteria.PaymentMethod == PaymentTypes.CHAIN.GetPaymentMethodId("BTC") &&
- criteria.Above && criteria.Value.Value == 5m && criteria.Value.Currency == "USD");
var handlers = tester.PayTester.GetService<PaymentMethodHandlerDictionary>();
await acc.ImportOldInvoices();
@@ -2840,6 +2757,31 @@ await TestUtils.EventuallyAsync(async () =>
Assert.Equal("6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d", details.AssetId.ToString());
}
+ [Fact(Timeout = TestUtils.TestTimeout)]
+ [Trait("Integration", "Integration")]
+ public async Task CanInitializeStorageOnFirstRun()
+ {
+ using var tester = CreateServerTester(newDb: true);
+ await tester.StartAsync();
+ var settings = tester.PayTester.GetService<SettingsRepository>();
+ var storage = await settings.GetSettingAsync<StorageSettings>();
+ Assert.NotNull(storage);
+ Assert.Equal(StorageProvider.FileSystem, storage.Provider);
+ Assert.Equal(JObject.FromObject(new FileSystemStorageConfiguration()), storage.Configuration);
+
+ storage = new StorageSettings
+ {
+ Provider = StorageProvider.AmazonS3,
+ Configuration = new JObject { ["BucketName"] = "existing-bucket" }
+ };
+ await settings.UpdateSetting(storage);
+ await settings.UpdateSetting<MigrationSettings>(null, SettingsRepository.KeyNameByType(typeof(MigrationSettings)));
+ await tester.PayTester.RestartStartupTask<MigrationStartupTask>();
+ var existingStorage = await settings.GetSettingAsync<StorageSettings>();
+ Assert.Equal(StorageProvider.AmazonS3, existingStorage.Provider);
+ Assert.Equal(storage.Configuration, existingStorage.Configuration);
+ }
+
[Fact(Timeout = TestUtils.TestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanConfigureStorage()
### BTCPayServer/BTCPayServer.csproj
@@ -35,7 +35,6 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="NBitcoin" Version="10.0.19" />
- <PackageReference Include="YamlDotNet" Version="18.1.0" />
<PackageReference Include="BIP78.Sender" Version="0.2.5" />
<PackageReference Include="BTCPayServer.Hwi" Version="2.0.6" />
<PackageReference Include="BTCPayServer.Lightning.All" Version="1.7.14" />
### BTCPayServer/Hosting/MigrationStartupTask.cs
@@ -1,94 +1,40 @@
using System;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
-using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Contracts;
-using BTCPayServer.Client.Models;
using BTCPayServer.Configuration;
using BTCPayServer.Data;
-using BTCPayServer.Fido2;
-using BTCPayServer.Fido2.Models;
using BTCPayServer.Payments;
using BTCPayServer.Payments.Bitcoin;
using BTCPayServer.Payments.Lightning;
-using BTCPayServer.Payouts;
-using BTCPayServer.Plugins.Crowdfund;
-using BTCPayServer.Plugins.Emails.Services;
-using BTCPayServer.Plugins.PointOfSale;
using BTCPayServer.Services;
-using BTCPayServer.Services.Apps;
using BTCPayServer.Services.Invoices;
-using BTCPayServer.Services.Stores;
using BTCPayServer.Storage.Models;
using BTCPayServer.Storage.Services.Providers.FileSystemStorage.Configuration;
-using Fido2NetLib.Cbor;
-using Fido2NetLib.Objects;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
-using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
-using YamlDotNet.RepresentationModel;
-using LightningAddressData = BTCPayServer.Data.LightningAddressData;
+using Npgsql;
namespace BTCPayServer.Hosting
{
- public class MigrationStartupTask : IStartupTask
+ public class MigrationStartupTask(
+ IEnumerable<IMigrationExecutor> migrationExecutors,
+ PaymentMethodHandlerDictionary handlers,
+ ApplicationDbContextFactory dbContextFactory,
+ SettingsRepository settingsRepository,
+ ILogger<MigrationStartupTask> logger)
+ : IStartupTask
{
-
- private readonly ApplicationDbContextFactory _DBContextFactory;
- private readonly StoreRepository _StoreRepository;
- private readonly IEnumerable<IMigrationExecutor> _migrationExecutors;
- private readonly PaymentMethodHandlerDictionary _handlers;
- private readonly SettingsRepository _Settings;
- private readonly AppService _appService;
- private readonly PayoutMethodHandlerDictionary _payoutHandlers;
- private readonly BTCPayNetworkJsonSerializerSettings _btcPayNetworkJsonSerializerSettings;
- private readonly LightningAddressService _lightningAddressService;
- private readonly ILogger<MigrationStartupTask> _logger;
- private readonly LightningClientFactoryService _lightningClientFactoryService;
- private readonly IFileService _fileService;
-
- public IOptions<LightningNetworkOptions> LightningOptions { get; }
-
- public MigrationStartupTask(
- IEnumerable<IMigrationExecutor> migrationExecutors,
- PaymentMethodHandlerDictionary handlers,
- StoreRepository storeRepository,
- ApplicationDbContextFactory dbContextFactory,
- IOptions<LightningNetworkOptions> lightningOptions,
- SettingsRepository settingsRepository,
- AppService appService,
- PayoutMethodHandlerDictionary payoutHandlers,
- BTCPayNetworkJsonSerializerSettings btcPayNetworkJsonSerializerSettings,
- LightningAddressService lightningAddressService,
- ILogger<MigrationStartupTask> logger,
- IFileService fileService,
- LightningClientFactoryService lightningClientFactoryService)
- {
- _migrationExecutors = migrationExecutors;
- _handlers = handlers;
- _DBContextFactory = dbContextFactory;
- _StoreRepository = storeRepository;
- _Settings = settingsRepository;
- _appService = appService;
- _payoutHandlers = payoutHandlers;
- _btcPayNetworkJsonSerializerSettings = btcPayNetworkJsonSerializerSettings;
- _lightningAddressService = lightningAddressService;
- _logger = logger;
- _fileService = fileService;
- _lightningClientFactoryService = lightningClientFactoryService;
- LightningOptions = lightningOptions;
- }
public async Task ExecuteAsync(CancellationToken cancellationToken = default)
{
try
{
await Migrate(cancellationToken);
- var settings = (await _Settings.GetSettingAsync<MigrationSettings>());
+ var settings = (await settingsRepository.GetSettingAsync<MigrationSettings>());
if (settings is null)
{
// If it is null, then it's the first run: let's skip all the migrations by setting flags to true
@@ -97,158 +43,58 @@ public async Task ExecuteAsync(CancellationToken cancellationToken = default)
{
prop.SetValue(settings, true);
}
- // Ensure these checks still get run
- settings.FileSystemStorageAsDefault = false;
- await _Settings.UpdateSetting(settings);
- await _Settings.UpdateSetting(new ThemeSettings());
- }
-
- if (!settings.PaymentMethodCriteria)
- {
- await MigratePaymentMethodCriteria();
- settings.PaymentMethodCriteria = true;
- await _Settings.UpdateSetting(settings);
- }
-
- if (!settings.TransitionToStoreBlobAdditionalData)
- {
- await TransitionToStoreBlobAdditionalData();
- settings.TransitionToStoreBlobAdditionalData = true;
- await _Settings.UpdateSetting(settings);
- }
-
- if (!settings.TransitionInternalNodeConnectionString)
- {
- await TransitionInternalNodeConnectionString();
- settings.TransitionInternalNodeConnectionString = true;
- await _Settings.UpdateSetting(settings);
- }
-
- if (!settings.MigrateU2FToFIDO2)
- {
- await MigrateU2FToFIDO2();
- settings.MigrateU2FToFIDO2 = true;
- await _Settings.UpdateSetting(settings);
- }
- if (!settings.MigrateHotwalletProperty)
- {
- await MigrateHotwalletProperty();
- settings.MigrateHotwalletProperty = true;
- await _Settings.UpdateSetting(settings);
- }
- if (!settings.MigrateAppCustomOption)
- {
- await MigrateAppCustomOption();
- settings.MigrateAppCustomOption = true;
- await _Settings.UpdateSetting(settings);
- }
- if (!settings.MigratePayoutDestinationId)
- {
- await MigratePayoutDestinationId();
- settings.MigratePayoutDestinationId = true;
- await _Settings.UpdateSetting(settings);
- }
- if (!settings.AddInitialUserBlob)
- {
- await AddInitialUserBlob();
- settings.AddInitialUserBlob = true;
- await _Settings.UpdateSetting(settings);
- }
- if (!settings.LighingAddressSettingRename)
- {
- await MigrateLighingAddressSettingRename();
- settings.LighingAddressSettingRename = true;
- await _Settings.UpdateSetting(settings);
- }
- if (!settings.LighingAddressDatabaseMigration)
- {
- await MigrateLighingAddressDatabaseMigration();
- settings.LighingAddressDatabaseMigration = true;
- }
- if (!settings.AddStoreToPayout)
- {
- await MigrateAddStoreToPayout();
- settings.AddStoreToPayout = true;
- await _Settings.UpdateSetting(settings);
- }
- if (!settings.MigrateEmailServerDisableTLSCerts)
- {
- await MigrateEmailServerDisableTLSCerts();
- settings.MigrateEmailServerDisableTLSCerts = true;
- await _Settings.UpdateSetting(settings);
- }
- if (!settings.MigrateWalletColors)
- {
- await MigrateMigrateLabels();
- settings.MigrateWalletColors = true;
- await _Settings.UpdateSetting(settings);
- }
- if (!settings.FileSystemStorageAsDefault)
- {
- var storageSettings = await _Settings.GetSettingAsync<StorageSettings>();
- if (storageSettings is null)
+ if (await settingsRepository.GetSettingAsync<StorageSettings>() is null)
{
- storageSettings = new StorageSettings
+ await settingsRepository.UpdateSetting(new StorageSettings
{
Provider = StorageProvider.FileSystem,
Configuration = JObject.FromObject(new FileSystemStorageConfiguration())
- };
- await _Settings.UpdateSetting(storageSettings);
+ });
}
- settings.FileSystemStorageAsDefault = true;
- await _Settings.UpdateSetting(settings);
- }
- if (!settings.FixMappedDomainAppType)
- {
- await FixMappedDomainAppType();
- settings.FixMappedDomainAppType = true;
- }
- if (!settings.MigrateAppYmlToJson)
- {
- await MigrateAppYmlToJson();
- settings.MigrateAppYmlToJson = true;
- await _Settings.UpdateSetting(settings);
+ await settingsRepository.UpdateSetting(new ThemeSettings());
+ await settingsRepository.UpdateSetting(settings);
}
+
if (!settings.MigrateToStoreConfig)
{
await MigrateToStoreConfig();
settings.MigrateToStoreConfig = true;
- await _Settings.UpdateSetting(settings);
+ await settingsRepository.UpdateSetting(settings);
}
if (!settings.MigrateBlockExplorerLinks)
{
await MigrateBlockExplorerLinks();
settings.MigrateBlockExplorerLinks = true;
- await _Settings.UpdateSetting(settings);
+ await settingsRepository.UpdateSetting(settings);
}
if (!settings.MigrateStoreExcludedPaymentMethods)
{
await MigrateStoreExcludedPaymentMethods();
settings.MigrateStoreExcludedPaymentMethods = true;
- await _Settings.UpdateSetting(settings);
+ await settingsRepository.UpdateSetting(settings);
}
if (!settings.MigrateOldDerivationSchemes)
{
await MigrateOldDerivationSchemes();
settings.MigrateOldDerivationSchemes = true;
- await _Settings.UpdateSetting(settings);
+ await settingsRepository.UpdateSetting(settings);
}
- foreach (var executor in _migrationExecutors)
+ foreach (var executor in migrationExecutors)
{
await executor.Execute(cancellationToken);
}
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error on the MigrationStartupTask");
+ logger.LogError(ex, "Error on the MigrationStartupTask");
throw;
}
}
private async Task MigrateOldDerivationSchemes()
{
- await using var ctx = _DBContextFactory.CreateContext();
+ await using var ctx = dbContextFactory.CreateContext();
var stores = await ctx.Stores.ToArrayAsync();
foreach (var store in stores)
{
@@ -259,7 +105,7 @@ private async Task MigrateOldDerivationSchemes()
continue;
foreach (var prop in strategies.Properties())
{
- var h = _handlers.TryGet(new PaymentMethodId(prop.Name));
+ var h = handlers.TryGet(new PaymentMethodId(prop.Name));
if (h is not BitcoinLikePaymentHandler bh ||
prop.Value is not JValue { Type: JTokenType.String, Value: string v })
continue;
@@ -273,7 +119,7 @@ private async Task MigrateOldDerivationSchemes()
private async Task MigrateStoreExcludedPaymentMethods()
{
- await using var ctx = _DBContextFactory.CreateContext();
+ await using var ctx = dbContextFactory.CreateContext();
var stores = await ctx.Stores.ToArrayAsync();
foreach (var store in stores)
{
@@ -294,7 +140,7 @@ private async Task MigrateStoreExcludedPaymentMethods()
private async Task MigrateBlockExplorerLinks()
{
- await using var ctx = _DBContextFactory.CreateContext();
+ await using var ctx = dbContextFactory.CreateContext();
var settings = await ctx.Settings.Where(s => s.Id == "BTCPayServer.Services.PoliciesSettings").FirstOrDefaultAsync();
if (settings is null)
return;
@@ -316,7 +162,7 @@ private async Task MigrateBlockExplorerLinks()
private async Task MigrateToStoreConfig()
{
- await using var ctx = _DBContextFactory.CreateContext();
+ await using var ctx = dbContextFactory.CreateContext();
var stores = await ctx.Stores.ToArrayAsync();
foreach (var store in stores)
{
@@ -359,587 +205,17 @@ private async Task MigrateToStoreConfig()
await ctx.SaveChangesAsync();
}
-
- private async Task FixMappedDomainAppType()
- {
- await using var ctx = _DBContextFactory.CreateContext();
- var setting = await ctx.Settings.FirstOrDefaultAsync(s => s.Id == "BTCPayServer.Services.PoliciesSettings");
- if (setting?.Value is null)
- return;
- string MapToString(int v)
- {
- return v switch
- {
- 0 => "PointOfSale",
- 1 => "Crowdfund",
- _ => throw new NotSupportedException()
- };
- }
- var data = JsonParser.ParseObject(setting.Value);
- if (data["RootAppType"]?.Type is JTokenType.Integer)
- {
- var v = data["RootAppType"].Value<int>();
- data["RootAppType"] = new JValue(MapToString(v));
- }
- var arr = data["DomainToAppMapping"] as JArray;
- if (arr != null)
- {
- foreach (var map in arr)
- {
- if (map["AppType"]?.Type is JTokenType.Integer)
- {
- var v = map["AppType"].Value<int>();
- map["AppType"] = new JValue(MapToString(v));
- }
- }
- }
- setting.Value = data.ToString();
- await ctx.SaveChangesAsync();
- }
- static async Task<string> GetMigrationState(ApplicationDbContext postgresContext)
- {
- var o = (await postgresContext.Settings.FromSqlRaw("SELECT \"Id\", \"Value\" FROM \"Settings\" WHERE \"Id\"='MigrationData'").AsNoTracking().FirstOrDefaultAsync())?.Value;
- if (o is null)
- return null;
- return JsonParser.ParseObject(o)["state"]?.Value<string>();
- }
- static async Task UpdateSequenceInvoiceSearch(ApplicationDbContext postgresContext)
- {
- await postgresContext.Database.ExecuteSqlRawAsync("SELECT SETVAL('\"InvoiceSearches_Id_seq\"', (SELECT max(\"Id\") FROM \"InvoiceSearches\"));");
- }
- private async Task MigrateAppYmlToJson()
- {
- await using var ctx = _DBContextFactory.CreateContext();
- var apps = await ctx.Apps.Where(data => CrowdfundAppType.AppType == data.AppType || PointOfSaleAppType.AppType == data.AppType)
- .ToListAsync();
- foreach (var app in apps)
- {
- switch (app.AppType)
- {
- case CrowdfundAppType.AppType:
- var cfSettings = app.GetSettings<CrowdfundSettings>();
- if (!string.IsNullOrEmpty(cfSettings?.PerksTemplate))
- {
- cfSettings.PerksTemplate = AppService.SerializeTemplate(ParsePOSYML(cfSettings?.PerksTemplate));
- app.SetSettings(cfSettings);
- }
- break;
- case PointOfSaleAppType.AppType:
- var pSettings = app.GetSettings<PointOfSaleSettings>();
- if (!string.IsNullOrEmpty(pSettings?.Template))
- {
- pSettings.Template = AppService.SerializeTemplate(ParsePOSYML(pSettings?.Template));
- app.SetSettings(pSettings);
- }
- break;
- }
- }
-
- await ctx.SaveChangesAsync();
-
- }
-
- public static AppItem[] ParsePOSYML(string yaml)
- {
- var items = new List<AppItem>();
- var stream = new YamlStream();
- if (string.IsNullOrEmpty(yaml))
- return items.ToArray();
-
- stream.Load(new StringReader(yaml));
-
- if (stream.Documents.FirstOrDefault()?.RootNode is not YamlMappingNode root)
- return items.ToArray();
- foreach (var posItem in root.Children)
- {
- var trimmedKey = ((YamlScalarNode)posItem.Key).Value?.Trim();
- if (string.IsNullOrEmpty(trimmedKey))
- {
- continue;
- }
-
- var currentItem = new AppItem
- {
- Id = trimmedKey,
- Title = trimmedKey,
- PriceType = AppItemPriceType.Fixed
- };
- var itemSpecs = (YamlMappingNode)posItem.Value;
- foreach (var spec in itemSpecs)
- {
- if (spec.Key is not YamlScalarNode { Value: string keyString } || string.IsNullOrEmpty(keyString))
- continue;
- var scalarValue = spec.Value as YamlScalarNode;
- switch (keyString)
- {
- case "title":
- currentItem.Title = scalarValue?.Value ?? trimmedKey;
- break;
- case "inventory":
- if (int.TryParse(scalarValue?.Value, out var inv))
- {
- currentItem.Inventory = inv;
- }
- break;
- case "description":
- currentItem.Description = scalarValue?.Value;
- break;
- case "image":
- currentItem.Image = scalarValue?.Value;
- break;
- case "price_type":
- case "custom":
- if (bool.TryParse(scalarValue?.Value, out var customBoolValue))
- {
- if (customBoolValue)
- {
- currentItem.PriceType = currentItem.Price is null or 0
- ? AppItemPriceType.Topup
- : AppItemPriceType.Minimum;
- }
- else
- {
- currentItem.PriceType = AppItemPriceType.Fixed;
- }
- }
- else if (Enum.TryParse<AppItemPriceType>(scalarValue?.Value, true,
- out var customPriceType))
- {
- currentItem.PriceType = customPriceType;
- }
-
- break;
- case "price":
- if (decimal.TryParse(scalarValue?.Value, out var price))
- {
- currentItem.Price = price;
- }
-
- break;
-
- case "buybuttontext":
- currentItem.BuyButtonText = scalarValue?.Value;
- break;
-
- case "disabled":
- if (bool.TryParse(scalarValue?.Value, out var disabled))
- {
- currentItem.Disabled = disabled;
- }
-
- break;
- }
- }
-
- items.Add(currentItem);
- }
-
- return items.ToArray();
- }
-
-#pragma warning disable CS0612 // Type or member is obsolete
-
- static WalletBlobInfo GetBlobInfo(WalletData walletData)
- {
- if (walletData.Blob == null || walletData.Blob.Length == 0)
- {
- return new WalletBlobInfo();
- }
- var blobInfo = JsonConvert.DeserializeObject<WalletBlobInfo>(ZipUtils.Unzip(walletData.Blob));
- return blobInfo;
- }
-
- private async Task MigrateMigrateLabels()
- {
- await using var ctx = _DBContextFactory.CreateContext();
- var wallets = await ctx.Wallets.AsNoTracking().ToArrayAsync();
- foreach (var wallet in wallets)
- {
- var blob = GetBlobInfo(wallet);
- HashSet<string> labels = new HashSet<string>(blob.LabelColors.Count);
- foreach (var label in blob.LabelColors)
- {
- var labelId = label.Key;
- if (labelId.StartsWith("{", StringComparison.OrdinalIgnoreCase))
- {
- try
- {
- labelId = JsonParser.ParseObject(label.Key)["value"].Value<string>();
- }
- catch
- {
- }
- }
- if (!labels.Add(labelId))
- continue;
- var obj = new JObject();
- obj.Add("color", label.Value);
- ctx.WalletObjects.Add(new WalletObjectData()
- {
- WalletId = wallet.Id,
- Type = WalletObjectData.Types.Label,
- Id = labelId,
- Data = obj.ToString()
- });
- }
- }
- await ctx.SaveChangesAsync();
- }
-#pragma warning restore CS0612 // Type or member is obsolete
-
- // In the past, if a server was considered local network, then we would disable TLS checks.
- // Now we don't do it anymore, as we have an explicit flag (DisableCertificateCheck) to control the behavior.
- // But we need to migrate old users that relied on the behavior before.
- private async Task MigrateEmailServerDisableTLSCerts()
- {
- await using var ctx = _DBContextFactory.CreateContext();
- var serverEmailSettings = await _Settings.GetSettingAsync<EmailSettings>();
- if (serverEmailSettings?.Server is String server)
- {
- serverEmailSettings.DisableCertificateCheck = Extensions.IsLocalNetwork(server);
- if (serverEmailSettings.DisableCertificateCheck)
- await _Settings.UpdateSetting(serverEmailSettings);
- }
- var stores = await ctx.Stores.ToArrayAsync();
- foreach (var store in stores)
- {
- var storeBlob = store.GetStoreBlob();
- if (storeBlob.EmailSettings?.Server is String storeServer)
- {
- storeBlob.EmailSettings.DisableCertificateCheck = Extensions.IsLocalNetwork(storeServer);
- if (storeBlob.EmailSettings.DisableCertificateCheck)
- store.SetStoreBlob(storeBlob);
- }
- }
- await ctx.SaveChangesAsync();
- }
-
- 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
- }
- .SetBlob(new LightningAddressDataBlob()
- {
- Max = val.Max,
- Min = val.Min,
- CurrencyCode = val.CurrencyCode
- }), ctx);
- }
- }
- }
-
- await ctx.SaveChangesAsync();
- await _Settings.UpdateSetting<object>(null, nameof(UILNURLController.LightningAddressSettings));
- }
-
- private async Task MigrateLighingAddressSettingRename()
- {
- var old = await _Settings.GetSettingAsync<UILNURLController.LightningAddressSettings>("BTCPayServer.LNURLController+LightningAddressSettings");
- if (old is not null)
- {
- await _Settings.UpdateSetting(old, nameof(UILNURLController.LightningAddressSettings));
- }
- }
-
- private async Task MigrateAddStoreToPayout()
- {
- await using var ctx = _DBContextFactory.CreateContext();
-
- await ctx.Database.ExecuteSqlRawAsync(@"
-WITH cte AS (
-SELECT DISTINCT p.""Id"", pp.""StoreId"" FROM ""Payouts"" p
-JOIN ""PullPayments"" pp ON pp.""Id"" = p.""PullPaymentDataId""
-WHERE p.""StoreDataId"" IS NULL
-)
-UPDATE ""Payouts"" p
-SET ""StoreDataId""=cte.""StoreId""
-FROM cte
-WHERE cte.""Id""=p.""Id""
-");
- }
-
- private async Task AddInitialUserBlob()
- {
- await using var ctx = _DBContextFactory.CreateContext();
- foreach (var user in await ctx.Users.AsQueryable().ToArrayAsync())
- {
- user.SetBlob(new UserBlob() { ShowInvoiceStatusChangeHint = true });
- }
- await ctx.SaveChangesAsync();
- }
-
- private async Task MigratePayoutDestinationId()
- {
- await using var ctx = _DBContextFactory.CreateContext();
- foreach (var payoutData in await ctx.Payouts.AsQueryable().ToArrayAsync())
- {
- var pmi = payoutData.GetPayoutMethodId();
- if (pmi is null)
- {
- continue;
- }
- var handler = _payoutHandlers
- .TryGet(pmi);
- if (handler is null)
- {
- continue;
- }
- var claim = await handler?.ParseClaimDestination(payoutData.GetBlob(_btcPayNetworkJsonSerializerSettings).Destination, default);
- payoutData.DedupId = claim.destination?.Id;
- }
- await ctx.SaveChangesAsync();
- }
-
- private async Task MigrateAppCustomOption()
- {
- await using var ctx = _DBContextFactory.CreateContext();
- foreach (var app in await ctx.Apps.Include(data => data.StoreData).AsQueryable().ToArrayAsync())
- {
- switch (app.AppType)
- {
- case CrowdfundAppType.AppType:
- var settings1 = app.GetSettings<CrowdfundSettings>();
- if (string.IsNullOrEmpty(settings1.TargetCurrency))
- {
- settings1.TargetCurrency = app.StoreData.GetStoreBlob().DefaultCurrency;
- app.SetSettings(settings1);
- }
- break;
-
- case PointOfSaleAppType.AppType:
-
- var settings2 = app.GetSettings<PointOfSaleSettings>();
- if (string.IsNullOrEmpty(settings2.Currency))
- {
- settings2.Currency = app.StoreData.GetStoreBlob().DefaultCurrency;
- app.SetSettings(settings2);
- }
- break;
- }
- }
- await ctx.SaveChangesAsync();
- }
-
- private async Task MigrateHotwalletProperty()
- {
- await using var ctx = _DBContextFactory.CreateContext();
- foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
- {
- foreach (var (id, paymentMethod) in store.GetPaymentMethodConfigs<DerivationSchemeSettings>(_handlers))
- {
- paymentMethod.IsHotWallet = paymentMethod.Source == "NBXplorer";
- if (paymentMethod.IsHotWallet)
- {
- paymentMethod.Source = "NBXplorerGenerated";
- store.SetPaymentMethodConfig(_handlers[id], paymentMethod);
- }
- }
- }
- await ctx.SaveChangesAsync();
- }
-
- private async Task MigrateU2FToFIDO2()
- {
- await using var ctx = _DBContextFactory.CreateContext();
- var u2fDevices = await ctx.U2FDevices.ToListAsync();
- foreach (U2FDevice u2FDevice in u2fDevices)
- {
- var fido2 = new Fido2Credential()
- {
- ApplicationUserId = u2FDevice.ApplicationUserId,
- Name = u2FDevice.Name,
- Type = Fido2Credential.CredentialType.FIDO2
- };
- fido2.SetBlob(new Fido2CredentialBlob()
- {
- SignatureCounter = (uint)u2FDevice.Counter,
- PublicKey = CreatePublicKeyFromU2fRegistrationData(u2FDevice.PublicKey).Encode(),
- UserHandle = u2FDevice.KeyHandle,
- Descriptor = new PublicKeyCredentialDescriptor(u2FDevice.KeyHandle)
- });
-
- await ctx.AddAsync(fido2);
-
- ctx.Remove(u2FDevice);
- }
- await ctx.SaveChangesAsync();
- }
- //from https://github.com/abergs/fido2-net-lib/blob/0fa7bb4b4a1f33f46c5f7ca4ee489b47680d579b/Test/ExistingU2fRegistrationDataTests.cs#L70
- private static CborMap CreatePublicKeyFromU2fRegistrationData(byte[] publicKeyData)
- {
- var x = new byte[32];
- var y = new byte[32];
- Buffer.BlockCopy(publicKeyData, 1, x, 0, 32);
- Buffer.BlockCopy(publicKeyData, 33, y, 0, 32);
-
- var point = new ECPoint
- {
- X = x,
- Y = y,
- };
-
- var coseKey = new CborMap
- {
- { (long)COSE.KeyCommonParameter.KeyType, (long)COSE.KeyType.EC2 },
- { (long)COSE.KeyCommonParameter.Alg, -7L },
-
- { (long)COSE.KeyTypeParameter.Crv, (long)COSE.EllipticCurve.P256 },
-
- { (long)COSE.KeyTypeParameter.X, point.X },
- { (long)COSE.KeyTypeParameter.Y, point.Y }
- };
-
- return coseKey;
- }
-
- private async Task TransitionInternalNodeConnectionString()
- {
- var nodes = LightningOptions.Value.InternalLightningByCryptoCode.Values.Select(c => c.ToString()).ToHashSet();
- await using var ctx = _DBContextFactory.CreateContext();
- foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
- {
-#pragma warning disable CS0618 // Type or member is obsolete
- if (!string.IsNullOrEmpty(store.DerivationStrategy))
- {
- var noLabel = store.DerivationStrategy.Split('-')[0];
- JObject jObject = new JObject();
- jObject.Add("BTC", new JObject()
- {
- new JProperty("signingKey", noLabel),
- new JProperty("accountDerivation", store.DerivationStrategy),
- new JProperty("accountOriginal", store.DerivationStrategy),
- new JProperty("accountKeySettings", new JArray()
- {
- new JObject()
- {
- new JProperty("accountKey", noLabel)
- }
- })
- });
- store.DerivationStrategies = jObject.ToString();
- store.DerivationStrategy = null;
- }
- if (string.IsNullOrEmpty(store.DerivationStrategies))
- continue;
-
- var strats = JsonParser.ParseObject(store.DerivationStrategies);
- bool updated = false;
- foreach (var prop in strats.Properties().Where(p => IsLN(PaymentMethodId.Parse(p.Name))))
- {
- var method = ((JObject)prop.Value);
- var lightningCharge = method.Property("LightningChargeUrl", StringComparison.OrdinalIgnoreCase);
- var ln = method.Property("LightningConnectionString", StringComparison.OrdinalIgnoreCase);
- if (lightningCharge != null)
- {
- var chargeUrl = lightningCharge.Value.Value<string>();
- var usr = method.Property("Username", StringComparison.OrdinalIgnoreCase)?.Value.Value<string>();
- var pass = method.Property("Password", StringComparison.OrdinalIgnoreCase)?.Value.Value<string>();
- updated = true;
- if (chargeUrl != null)
- {
- var fullUri = new UriBuilder(chargeUrl)
- {
- UserName = usr,
- Password = pass
- }.Uri.AbsoluteUri;
- var newStr = $"type=charge;server={fullUri};allowinsecure=true";
- if (ln is null)
- {
- ln = new JProperty("LightningConnectionString", newStr);
- method.Add(ln);
- }
- else
- {
- ln.Value = newStr;
- }
- }
- foreach (var p in new[] { "Username", "Password", "LightningChargeUrl" })
- method.Property(p, StringComparison.OrdinalIgnoreCase)?.Remove();
- }
-
- var paymentId = method.Property("PaymentId", StringComparison.OrdinalIgnoreCase);
- if (paymentId != null)
- {
- paymentId.Remove();
- updated = true;
- }
-
- if (ln is null)
- continue;
- if (nodes.Contains(ln.Value.Value<string>()))
- {
- updated = true;
- ln.Value = null;
- if (!(method.Property("InternalNodeRef", StringComparison.OrdinalIgnoreCase) is JProperty internalNode))
- {
- internalNode = new JProperty("InternalNodeRef", null);
- method.Add(internalNode);
- }
- internalNode.Value = new JValue(LightningPaymentMethodConfig.InternalNode);
- }
- }
-
- if (updated)
- store.DerivationStrategies = strats.ToString();
-#pragma warning restore CS0618 // Type or member is obsolete
- }
- await ctx.SaveChangesAsync();
- }
-
private bool IsLN(PaymentMethodId paymentMethodId)
{
- return _handlers.TryGetValue(paymentMethodId, out var v) && v is LightningLikePaymentHandler;
+ return handlers.TryGetValue(paymentMethodId, out var v) && v is LightningLikePaymentHandler;
}
private bool IsChain(PaymentMethodId paymentMethodId)
{
- return _handlers.TryGetValue(paymentMethodId, out var v) && v is BitcoinLikePaymentHandler;
+ return handlers.TryGetValue(paymentMethodId, out var v) && v is BitcoinLikePaymentHandler;
}
private bool IsLNURL(PaymentMethodId paymentMethodId)
{
- return _handlers.TryGetValue(paymentMethodId, out var v) && v is LNURLPayPaymentHandler;
- }
-
- private async Task TransitionToStoreBlobAdditionalData()
- {
- await using var ctx = _DBContextFactory.CreateContext();
- foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
- {
- var blob = store.GetStoreBlob();
- blob.AdditionalData.Remove("walletKeyPathRoots");
- blob.AdditionalData.Remove("onChainMinValue");
- blob.AdditionalData.Remove("lightningMaxValue");
- blob.AdditionalData.Remove("networkFeeDisabled");
- blob.AdditionalData.Remove("rateRules");
- store.SetStoreBlob(blob);
- }
-
- await ctx.SaveChangesAsync();
+ return handlers.TryGetValue(paymentMethodId, out var v) && v is LNURLPayPaymentHandler;
}
private async Task Migrate(CancellationToken cancellationToken)
@@ -951,94 +227,40 @@ private async Task Migrate(CancellationToken cancellationToken)
retry:
try
{
- _logger.LogInformation("Running the migration scripts...");
- var db = _DBContextFactory.CreateContext(o => o.CommandTimeout(((int)cancellationTimeout.TotalSeconds) + 1));
- await db.Database.MigrateAsync(timeout.Token);
- _logger.LogInformation("All migration scripts ran successfully");
+ logger.LogInformation("Running the migration scripts...");
+ await using var db = dbContextFactory.CreateContext(o => o.CommandTimeout(((int)cancellationTimeout.TotalSeconds) + 1));
+ try
+ {
+ await db.Database.MigrateAsync(timeout.Token);
+ }
+ catch (PostgresException ex) when (ex.SqlState == PostgresErrorCodes.DuplicateTable)
+ {
+ // Diagnose unsupported upgrades only after failure, without another query on normal startup.
+ const string baseline = "20231020135844_AddBoltcardsTable";
+ var applied = (await db.Database.GetAppliedMigrationsAsync(cts.Token)).ToArray();
+ if (!applied.Contains(baseline) && applied.Any(m => string.CompareOrdinal(m, baseline) < 0))
+ {
+ throw new ConfigException(
+ "This database requires an intermediate upgrade. " +
+ "Upgrade to BTCPay Server 1.12.x or 1.13.x first, then upgrade to this version.");
+ }
+ throw;
+ }
+ logger.LogInformation("All migration scripts ran successfully");
}
// Starting up
catch (ConfigException) { throw; }
catch (Exception ex) when (!cts.Token.IsCancellationRequested)
{
try
{
- _logger.LogWarning(ex, "Error while running migration scripts, retrying...");
+ logger.LogWarning(ex, "Error while running migration scripts, retrying...");
await Task.Delay(1000, cts.Token);
}
catch { }
goto retry;
}
}
}
-
- private async Task MigratePaymentMethodCriteria()
- {
- using var ctx = _DBContextFactory.CreateContext();
- foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
- {
- var blob = store.GetStoreBlob();
-
- CurrencyValue onChainMinValue = null;
- CurrencyValue lightningMaxValue = null;
- if (blob.AdditionalData.TryGetValue("onChainMinValue", out var onChainMinValueJToken))
- {
- CurrencyValue.TryParse(onChainMinValueJToken.Value<string>(), out onChainMinValue);
- blob.AdditionalData.Remove("onChainMinValue");
- }
- if (blob.AdditionalData.TryGetValue("lightningMaxValue", out var lightningMaxValueJToken))
- {
- CurrencyValue.TryParse(lightningMaxValueJToken.Value<string>(), out lightningMaxValue);
- blob.AdditionalData.Remove("lightningMaxValue");
- }
- blob.PaymentMethodCriteria = store.GetPaymentMethodConfigs().Select(c => c.Key).Select(paymentMethodId =>
- {
- var matchedFromBlob =
- blob.PaymentMethodCriteria?.SingleOrDefault(criteria => criteria.PaymentMethod == paymentMethodId && criteria.Value != null);
- return matchedFromBlob switch
- {
- null when _handlers.TryGet(paymentMethodId) is LightningLikePaymentHandler &&
- lightningMaxValue != null => new PaymentMethodCriteria()
- {
- Above = false,
- PaymentMethod = paymentMethodId,
- Value = lightningMaxValue
- },
- null when _handlers.TryGet(paymentMethodId) is BitcoinLikePaymentHandler &&
- onChainMinValue != null => new PaymentMethodCriteria()
- {
- Above = true,
- PaymentMethod = paymentMethodId,
- Value = onChainMinValue
- },
- _ => new PaymentMethodCriteria()
- {
- PaymentMethod = paymentMethodId,
- Above = matchedFromBlob?.Above ?? true,
- Value = matchedFromBlob?.Value
- }
- };
- }).ToList();
-
- store.SetStoreBlob(blob);
- }
-
- await ctx.SaveChangesAsync();
- }
-
- public class RateRule_Obsolete
- {
- public RateRule_Obsolete()
- {
- RuleName = "Multiplier";
- }
- public string RuleName { get; set; }
-
- public double Multiplier { get; set; }
-
- public decimal Apply(BTCPayNetworkBase network, decimal rate)
- {
- return rate * (decimal)Multiplier;
- }
- }
}
}
### BTCPayServer/Services/MigrationSettings.cs
@@ -1,30 +1,10 @@
-using Newtonsoft.Json;
-
namespace BTCPayServer.Services
{
public class MigrationSettings
{
- [JsonProperty("MigrateHotwalletProperty2")]
- public bool MigrateHotwalletProperty { get; set; }
- public bool MigrateU2FToFIDO2 { get; set; }
- public bool PaymentMethodCriteria { get; set; }
- public bool TransitionToStoreBlobAdditionalData { get; set; }
- public bool TransitionInternalNodeConnectionString { get; set; }
-
// Done in DbMigrationsHostedService
public int? MigratedInvoiceTextSearchPages { get; set; }
public int? MigratedTransactionLabels { get; set; }
- public bool MigrateAppCustomOption { get; set; }
- public bool MigratePayoutDestinationId { get; set; }
- public bool AddInitialUserBlob { get; set; }
- public bool LighingAddressSettingRename { get; set; }
- public bool LighingAddressDatabaseMigration { get; set; }
- public bool AddStoreToPayout { get; set; }
- public bool MigrateEmailServerDisableTLSCerts { get; set; }
- public bool MigrateWalletColors { get; set; }
- public bool FileSystemStorageAsDefault { get; set; }
- public bool FixMappedDomainAppType { get; set; }
- public bool MigrateAppYmlToJson { get; set; }
public bool MigrateToStoreConfig { get; set; }
public bool MigrateBlockExplorerLinks { get; set; }
public bool MigrateStoreExcludedPaymentMethods { get; set; }
### docs/maintainers/README.md
@@ -71,6 +71,40 @@ If Entity Framework cannot generate the required operation, add a timestamp-pref
Test both a fresh database and an upgrade from the previous schema when the change has meaningful data or compatibility risk.
+### Consolidated Migrations
+
+`DBScripts/000.Init.sql` contains the schema and seed data through
+`20231020135844_AddBoltcardsTable` (BTCPay Server 1.12.0). The migration keeps its
+original ID so existing databases skip the initialization script. Older instances
+must upgrade to a release containing that migration before upgrading to this code.
+Startup data migrations already present in 1.12.0 are also removed; first-run
+defaults remain part of initialization rather than migration flags.
+
+`MigrationStartupTask` diagnoses unsupported upgrades only after PostgreSQL
+reports a duplicate-table error. It then checks the applied migration history: if
+an older migration exists but the consolidated baseline is missing, startup stops
+with a `ConfigException` explaining that an intermediate upgrade to 1.12.x or
+1.13.x is required. This avoids the normal migration retry loop for unsupported
+databases without adding a query to successful startup. Other migration failures
+retain the existing retry behavior.
+
+To regenerate the baseline, create a temporary database test that migrates to the
+desired cutoff. Run it with `PLAYWRIGHT_HEADLESS=true` and detailed test output to
+obtain the database name logged by `DatabaseTester`. Use `pg_dump` in the test
+PostgreSQL container with `--schema-only --no-owner --no-privileges`, excluding
+`__EFMigrationsHistory`. Also export the `StoreRoles` seed rows with
+`--data-only --column-inserts`. Remove dump comments, session settings, psql
+meta-commands, and `public.` qualifiers before updating `000.Init.sql`.
+
+When moving the baseline forward, generate the dump before deleting the old
+migrations. `MigrateUntil` excludes the named migration, so select the first
+migration after the desired cutoff. Verify that both the baseline and final
+schemas match those produced by the original migration chain.
+Also update the baseline ID and intermediate-release guidance in
+`MigrationStartupTask`'s failure-path check. Verify fresh installations, upgrades
+with the baseline already applied, rejection of older databases, and retries for
+unrelated duplicate-table errors.
+
## Release Cycles
BTCPay Server uses three release types.Why this scored 29/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.