Consolidate migrations through BTCPay Server 2.0 (#7852)
What changed, and why it matters
This commit is a large database cleanup for the BTCPay Server 2.0 release. It merges many small database migration scripts into one consolidated starting schema, removes old one-off migration code, and updates related tests. It is not a security patch in the usual sense; it is infrastructure housekeeping that could affect how safely future upgrades happen.
Treat this as a high-risk maintenance change for upgrades rather than an exploitable vulnerability. Operators moving to BTCPay Server 2.0 should back up their database before upgrading and verify that all pre-2.0 migrations have already been applied. Developers should review the consolidated schema against production data edge cases and ensure tests adequately cover upgrade paths from the last 1.x release.
Security signals we found
Large deletion of migration code and tests reduces the codebase's upgrade safety net
Consolidated schema changes how fresh installs versus existing databases reach the 2.0 state
Removal of on-the-fly invoice/payment blob migration means pre-2.0 data must already be migrated before this version runs
Schema changes include dropping tables, altering primary keys, and converting blob columns to jsonb
No explicit security fix, CVE, or researcher attribution in commit message or diff
Evidence from the diff
The change consolidates all migrations up to BTCPay Server 2.0 into a single SQL initialization script (000.Init.sql) and deletes the individual EF Core migration classes and SQL scripts that previously applied step-by-step. It also removes the C# invoice/payment blob migration helpers (InvoiceData.Migration.cs, PaymentData.Migration.cs, MigrationExtensions.cs) and trims tests that exercised those removed migrations. The remaining on-the-fly migration is limited to payment requests. The schema changes include dropping the CustodianAccount table, removing PendingInvoices, normalizing AddressInvoices and Payments primary keys, adding Amount/Currency columns, converting several bytea blobs to jsonb, and updating StoreRoles seed data.
Changed components
BTCPayServer.Data/DBScripts/000.Init.sqlBTCPayServer.Data/Migrations/*.csBTCPayServer.Data/Data/InvoiceData.Migration.csBTCPayServer.Data/Data/PaymentData.Migration.csBTCPayServer.Data/Data/MigrationExtensions.csBTCPayServer.Data/Data/PaymentRequestData.Migration.csBTCPayServer/HostedServices/DbMigrationsHostedService.csBTCPayServer/Hosting/MigrationStartupTask.csBTCPayServer.Tests/DatabaseTests.csBTCPayServer.Tests/FastTests.csBTCPayServer.Tests/LightningTests.csBTCPayServer.Tests/PullPaymentsTests.csInspect captured patch +361 / −3722
### BTCPayServer.Data/DBScripts/000.Init.sql
@@ -1,9 +1,10 @@
--- Consolidated schema and seed data through 20231020135844_AddBoltcardsTable.
+-- Consolidated schema and seed data through 20240924065254_monitoredinvoices (2.0.0).
CREATE TABLE "AddressInvoices" (
"Address" text NOT NULL,
"InvoiceDataId" text,
- "CreatedTime" timestamp with time zone
+ "PaymentMethodId" text DEFAULT ''::text NOT NULL
);
+
CREATE TABLE "ApiKeys" (
"Id" character varying(50) NOT NULL,
"StoreId" character varying(50),
@@ -13,50 +14,58 @@ CREATE TABLE "ApiKeys" (
"Blob" bytea,
"Blob2" jsonb
);
+
CREATE TABLE "Apps" (
"Id" text NOT NULL,
"AppType" text,
"Created" timestamp with time zone NOT NULL,
"Name" text,
- "Settings" text,
+ "Settings" jsonb,
"StoreDataId" text,
"TagAllInvoices" boolean DEFAULT false NOT NULL,
"Archived" boolean DEFAULT false NOT NULL
);
+
CREATE TABLE "AspNetRoleClaims" (
"Id" integer NOT NULL,
"ClaimType" text,
"ClaimValue" text,
"RoleId" text NOT NULL
);
+
CREATE TABLE "AspNetRoles" (
"Id" text NOT NULL,
"ConcurrencyStamp" text,
"Name" character varying(256),
"NormalizedName" character varying(256)
);
+
CREATE TABLE "AspNetUserClaims" (
"Id" integer NOT NULL,
"ClaimType" text,
"ClaimValue" text,
"UserId" text NOT NULL
);
+
CREATE TABLE "AspNetUserLogins" (
"LoginProvider" character varying(255) NOT NULL,
"ProviderKey" character varying(255) NOT NULL,
"ProviderDisplayName" text,
"UserId" text NOT NULL
);
+
CREATE TABLE "AspNetUserRoles" (
"UserId" text NOT NULL,
"RoleId" text NOT NULL
);
+
CREATE TABLE "AspNetUserTokens" (
"UserId" text NOT NULL,
"LoginProvider" character varying(64) NOT NULL,
"Name" character varying(64) NOT NULL,
"Value" text
);
+
CREATE TABLE "AspNetUsers" (
"Id" text NOT NULL,
"AccessFailedCount" integer NOT NULL,
@@ -77,16 +86,11 @@ CREATE TABLE "AspNetUsers" (
"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
+ "Blob2" jsonb,
+ "Approved" boolean DEFAULT false NOT NULL,
+ "RequiresApproval" boolean DEFAULT false NOT NULL
);
+
CREATE TABLE "Fido2Credentials" (
"Id" text NOT NULL,
"Name" text,
@@ -95,64 +99,71 @@ CREATE TABLE "Fido2Credentials" (
"Type" integer NOT NULL,
"Blob2" jsonb
);
+
CREATE TABLE "Files" (
"Id" text NOT NULL,
"FileName" text,
"StorageFileName" text,
"Timestamp" timestamp with time zone NOT NULL,
"ApplicationUserId" 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,
"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,
"Blob" bytea,
"Created" timestamp with time zone NOT NULL,
- "CustomerEmail" text,
"ExceptionStatus" text,
- "ItemCode" text,
- "OrderId" text,
"Status" text,
"StoreDataId" text,
"Archived" boolean DEFAULT false NOT NULL,
- "CurrentRefundId" text,
- "Blob2" jsonb
+ "Blob2" jsonb,
+ "Amount" numeric,
+ "Currency" text
);
+
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,
@@ -162,17 +173,20 @@ CREATE TABLE "Notifications" (
"Blob" bytea,
"Blob2" jsonb
);
+
CREATE TABLE "OffchainTransactions" (
"Id" character varying(64) NOT NULL,
"Blob" bytea
);
+
CREATE TABLE "PairedSINData" (
"Id" text NOT NULL,
"Label" text,
"PairingTime" timestamp with time zone NOT NULL,
"SIN" text,
"StoreDataId" text
);
+
CREATE TABLE "PairingCodes" (
"Id" text NOT NULL,
"DateCreated" timestamp with time zone NOT NULL,
@@ -183,9 +197,11 @@ 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,
@@ -195,73 +211,90 @@ CREATE TABLE "PaymentRequests" (
"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,
"Blob2" jsonb,
- "Type" text
+ "PaymentMethodId" text NOT NULL,
+ "Amount" numeric,
+ "Created" timestamp with time zone,
+ "Currency" text,
+ "Status" text
);
+
CREATE TABLE "PayoutProcessors" (
"Id" text NOT NULL,
"StoreId" text,
- "PaymentMethod" text,
+ "PayoutMethodId" 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
+ "PayoutMethodId" character varying(20) CONSTRAINT "Payouts_PaymentMethodId_not_null" NOT NULL,
+ "DedupId" text,
+ "Blob" jsonb,
+ "Proof" jsonb,
+ "StoreDataId" text,
+ "Currency" text NOT NULL,
+ "Amount" numeric,
+ "OriginalAmount" numeric NOT NULL,
+ "OriginalCurrency" text NOT NULL
);
+
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
+ "Blob" jsonb,
+ "Currency" text NOT NULL,
+ "Limit" numeric NOT NULL
);
+
CREATE TABLE "Refunds" (
"InvoiceDataId" text NOT NULL,
"PullPaymentDataId" text NOT NULL
);
+
CREATE TABLE "Settings" (
"Id" text NOT NULL,
"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,
"DerivationStrategy" text,
@@ -274,6 +307,7 @@ CREATE TABLE "Stores" (
"DefaultCrypto" text,
"Archived" boolean DEFAULT false NOT NULL
);
+
CREATE TABLE "U2FDevices" (
"Id" text NOT NULL,
"Name" text,
@@ -283,11 +317,13 @@ CREATE TABLE "U2FDevices" (
"Counter" integer NOT NULL,
"ApplicationUserId" text
);
+
CREATE TABLE "UserStore" (
"ApplicationUserId" text NOT NULL,
"StoreDataId" text NOT NULL,
"Role" text
);
+
CREATE TABLE "WalletObjectLinks" (
"WalletId" text NOT NULL,
"AType" text NOT NULL,
@@ -296,264 +332,493 @@ CREATE TABLE "WalletObjectLinks" (
"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,
"Labels" text,
"Blob" bytea
);
+
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
);
+
+CREATE TABLE lang_dictionaries (
+ dict_id text NOT NULL,
+ fallback text,
+ source text,
+ metadata jsonb
+);
+
+CREATE TABLE lang_translations (
+ dict_id text NOT NULL,
+ sentence text NOT NULL,
+ translation text NOT NULL
+);
+
+CREATE VIEW translations AS
+ WITH RECURSIVE translations_with_paths AS (
+ SELECT d.dict_id,
+ t.sentence,
+ t.translation,
+ ARRAY[d.dict_id] AS path
+ FROM (lang_translations t
+ JOIN lang_dictionaries d USING (dict_id))
+ UNION ALL
+ SELECT d.dict_id,
+ t.sentence,
+ t.translation,
+ (d.dict_id || t.path)
+ FROM (translations_with_paths t
+ JOIN lang_dictionaries d ON ((d.fallback = t.dict_id)))
+ ), ranked_translations AS (
+ SELECT translations_with_paths.dict_id,
+ translations_with_paths.sentence,
+ translations_with_paths.translation,
+ translations_with_paths.path,
+ row_number() OVER (PARTITION BY translations_with_paths.dict_id, translations_with_paths.sentence ORDER BY (array_length(translations_with_paths.path, 1))) AS rn
+ FROM translations_with_paths
+ )
+ SELECT dict_id,
+ sentence,
+ translation,
+ path
+ FROM ranked_translations
+ WHERE (rn = 1);
+
+COMMENT ON VIEW translations IS 'Compute the translation for all sentences for all dictionaries, taking into account fallbacks';
+
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");
+ ADD CONSTRAINT "PK_AddressInvoices" PRIMARY KEY ("Address", "PaymentMethodId");
+
ALTER TABLE ONLY "ApiKeys"
ADD CONSTRAINT "PK_ApiKeys" PRIMARY KEY ("Id");
+
ALTER TABLE ONLY "Apps"
ADD CONSTRAINT "PK_Apps" PRIMARY KEY ("Id");
+
ALTER TABLE ONLY "AspNetRoleClaims"
ADD CONSTRAINT "PK_AspNetRoleClaims" PRIMARY KEY ("Id");
+
ALTER TABLE ONLY "AspNetRoles"
ADD CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id");
+
ALTER TABLE ONLY "AspNetUserClaims"
ADD CONSTRAINT "PK_AspNetUserClaims" PRIMARY KEY ("Id");
+
ALTER TABLE ONLY "AspNetUserLogins"
ADD CONSTRAINT "PK_AspNetUserLogins" PRIMARY KEY ("LoginProvider", "ProviderKey");
+
ALTER TABLE ONLY "AspNetUserRoles"
ADD CONSTRAINT "PK_AspNetUserRoles" PRIMARY KEY ("UserId", "RoleId");
+
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 "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");
+ ADD CONSTRAINT "PK_Payments" PRIMARY KEY ("Id", "PaymentMethodId");
+
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 "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);
+
+ALTER TABLE ONLY lang_dictionaries
+ ADD CONSTRAINT lang_dictionaries_pkey PRIMARY KEY (dict_id);
+
+ALTER TABLE ONLY lang_translations
+ ADD CONSTRAINT lang_translations_pkey PRIMARY KEY (dict_id, sentence);
+
+CREATE FUNCTION get_itemcode(invoice_blob jsonb) RETURNS text
+ LANGUAGE sql IMMUTABLE
+ AS $$
+ SELECT invoice_blob->'metadata'->>'itemCode';
+$$;
+
+CREATE FUNCTION get_orderid(invoice_blob jsonb) RETURNS text
+ LANGUAGE sql IMMUTABLE
+ AS $$
+ SELECT invoice_blob->'metadata'->>'orderId';
+$$;
+
+CREATE FUNCTION get_prompt(invoice_blob jsonb, payment_method_id text) RETURNS jsonb
+ LANGUAGE sql IMMUTABLE
+ AS $$
+ SELECT invoice_blob->'prompts'->payment_method_id
+$$;
+
+CREATE FUNCTION is_pending(status text) RETURNS boolean
+ LANGUAGE sql IMMUTABLE
+ AS $$
+ SELECT status = 'Processing' OR status = 'New';
+$$;
+
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");
+
CREATE INDEX "IX_ApiKeys_UserId" ON "ApiKeys" USING btree ("UserId");
+
CREATE INDEX "IX_Apps_StoreDataId" ON "Apps" USING btree ("StoreDataId");
+
CREATE INDEX "IX_AspNetRoleClaims_RoleId" ON "AspNetRoleClaims" USING btree ("RoleId");
+
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_InvoiceEvents_InvoiceDataId" ON "InvoiceEvents" USING btree ("InvoiceDataId");
+
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_Metadata_ItemCode" ON "Invoices" USING btree (get_itemcode("Blob2")) WHERE (get_itemcode("Blob2") IS NOT NULL);
+
+CREATE INDEX "IX_Invoices_Metadata_OrderId" ON "Invoices" USING btree (get_orderid("Blob2")) WHERE (get_orderid("Blob2") IS NOT NULL);
+
+CREATE INDEX "IX_Invoices_Pending" ON "Invoices" USING btree ((1)) WHERE is_pending("Status");
+
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_Payments_Pending" ON "Payments" USING btree ((1)) WHERE is_pending("Status");
+
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_DedupId_State" ON "Payouts" USING btree ("DedupId", "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"
ADD CONSTRAINT "FK_AddressInvoices_Invoices_InvoiceDataId" FOREIGN KEY ("InvoiceDataId") REFERENCES "Invoices"("Id") ON DELETE CASCADE;
+
ALTER TABLE ONLY "ApiKeys"
ADD CONSTRAINT "FK_ApiKeys_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE;
+
ALTER TABLE ONLY "ApiKeys"
ADD CONSTRAINT "FK_ApiKeys_Stores_StoreId" FOREIGN KEY ("StoreId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+
ALTER TABLE ONLY "Apps"
ADD CONSTRAINT "FK_Apps_Stores_StoreDataId" FOREIGN KEY ("StoreDataId") REFERENCES "Stores"("Id") ON DELETE CASCADE;
+
ALTER TABLE ONLY "AspNetRoleClaims"
ADD CONSTRAINT "FK_AspNetRoleClaims_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles"("Id") ON DELETE CASCADE;
+
ALTER TABLE ONLY "AspNetUserClaims"
ADD CONSTRAINT "FK_AspNetUserClaims_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE;
+
ALTER TABLE ONLY "AspNetUserLogins"
ADD CONSTRAINT "FK_AspNetUserLogins_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE;
+
ALTER TABLE ONLY "AspNetUserRoles"
ADD CONSTRAINT "FK_AspNetUserRoles_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles"("Id") ON DELETE CASCADE;
+
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 "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 "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 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}');
+
+ALTER TABLE ONLY lang_dictionaries
+ ADD CONSTRAINT lang_dictionaries_fallback_fkey FOREIGN KEY (fallback) REFERENCES lang_dictionaries(dict_id) ON UPDATE CASCADE ON DELETE SET NULL;
+
+ALTER TABLE ONLY lang_translations
+ ADD CONSTRAINT lang_translations_dict_id_fkey FOREIGN KEY (dict_id) REFERENCES lang_dictionaries(dict_id) ON UPDATE CASCADE ON DELETE CASCADE;
+
+CREATE FUNCTION get_monitored_invoices(arg_payment_method_id text, include_non_activated boolean) RETURNS TABLE(invoice_id text, payment_id text, payment_method_id text)
+ LANGUAGE sql STABLE
+ AS $$
+WITH cte AS (
+SELECT i."Id" invoice_id, p."Id" payment_id, p."PaymentMethodId" payment_method_id FROM "Invoices" i LEFT JOIN "Payments" p ON i."Id" = p."InvoiceDataId"
+ WHERE is_pending(i."Status")
+UNION ALL
+SELECT i."Id" invoice_id, p."Id" payment_id, p."PaymentMethodId" payment_method_id FROM "Invoices" i INNER JOIN "Payments" p ON i."Id" = p."InvoiceDataId"
+ WHERE is_pending(p."Status") AND NOT is_pending(i."Status"))
+SELECT cte.* FROM cte
+JOIN "Invoices" i ON cte.invoice_id=i."Id"
+LEFT JOIN "Payments" p ON cte.payment_id=p."Id" AND cte.payment_method_id=p."PaymentMethodId"
+WHERE (p."PaymentMethodId" IS NOT NULL AND p."PaymentMethodId" = arg_payment_method_id) OR
+ (p."PaymentMethodId" IS NULL AND get_prompt(i."Blob2", arg_payment_method_id) IS NOT NULL AND
+ (include_non_activated IS TRUE OR (get_prompt(i."Blob2", arg_payment_method_id)->'inactive')::BOOLEAN IS NOT TRUE));
+$$;
+
+INSERT INTO lang_dictionaries (dict_id, source) VALUES ('English', 'Default');
+
+INSERT INTO "StoreRoles" ("Id", "StoreDataId", "Role", "Permissions") VALUES ('Manager', NULL, 'Manager', '{btcpay.store.canviewstoresettings,btcpay.store.canmodifyinvoices,btcpay.store.webhooks.canmodifywebhooks,btcpay.store.canmodifypaymentrequests,btcpay.store.canmanagepullpayments,btcpay.store.canmanagepayouts}');
+INSERT INTO "StoreRoles" ("Id", "StoreDataId", "Role", "Permissions") VALUES ('Employee', NULL, 'Employee', '{btcpay.store.canmodifyinvoices,btcpay.store.canmodifypaymentrequests,btcpay.store.cancreatenonapprovedpullpayments,btcpay.store.canviewpayouts,btcpay.store.canviewpullpayments}');
+INSERT INTO "StoreRoles" ("Id", "StoreDataId", "Role", "Permissions") VALUES ('Guest', NULL, 'Guest', '{btcpay.store.canmodifyinvoices,btcpay.store.canviewpaymentrequests,btcpay.store.canviewpullpayments,btcpay.store.canviewpayouts}');
+INSERT INTO "StoreRoles" ("Id", "StoreDataId", "Role", "Permissions") VALUES ('Owner', NULL, 'Owner', '{btcpay.store.canmodifystoresettings}');
### BTCPayServer.Data/DBScripts/001.InvoiceFunctions.sql
@@ -1,12 +0,0 @@
-CREATE OR REPLACE FUNCTION get_orderid(invoice_blob jsonb)
-RETURNS text AS $$
- SELECT invoice_blob->'metadata'->>'orderId';
-$$ LANGUAGE sql IMMUTABLE;
-
-CREATE OR REPLACE FUNCTION get_itemcode(invoice_blob jsonb)
-RETURNS text AS $$
- SELECT invoice_blob->'metadata'->>'itemCode';
-$$ LANGUAGE sql IMMUTABLE;
-
-CREATE INDEX IF NOT EXISTS "IX_Invoices_Metadata_OrderId" ON "Invoices" (get_orderid("Blob2")) WHERE get_orderid("Blob2") IS NOT NULL;
-CREATE INDEX IF NOT EXISTS "IX_Invoices_Metadata_ItemCode" ON "Invoices" (get_itemcode("Blob2")) WHERE get_itemcode("Blob2") IS NOT NULL;
### BTCPayServer.Data/DBScripts/002.RefactorPayouts.sql
@@ -1,62 +0,0 @@
--- Rename column
-ALTER TABLE "Payouts" RENAME COLUMN "PaymentMethodId" TO "PayoutMethodId";
-
--- Add Currency column, guessed from the PaymentMethodId
-ALTER TABLE "Payouts" ADD COLUMN "Currency" TEXT;
-UPDATE "Payouts" SET
- "Currency" = split_part("PayoutMethodId", '_', 1),
- "PayoutMethodId"=
- CASE
- WHEN ("Blob"->>'Amount')::NUMERIC < 0 THEN 'TOPUP'
- WHEN split_part("PayoutMethodId", '_', 2) = 'LightningLike' THEN split_part("PayoutMethodId", '_', 1) || '-LN'
- ELSE split_part("PayoutMethodId", '_', 1) || '-CHAIN'
- END;
-ALTER TABLE "Payouts" ALTER COLUMN "Currency" SET NOT NULL;
-
--- Remove Currency and Limit from PullPayment Blob, and put it into the columns in the table
-ALTER TABLE "PullPayments" ADD COLUMN "Currency" TEXT;
-UPDATE "PullPayments" SET "Currency" = "Blob"->>'Currency';
-ALTER TABLE "PullPayments" ALTER COLUMN "Currency" SET NOT NULL;
-ALTER TABLE "PullPayments" ADD COLUMN "Limit" NUMERIC;
-UPDATE "PullPayments" SET "Limit" = ("Blob"->>'Limit')::NUMERIC;
-ALTER TABLE "PullPayments" ALTER COLUMN "Limit" SET NOT NULL;
-
--- Remove unused properties, rename SupportedPaymentMethods, and fix legacy payment methods IDs
-UPDATE "PullPayments" SET
- "Blob" = jsonb_set(
- "Blob" - 'SupportedPaymentMethods' - 'Limit' - 'Currency' - 'Period',
- '{SupportedPayoutMethods}',
- (SELECT jsonb_agg(to_jsonb(
- CASE
- WHEN split_part(value::TEXT, '_', 2) = 'LightningLike' THEN split_part(value::TEXT, '_', 1) || '-LN'
- ELSE split_part(value::TEXT, '_', 1) || '-CHAIN'
- END))
- FROM jsonb_array_elements_text("Blob"->'SupportedPaymentMethods') AS value
- ));
-
---Remove "Amount" and "CryptoAmount" from Payout Blob, and put it into the columns in the table
--- Respectively "OriginalAmount" and "Amount"
-
-ALTER TABLE "Payouts" ADD COLUMN "Amount" NUMERIC;
-UPDATE "Payouts" SET "Amount" = ("Blob"->>'CryptoAmount')::NUMERIC;
-
-ALTER TABLE "Payouts" ADD COLUMN "OriginalAmount" NUMERIC;
-UPDATE "Payouts" SET "OriginalAmount" = ("Blob"->>'Amount')::NUMERIC;
-ALTER TABLE "Payouts" ALTER COLUMN "OriginalAmount" SET NOT NULL;
-
-ALTER TABLE "Payouts" ADD COLUMN "OriginalCurrency" TEXT;
-
-
-UPDATE "Payouts" p
-SET
- "OriginalCurrency" = "Currency",
- "Blob" = "Blob" - 'Amount' - 'CryptoAmount'
-WHERE "PullPaymentDataId" IS NULL AND "OriginalCurrency" IS NULL;
-
-UPDATE "Payouts" p
-SET
- "OriginalCurrency" = pp."Currency"
-FROM "PullPayments" pp
-WHERE "OriginalCurrency" IS NULL AND pp."Id"=p."PullPaymentDataId";
-
-ALTER TABLE "Payouts" ALTER COLUMN "OriginalCurrency" SET NOT NULL;
### BTCPayServer.Data/DBScripts/003.RefactorPendingInvoicesPayments.sql
@@ -1,9 +0,0 @@
-CREATE OR REPLACE FUNCTION is_pending(status TEXT)
-RETURNS BOOLEAN AS $$
- SELECT status = 'Processing' OR status = 'New';
-$$ LANGUAGE sql IMMUTABLE;
-
-CREATE INDEX "IX_Invoices_Pending" ON "Invoices"((1)) WHERE is_pending("Status");
-CREATE INDEX "IX_Payments_Pending" ON "Payments"((1)) WHERE is_pending("Status");
-DROP TABLE "PendingInvoices";
-ANALYZE "Invoices";
### BTCPayServer.Data/DBScripts/004.MonitoredInvoices.sql
@@ -1,23 +0,0 @@
-CREATE OR REPLACE FUNCTION get_prompt(invoice_blob JSONB, payment_method_id TEXT)
-RETURNS JSONB AS $$
- SELECT invoice_blob->'prompts'->payment_method_id
-$$ LANGUAGE sql IMMUTABLE;
-
-
-CREATE OR REPLACE FUNCTION get_monitored_invoices(arg_payment_method_id TEXT, include_non_activated BOOLEAN)
-RETURNS TABLE (invoice_id TEXT, payment_id TEXT, payment_method_id TEXT) AS $$
-WITH cte AS (
--- Get all the invoices which are pending. Even if no payments.
-SELECT i."Id" invoice_id, p."Id" payment_id, p."PaymentMethodId" payment_method_id FROM "Invoices" i LEFT JOIN "Payments" p ON i."Id" = p."InvoiceDataId"
- WHERE is_pending(i."Status")
-UNION ALL
--- For invoices not pending, take all of those which have pending payments
-SELECT i."Id" invoice_id, p."Id" payment_id, p."PaymentMethodId" payment_method_id FROM "Invoices" i INNER JOIN "Payments" p ON i."Id" = p."InvoiceDataId"
- WHERE is_pending(p."Status") AND NOT is_pending(i."Status"))
-SELECT cte.* FROM cte
-JOIN "Invoices" i ON cte.invoice_id=i."Id"
-LEFT JOIN "Payments" p ON cte.payment_id=p."Id" AND cte.payment_method_id=p."PaymentMethodId"
-WHERE (p."PaymentMethodId" IS NOT NULL AND p."PaymentMethodId" = arg_payment_method_id) OR
- (p."PaymentMethodId" IS NULL AND get_prompt(i."Blob2", arg_payment_method_id) IS NOT NULL AND
- (include_non_activated IS TRUE OR (get_prompt(i."Blob2", arg_payment_method_id)->'inactive')::BOOLEAN IS NOT TRUE));
-$$ LANGUAGE SQL STABLE;
### BTCPayServer.Data/Data/InvoiceData.Migration.cs
@@ -1,365 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.DataAnnotations.Schema;
-using Newtonsoft.Json.Linq;
-using System.Linq;
-using System.Globalization;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Serialization;
-
-namespace BTCPayServer.Data
-{
- public partial class InvoiceData : MigrationInterceptor.IHasMigration
- {
- static HashSet<string> superflousProperties = new HashSet<string>()
- {
- "availableAddressHashes",
- "events",
- "refunds",
- "paidAmount",
- "historicalAddresses",
- "refundable",
- "status",
- "exceptionStatus",
- "storeId",
- "id",
- "txFee",
- "refundMail",
- "rate",
- "depositAddress",
- "currency",
- "price",
- "payments",
- "orderId",
- "buyerInformation",
- "productInformation",
- "derivationStrategy",
- "archived",
- "isUnderPaid",
- "requiresRefundEmail",
- "invoiceTime",
- "checkoutType",
- "customLogo",
- "customCSS"
- };
-
-#pragma warning disable CS0618 // Type or member is obsolete
- public bool TryMigrate()
- {
- if (Currency is not null)
- return false;
- if (Blob is not (null or { Length: 0 }))
- {
- Blob2 = MigrationExtensions.Unzip(Blob);
- Blob2 = MigrationExtensions.SanitizeJSON(Blob2);
- Blob = null;
- }
- var blob = JsonParser.ParseObject(Blob2);
- if (blob["cryptoData"]?["BTC"] is not (null or { Type: JTokenType.Null }))
- {
- blob.Move(["rate"], ["cryptoData", "BTC", "rate"]);
- blob.Move(["txFee"], ["cryptoData", "BTC", "txFee"]);
- }
- blob.Move(["customerEmail"], ["metadata", "buyerEmail"]);
- foreach (var prop in (blob["cryptoData"] as JObject)?.Properties()?.ToList() ?? [])
- {
- // We should only change data for onchain
- if (prop.Name.Contains('_', StringComparison.OrdinalIgnoreCase))
- {
- if (prop.Value is JObject pm)
- {
- pm.Remove("depositAddress");
- pm.Remove("feeRate");
- pm.Remove("txFee");
- }
- continue;
- }
- if (prop.Value is JObject o)
- {
- o.ConvertNumberToString("rate");
- if (o["paymentMethod"] is JObject pm)
- {
- if (pm["networkFeeRate"] is null)
- pm["networkFeeRate"] = o["feeRate"] ?? 0.0m;
- if (pm["networkFeeMode"] is JValue { Type: JTokenType.Integer, Value: 0 or 0L })
- pm.Remove("networkFeeMode");
- if (pm["networkFeeMode"] is JValue { Type: JTokenType.Integer, Value: 2 or 2L })
- pm["networkFeeRate"] = 0.0m;
- }
- }
- }
-
- var metadata = blob.Property("metadata")?.Value as JObject;
- if (metadata is null)
- {
- metadata = new JObject();
- blob.Add("metadata", metadata);
- }
- foreach (var prop in (blob["buyerInformation"] as JObject)?.Properties()?.ToList() ?? [])
- {
- if (prop.Value?.Value<string>() is not null)
- blob.Move(["buyerInformation", prop.Name], ["metadata", prop.Name]);
- }
- foreach (var prop in (blob["productInformation"] as JObject)?.Properties()?.ToList() ?? [])
- {
- if (prop.Name is "price" or "currency")
- blob.Move(["productInformation", prop.Name], [prop.Name]);
- else if (prop.Value?.Value<string>() is not null)
- blob.Move(["productInformation", prop.Name], ["metadata", prop.Name]);
- }
- blob.Move(["orderId"], ["metadata", "orderId"]);
- foreach (string prop in new string[] { "posData", "defaultLanguage", "notificationURL", "storeSupportUrl", "redirectURL" })
- {
- blob.RemoveIfNull(prop);
- }
- blob.Remove("notificationEmail");
- blob.RemoveIfValue<bool>("fullNotifications", false);
- if (blob["receiptOptions"] is JObject receiptOptions)
- {
- foreach (string prop in new string[] { "showQR", "enabled", "showPayments" })
- {
- receiptOptions.RemoveIfNull(prop);
- }
- }
-
- {
- if (blob.Property("paymentTolerance") is JProperty { Value: { Type: JTokenType.Float } pv } prop)
- {
- if (pv.Value<decimal>() == 0.0m)
- prop.Remove();
- }
- }
-
- var posData = blob.Move(["posData"], ["metadata", "posData"]);
- if (posData is not null && posData.Value?.Type is JTokenType.String)
- {
- try
- {
- posData.Value = JsonParser.ParseObject(posData.Value<string>());
- }
- catch
- {
- posData.Remove();
- }
- }
- if (posData?.Type is JTokenType.Null)
- posData.Remove();
-
- if (blob["derivationStrategies"] is JValue { Type: JTokenType.String } v)
- blob["derivationStrategies"] = JsonParser.ParseObject(v.Value<string>());
- if (blob["derivationStrategies"] is JObject derivations)
- {
- foreach (var prop in derivations.Properties().ToList())
- {
- // We should only change data for onchain
- if (prop.Name.Contains('_', StringComparison.OrdinalIgnoreCase))
- continue;
- if (prop.Value is JValue
- {
- Type: JTokenType.String,
- Value: String { Length: > 0 } val
- })
- {
- if (val[0] == '{')
- derivations[prop.Name] = JsonParser.ParseObject(val);
- else
- {
- if (val.Contains('-', StringComparison.OrdinalIgnoreCase))
- derivations[prop.Name] = new JObject() { ["accountDerivation"] = val };
- else
- derivations[prop.Name] = null;
- }
- }
- if (prop.Value is JObject derivation)
- {
- derivations[prop.Name] = derivation["accountDerivation"];
- }
- }
- }
-
- if (blob["derivationStrategies"] is null && blob["derivationStrategy"] is not null)
- {
- // If it's NBX derivation strategy, keep it. Else just give up, it might be Electrum format and we shouldn't support
- // that anymore in the backend for long...
- if (blob["derivationStrategy"]?.Value<string>().Contains('-', StringComparison.OrdinalIgnoreCase) is true)
- blob.Move(["derivationStrategy"], ["derivationStrategies", "BTC"]);
- else
- {
- blob.Remove("derivationStrategy");
- blob.Add("derivationStrategies", new JObject() { ["BTC"] = null });
- }
- }
-
-
- if (blob["type"]?.Value<string>() is "Standard")
- blob.Remove("type");
- foreach (var prop in new string[] { "extendedNotifications", "lazyPaymentMethods", "lazyPaymentMethods", "redirectAutomatically" })
- {
- if (blob[prop]?.Value<bool>() is false)
- blob.Remove(prop);
- }
-
- blob.ConvertNumberToString("price");
- Currency = blob["currency"].Value<string>().ToUpperInvariant();
- var isTopup = blob["type"]?.Value<string>() is "TopUp";
- var amount = decimal.Parse(blob["price"].Value<string>(), CultureInfo.InvariantCulture);
- Amount = isTopup && amount == 0 ? null : decimal.Parse(blob["price"].Value<string>(), CultureInfo.InvariantCulture);
- foreach (var prop in superflousProperties)
- blob.Property(prop)?.Remove();
- if (blob["speedPolicy"] is JValue { Type: JTokenType.Integer, Value: 0 or 0L })
- blob.Remove("speedPolicy");
- blob.TryAdd("internalTags", new JArray());
- blob.TryAdd("receiptOptions", new JObject());
-
- foreach (var prop in ((JObject)blob["cryptoData"]).Properties())
- {
- if (prop.Name.EndsWith("_LightningLike", StringComparison.OrdinalIgnoreCase) ||
- prop.Name.EndsWith("_LNURLPAY", StringComparison.OrdinalIgnoreCase))
- {
- if (prop.Value["paymentMethod"]?["PaymentHash"] is JObject)
- prop.Value["paymentMethod"]["PaymentHash"] = JValue.CreateNull();
- if (prop.Value["paymentMethod"]?["Preimage"] is JObject)
- prop.Value["paymentMethod"]["Preimage"] = JValue.CreateNull();
- }
- }
-
- foreach (var prop in ((JObject)blob["cryptoData"]).Properties())
- {
- var crypto = prop.Name.Split(['_', '-']).First();
- if (blob.Move(["cryptoData", prop.Name, "rate"], ["rates", crypto]) is not null)
- ((JObject)blob["rates"]).ConvertNumberToString(crypto);
- }
- blob.Move(["cryptoData"], ["prompts"]);
- var prompts = ((JObject)blob["prompts"]);
- foreach (var prop in prompts.Properties().ToList())
- {
- ((JObject)blob["prompts"]).RenameProperty(prop.Name, MigrationExtensions.MigratePaymentMethodId(prop.Name));
- }
- blob["derivationStrategies"] = blob["derivationStrategies"] ?? new JObject();
- foreach (var prop in ((JObject)blob["derivationStrategies"]).Properties().ToList())
- {
- ((JObject)blob["derivationStrategies"]).RenameProperty(prop.Name, MigrationExtensions.MigratePaymentMethodId(prop.Name));
- }
-
- foreach (var prop in prompts.Properties())
- {
- var prompt = prop.Value as JObject;
- if (prompt is null)
- continue;
- prompt["currency"] = prop.Name.Split('-').First();
- prompt.RemoveIfNull("depositAddress");
- prompt.RemoveIfNull("txFee");
- prompt.RemoveIfNull("feeRate");
-
- prompt.RenameProperty("depositAddress", "destination");
- prompt.RenameProperty("txFee", "paymentMethodFee");
-
- var divisibility = MigrationExtensions.GetDivisibility(prop.Name);
- prompt.Add("divisibility", divisibility);
- if (prompt["paymentMethodFee"] is { Type: JTokenType.Integer } paymentMethodFee)
- {
- prompt["paymentMethodFee"] = ((decimal)paymentMethodFee.Value<long>() / (decimal)Math.Pow(10, divisibility)).ToString(CultureInfo.InvariantCulture);
- prompt.RemoveIfValue<string>("paymentMethodFee", "0");
- }
- prompt.Move(["paymentMethod"], ["details"]);
- prompt.Move(["feeRate"], ["details", "recommendedFeeRate"]);
- prompt.Move(["details", "networkFeeRate"], ["details", "paymentMethodFeeRate"]);
- prompt.Move(["details", "networkFeeMode"], ["details", "feeMode"]);
- if ((prompt["details"]?["Activated"])?.Value<bool>() is bool activated)
- {
- ((JObject)prompt["details"]).Remove("Activated");
- prompt["inactive"] = !activated;
- prompt.RemoveIfValue<bool>("inactive", false);
- }
- if ((prompt["details"]?["activated"])?.Value<bool>() is bool activated2)
- {
- ((JObject)prompt["details"]).Remove("activated");
- prompt["inactive"] = !activated2;
- prompt.RemoveIfValue<bool>("inactive", false);
- }
- var details = prompt["details"] as JObject ?? new JObject();
- details.RemoveIfValue<bool>("payjoinEnabled", false);
- details.RemoveIfNull("feeMode");
- if (details["feeMode"] is not (null or { Type: JTokenType.Null }))
- {
- details["feeMode"] = details["feeMode"].Value<int>() switch
- {
- 1 => "Always",
- 2 => "Never",
- _ => null
- };
- details.RemoveIfNull("feeMode");
- }
-
- details.RemoveIfNull("BOLT11");
- details.RemoveIfNull("address");
- details.RemoveIfNull("Address");
- prompt.Move(["details", "BOLT11"], ["destination"]);
- prompt.Move(["details", "address"], ["destination"]);
- prompt.Move(["details", "Address"], ["destination"]);
- prompt.RenameProperty("Address", "destination");
- prompt.RenameProperty("BOLT11", "destination");
-
- details.Remove("LightningSupportedPaymentMethod");
- foreach (var o in detailsRemoveDefault)
- details.RemoveIfNull(o);
- details.RemoveIfValue<decimal>("recommendedFeeRate", 0.0m);
- details.RemoveIfValue<decimal>("paymentMethodFeeRate", 0.0m);
- if (prop.Name.EndsWith("-CHAIN"))
- blob.Move(["derivationStrategies", prop.Name], ["prompts", prop.Name, "details", "accountDerivation"]);
-
- var camel = new CamelCaseNamingStrategy();
- foreach (var p in details.Properties().ToList())
- {
- var camelName = camel.GetPropertyName(p.Name, false);
- if (camelName != p.Name)
- details.RenameProperty(p.Name, camelName);
- }
- }
-
- if (blob["defaultPaymentMethod"] is not (null or { Type : JTokenType.Null }))
- blob["defaultPaymentMethod"] = MigrationExtensions.MigratePaymentMethodId(blob["defaultPaymentMethod"].Value<string>());
- blob.Remove("derivationStrategies");
- Status = Status switch
- {
- "new" => "New",
- "paid" => "Processing",
- "complete" or "confirmed" => "Settled",
- "expired" => "Expired",
- null or "invalid" => "Invalid",
- _ => throw new NotSupportedException($"Unknown Status for invoice ({Status})")
- };
- ExceptionStatus = ExceptionStatus switch
- {
- "marked" => "Marked",
- "paidLate" => "PaidLate",
- "paidPartial" => "PaidPartial",
- "paidOver" => "PaidOver",
- null or "" => "",
- _ => throw new NotSupportedException($"Unknown ExceptionStatus for invoice ({ExceptionStatus})")
- };
- blob["version"] = 3;
- Blob2 = blob.ToString(Formatting.None);
- return true;
- }
-
- [NotMapped]
- public bool Migrated { get; set; }
- static string[] detailsRemoveDefault =
- [
- "paymentMethodFeeRate",
- "keyPath",
- "BOLT11",
- "NodeInfo",
- "Preimage",
- "InvoiceId",
- "PaymentHash",
- "ProvidedComment",
- "GeneratedBoltAmount",
- "ConsumedLightningAddress",
- "PayRequest"
- ];
-
-#pragma warning restore CS0618 // Type or member is obsolete
- }
-}
### BTCPayServer.Data/Data/MigrationExtensions.cs
@@ -1,173 +0,0 @@
-#nullable enable
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO.Compression;
-using System.IO;
-using System.Text;
-using Newtonsoft.Json.Linq;
-using Newtonsoft.Json.Serialization;
-
-namespace BTCPayServer.Data
-{
- public static class MigrationExtensions
- {
- public static JProperty? Move(this JObject blob, string[] pathFrom, string[] pathTo)
- {
- var from = GetProperty(blob, pathFrom, false);
- if (from is null)
- return null;
- var to = GetProperty(blob, pathTo, true);
- to!.Value = from.Value;
- from.Remove();
- return to;
- }
-
- public static void RenameProperty(this JObject o, string oldName, string newName)
- {
- var p = o.Property(oldName);
- if (p is null)
- return;
- RenameProperty(ref p, newName);
- }
- public static void RenameProperty(ref JProperty ls, string newName)
- {
- if (ls.Name != newName)
- {
- var parent = ls.Parent;
- ls.Remove();
- ls = new JProperty(newName, ls.Value);
- parent!.Add(ls);
- }
- }
-
- public static JProperty? GetProperty(this JObject blob, string[] pathFrom, bool createIfNotExists)
- {
- var current = blob;
- for (int i = 0; i < pathFrom.Length - 1; i++)
- {
- if (current.TryGetValue(pathFrom[i], out var value) && value is JObject jObject)
- {
- current = jObject;
- }
- else
- {
- if (!createIfNotExists)
- return null;
- JProperty? prop = null;
- for (int ii = i; ii < pathFrom.Length; ii++)
- {
- var newProp = new JProperty(pathFrom[ii], new JObject());
- if (prop is null)
- current.Add(newProp);
- else
- prop.Value = new JObject(newProp);
- prop = newProp;
- }
- return prop;
- }
- }
- var result = current.Property(pathFrom[pathFrom.Length - 1]);
- if (result is null && createIfNotExists)
- {
- result = new JProperty(pathFrom[pathFrom.Length - 1], null as object);
- current.Add(result);
- }
- return result;
- }
- public static CamelCaseNamingStrategy Camel = new CamelCaseNamingStrategy();
- public static void RemoveIfNull(this JObject blob, string propName)
- {
- if (blob.Property(propName)?.Value.Type is JTokenType.Null)
- blob.Remove(propName);
- }
- public static void RemoveIfValue<T>(this JObject conf, string propName, T v)
- {
- var p = conf.Property(propName);
- if (p is null)
- return;
- if (p.Value is JValue { Type: JTokenType.Null })
- {
- if (EqualityComparer<T>.Default.Equals(default, v))
- p.Remove();
- }
- else if (p.Value is JValue jv)
- {
- if (EqualityComparer<T>.Default.Equals(jv.Value<T>(), v))
- {
- p.Remove();
- }
- }
- }
-
- public static void ConvertNumberToString(this JObject o, string prop)
- {
- if (o[prop]?.Type is JTokenType.Float)
- o[prop] = o[prop]!.Value<decimal>().ToString(CultureInfo.InvariantCulture);
- if (o[prop]?.Type is JTokenType.Integer)
- o[prop] = o[prop]!.Value<long>().ToString(CultureInfo.InvariantCulture);
- }
- public static string Unzip(byte[] bytes)
- {
- MemoryStream ms = new MemoryStream(bytes);
- using GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);
- StreamReader reader = new StreamReader(gzip, Encoding.UTF8);
- var unzipped = reader.ReadToEnd();
- return unzipped;
- }
-
- public static int GetDivisibility(string paymentMethodId)
- {
- var splitted = paymentMethodId.Split('-');
- return (CryptoCode: splitted[0], Type: splitted[1]) switch
- {
- { Type: "LN" } or { Type: "LNURL" } => 11,
- { Type: "CHAIN", CryptoCode: var code } when code == "XMR" => 12,
- { Type: "CHAIN" } => 8,
- { Type: "LEGACY" } => 18,
- _ => 8
- };
- }
-
- public static string MigratePaymentMethodId(string paymentMethodId)
- {
- var splitted = paymentMethodId.Split(new[] { '_', '-' });
- if (splitted is [var cryptoCode, var paymentType])
- {
- return paymentType switch
- {
- "BTCLike" or "MoneroLike" or "ZcashLike" => $"{cryptoCode}-CHAIN",
- "LightningLike" or "LightningNetwork" => $"{cryptoCode}-LN",
- "LNURLPAY" => $"{cryptoCode}-LNURL",
- "EthereumLike" => $"{cryptoCode}-LEGACY",
- "CHAIN" or "LNURL" or "LN" => paymentMethodId,
- _ => throw new NotSupportedException("Unknown payment type " + paymentType)
- };
- }
- if (splitted.Length == 1)
- return $"{splitted[0]}-CHAIN";
- throw new NotSupportedException("Unknown payment id " + paymentMethodId);
- }
- public static string TryMigratePaymentMethodId(string paymentMethodId)
- {
- var splitted = paymentMethodId.Split(new[] { '_', '-' });
- if (splitted is [var cryptoCode, var paymentType])
- {
- return paymentType switch
- {
- "BTCLike" or "MoneroLike" or "ZcashLike" => $"{cryptoCode}-CHAIN",
- "LightningLike" or "LightningNetwork" => $"{cryptoCode}-LN",
- "LNURLPAY" => $"{cryptoCode}-LNURL",
- "EthereumLike" => $"{cryptoCode}-LEGACY",
- _ => paymentMethodId
- };
- }
- if (splitted.Length == 1)
- return $"{splitted[0]}-CHAIN";
- return paymentMethodId;
- }
-
- // Make postgres happy
- public static string SanitizeJSON(string json) => json.Replace("\\u0000", string.Empty, StringComparison.OrdinalIgnoreCase);
- }
-}
### BTCPayServer.Data/Data/MigrationInterceptor.cs
@@ -7,7 +7,7 @@ namespace BTCPayServer.Data
{
/// <summary>
/// We have a migration running in the background that will migrate the data from the old blob to the new blob
- /// Meanwhile, we need to make sure that invoices which haven't been migrated yet are migrated on the fly.
+ /// Meanwhile, payment requests awaiting conversion are migrated on the fly.
/// </summary>
public class MigrationInterceptor : IMaterializationInterceptor, ISaveChangesInterceptor
{
### BTCPayServer.Data/Data/PaymentData.Migration.cs
@@ -1,210 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.ComponentModel.DataAnnotations.Schema;
-using System.Linq;
-using NBitcoin;
-using NBitcoin.Altcoins;
-using NBitcoin.DataEncoders;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-
-namespace BTCPayServer.Data
-{
- public partial class PaymentData : MigrationInterceptor.IHasMigration
- {
- public bool TryMigrate()
- {
-#pragma warning disable CS0618 // Type or member is obsolete
- if (Currency is not null)
- return false;
- if (Blob is not (null or { Length: 0 }))
- {
- Blob2 = MigrationExtensions.Unzip(Blob);
- Blob2 = MigrationExtensions.SanitizeJSON(Blob2);
- Blob = null;
- }
- var blob = JsonParser.ParseObject(Blob2);
- if (blob["cryptoPaymentDataType"] is null)
- blob["cryptoPaymentDataType"] = "BTCLike";
- if (blob["cryptoCode"] is null)
- blob["cryptoCode"] = "BTC";
-
- if (blob["receivedTime"] is null)
- blob.Move(["receivedTimeMs"], ["receivedTime"]);
- else
- {
- // Convert number of seconds to number of milliseconds
- var timeSeconds = (ulong)(long)blob["receivedTime"].Value<long>();
- var date = NBitcoin.Utils.UnixTimeToDateTime(timeSeconds);
- blob["receivedTime"] = DateTimeToMilliUnixTime(date.UtcDateTime);
- }
-
- var cryptoCode = blob["cryptoCode"].Value<string>();
- MigratedPaymentMethodId = PaymentMethodId;
- PaymentMethodId = cryptoCode + "_" + blob["cryptoPaymentDataType"].Value<string>();
- PaymentMethodId = MigrationExtensions.MigratePaymentMethodId(PaymentMethodId);
- var divisibility = MigrationExtensions.GetDivisibility(PaymentMethodId);
- Currency = blob["cryptoCode"].Value<string>();
- blob.Remove("cryptoCode");
- blob.Remove("cryptoPaymentDataType");
-
- JObject cryptoData;
- if (blob["cryptoPaymentData"] is null)
- {
- cryptoData = new JObject();
- blob["cryptoPaymentData"] = cryptoData;
- cryptoData["RBF"] = true;
- cryptoData["confirmationCount"] = 0;
- }
- else
- {
- cryptoData = JsonParser.ParseObject(blob["cryptoPaymentData"].Value<string>());
- foreach (var prop in cryptoData.Properties().ToList())
- {
- if (prop.Name is "rbf")
- cryptoData.RenameProperty("rbf", "RBF");
- else if (prop.Name is "bolT11")
- cryptoData.RenameProperty("bolT11", "BOLT11");
- else
- cryptoData.RenameProperty(prop.Name, MigrationExtensions.Camel.GetPropertyName(prop.Name, false));
- }
- }
- blob.Remove("cryptoPaymentData");
- cryptoData["outpoint"] = blob["outpoint"];
- if (blob["output"] is not (null or { Type: JTokenType.Null }))
- {
- // Old versions didn't track addresses, so we take it from output.
- // We don't know the network for sure but better having something than nothing in destination.
- // If signet/testnet crash we don't really care anyway.
- // Also, only LTC was supported at this time.
- Network network = (cryptoCode switch { "LTC" => (INetworkSet)Litecoin.Instance, _ => Bitcoin.Instance }).Mainnet;
- var txout = network.Consensus.ConsensusFactory.CreateTxOut();
- txout.ReadWrite(Encoders.Hex.DecodeData(blob["output"].Value<string>()), network);
- cryptoData["value"] = txout.Value.Satoshi;
- blob["destination"] = txout.ScriptPubKey.GetDestinationAddress(network)?.ToString();
- }
- blob.Remove("output");
- blob.Remove("outpoint");
- // Convert from sats to btc
- if (cryptoData["value"] is not (null or { Type: JTokenType.Null } or { Type: JTokenType.Object }))
- {
- var v = cryptoData["value"].Value<long>();
- Amount = (decimal)v / (decimal)Money.COIN;
- cryptoData.Remove("value");
-
- blob["paymentMethodFee"] = blob["networkFee"];
- blob.RemoveIfValue<decimal>("paymentMethodFee", 0.0m);
- blob.ConvertNumberToString("paymentMethodFee");
- blob.Remove("networkFee");
- blob.RemoveIfNull("paymentMethodFee");
- }
- // Liquid
- else if (cryptoData["value"] is { Type: JTokenType.Object })
- {
- var v = cryptoData["value"]["value"].Value<long>();
- var assetId = cryptoData["value"]["assetId"].Value<string>();
- divisibility = GetDivisibility(assetId) ?? 8;
- Amount = (decimal)v / (decimal)Math.Pow(10.0, divisibility);
- cryptoData.Remove("value");
- cryptoData["assetId"] = assetId;
- blob["paymentMethodFee"] = blob["networkFee"];
- blob.RemoveIfValue<decimal>("paymentMethodFee", 0.0m);
- blob.ConvertNumberToString("paymentMethodFee");
- blob.Remove("networkFee");
- blob.RemoveIfNull("paymentMethodFee");
- }
- // Convert from millisats to btc
- else if (cryptoData["amount"] is not (null or { Type: JTokenType.Null }))
- {
- var v = cryptoData["amount"].Value<long>();
- Amount = (decimal)v / (decimal)Math.Pow(10.0, divisibility);
- cryptoData.Remove("amount");
- }
- if (cryptoData["address"] is not (null or { Type: JTokenType.Null }))
- {
- blob["destination"] = cryptoData["address"];
- cryptoData.Remove("address");
- }
- if (cryptoData["BOLT11"] is not (null or { Type: JTokenType.Null }))
- {
- blob["destination"] = cryptoData["BOLT11"];
- cryptoData.Remove("BOLT11");
- }
- if (cryptoData["outpoint"] is not (null or { Type: JTokenType.Null }))
- {
- // Convert to format txid-n
- cryptoData["outpoint"] = OutPoint.Parse(cryptoData["outpoint"].Value<string>()).ToString();
- }
- if (Accounted is false)
- Status = PaymentStatus.Unaccounted;
- else if (cryptoData["confirmationCount"] is { Type: JTokenType.Integer })
- {
- var confirmationCount = cryptoData["confirmationCount"].Value<int>();
- // Technically, we should use the invoice's speed policy, however it's not on our
- // scope and is good enough for majority of cases.
- Status = confirmationCount > 0 ? PaymentStatus.Settled : PaymentStatus.Processing;
- if (cryptoData["LockTime"] is { Type: JTokenType.Integer })
- {
- var lockTime = cryptoData["LockTime"].Value<int>();
- if (confirmationCount < lockTime)
- Status = PaymentStatus.Processing;
- }
- }
- else
- {
- Status = PaymentStatus.Settled;
- }
- Created = MilliUnixTimeToDateTime(blob["receivedTime"].Value<long>());
- cryptoData.RemoveIfValue<bool>("rbf", false);
- cryptoData.Remove("legacy");
- cryptoData.Remove("networkFee");
- cryptoData.Remove("paymentType");
- cryptoData.RemoveIfNull("outpoint");
- cryptoData.RemoveIfValue<bool>("RBF", false);
-
- blob.Remove("receivedTime");
- blob.Remove("accounted");
- blob.Remove("networkFee");
- blob["details"] = cryptoData;
- blob["divisibility"] = divisibility;
- blob["version"] = 2;
- Blob2 = blob.ToString(Formatting.None);
- Accounted = null;
-#pragma warning restore CS0618 // Type or member is obsolete
- return true;
- }
-
- private int? GetDivisibility(string assetId) =>
- assetId switch
- {
- "ce091c998b83c78bb71a632313ba3760f1763d9cfcffae02258ffa9865a37bd2" => 8,
- "aa775044c32a7df391902b3659f46dfe004ccb2644ce2ddc7dba31e889391caf" => 2,
- "0e99c1a6da379d1f4151fb9df90449d40d0608f6cb33a5bcbfc8c265f42bab0a" => 8,
- "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d" => 8,
- _ => null,
- };
-
- [NotMapped]
- public bool Migrated { get; set; }
- [NotMapped]
- [EditorBrowsable(EditorBrowsableState.Never)]
- public string MigratedPaymentMethodId { get; set; }
-
- static readonly DateTimeOffset unixRef = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
- public static long DateTimeToMilliUnixTime(in DateTime time)
- {
- var date = ((DateTimeOffset)time).ToUniversalTime();
- long v = (long)(date - unixRef).TotalMilliseconds;
- if (v < 0)
- throw new FormatException("Invalid datetime (less than 1/1/1970)");
- return v;
- }
- public static DateTimeOffset MilliUnixTimeToDateTime(long value)
- {
- var v = value;
- if (v < 0)
- throw new FormatException("Invalid datetime (less than 1/1/1970)");
- return unixRef + TimeSpan.FromMilliseconds(v);
- }
- }
-}
### BTCPayServer.Data/Data/PaymentRequestData.Migration.cs
@@ -1,6 +1,9 @@
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Globalization;
+using System.IO;
+using System.IO.Compression;
+using System.Text;
using Newtonsoft.Json.Linq;
namespace BTCPayServer.Data
@@ -17,8 +20,8 @@ public bool TryMigrate()
return false;
if (Blob2 is null)
{
- Blob2 = Blob is not (null or { Length: 0 }) ? MigrationExtensions.Unzip(Blob) : "{}";
- Blob2 = MigrationExtensions.SanitizeJSON(Blob2);
+ Blob2 = Blob is not (null or { Length: 0 }) ? Unzip(Blob) : "{}";
+ Blob2 = SanitizeJSON(Blob2);
}
Blob = null;
#pragma warning restore CS0618 // Type or member is obsolete
@@ -52,5 +55,16 @@ public bool TryMigrate()
Blob2 = jobj.ToString(Newtonsoft.Json.Formatting.None);
return true;
}
+
+ private static string Unzip(byte[] bytes)
+ {
+ using var ms = new MemoryStream(bytes);
+ using var gzip = new GZipStream(ms, CompressionMode.Decompress);
+ using var reader = new StreamReader(gzip, Encoding.UTF8);
+ return reader.ReadToEnd();
+ }
+
+ // Make postgres happy
+ private static string SanitizeJSON(string json) => json.Replace("\\u0000", string.Empty, StringComparison.OrdinalIgnoreCase);
}
}
### BTCPayServer.Data/Migrations/20231020135844_AddBoltcardsTable.cs
@@ -1,13 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20231020135844_AddBoltcardsTable")]
- [DBScript("000.Init.sql")]
- public partial class AddBoltcardsTable : DBScriptsMigration
- {
- }
-}
### BTCPayServer.Data/Migrations/20231121031609_removecurrentrefund.cs
@@ -1,33 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20231121031609_removecurrentrefund")]
- public partial class removecurrentrefund : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropForeignKey(
- name: "FK_Invoices_Refunds_Id_CurrentRefundId",
- table: "Invoices");
-
- migrationBuilder.DropIndex(
- name: "IX_Invoices_Id_CurrentRefundId",
- table: "Invoices");
-
- migrationBuilder.DropColumn(
- name: "CurrentRefundId",
- table: "Invoices");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- }
- }
-}
### BTCPayServer.Data/Migrations/20231219031609_appssettingstojson.cs
@@ -1,23 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20231219031609_appssettingstojson")]
- public partial class appssettingstojson : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql("ALTER TABLE \"Apps\" ALTER COLUMN \"Settings\" TYPE JSONB USING \"Settings\"::JSONB");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- }
- }
-}
### BTCPayServer.Data/Migrations/20231219031609_translationsmigration.cs
@@ -1,58 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20231219031609_translationsmigration")]
- public partial class translationsmigration : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql("""
- CREATE TABLE lang_dictionaries (
- dict_id TEXT PRIMARY KEY,
- fallback TEXT DEFAULT NULL,
- source TEXT DEFAULT NULL,
- metadata JSONB DEFAULT NULL,
- FOREIGN KEY (fallback) REFERENCES lang_dictionaries(dict_id) ON UPDATE CASCADE ON DELETE SET NULL
- );
- INSERT INTO lang_dictionaries(dict_id, source) VALUES ('English', 'Default');
-
- CREATE TABLE lang_translations (
- dict_id TEXT NOT NULL,
- sentence TEXT NOT NULL,
- translation TEXT NOT NULL,
- PRIMARY KEY (dict_id, sentence),
- FOREIGN KEY (dict_id) REFERENCES lang_dictionaries(dict_id) ON UPDATE CASCADE ON DELETE CASCADE
- );
-
- CREATE VIEW translations AS
- WITH RECURSIVE translations_with_paths AS (
- SELECT d.dict_id, t.sentence, t.translation, ARRAY[d.dict_id] AS path FROM lang_translations t
- INNER JOIN lang_dictionaries d USING (dict_id)
-
- UNION ALL
-
- SELECT d.dict_id, t.sentence, t.translation, d.dict_id || t.path FROM translations_with_paths t
- INNER JOIN lang_dictionaries d ON d.fallback=t.dict_id
- ),
- ranked_translations AS (
- SELECT *,
- ROW_NUMBER() OVER (PARTITION BY dict_id, sentence ORDER BY array_length(path, 1)) AS rn
- FROM translations_with_paths
- )
- SELECT dict_id, sentence, translation, path FROM ranked_translations WHERE rn=1;
- COMMENT ON VIEW translations IS 'Compute the translation for all sentences for all dictionaries, taking into account fallbacks';
- """);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- }
- }
-}
### BTCPayServer.Data/Migrations/20240104155620_AddApprovalToApplicationUser.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("20240104155620_AddApprovalToApplicationUser")]
- public partial class AddApprovalToApplicationUser : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<bool>(
- name: "Approved",
- table: "AspNetUsers",
- nullable: false,
- defaultValue: false);
-
- migrationBuilder.AddColumn<bool>(
- name: "RequiresApproval",
- table: "AspNetUsers",
- nullable: false,
- defaultValue: false);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Approved",
- table: "AspNetUsers");
-
- migrationBuilder.DropColumn(
- name: "RequiresApproval",
- table: "AspNetUsers");
- }
- }
-}
### BTCPayServer.Data/Migrations/20240220000000_FixWalletObjectsWithEmptyWalletId.cs
@@ -1,23 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240220000000_FixWalletObjectsWithEmptyWalletId")]
- public partial class FixWalletObjectsWithEmptyWalletId : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql("DELETE FROM \"WalletObjects\" WHERE \"WalletId\"='';");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- }
- }
-}
### BTCPayServer.Data/Migrations/20240229000000_PayoutAndPullPaymentToJsonBlob.cs
@@ -1,25 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240229000000_PayoutAndPullPaymentToJsonBlob")]
- public partial class PayoutAndPullPaymentToJsonBlob : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql("ALTER TABLE \"Payouts\" ALTER COLUMN \"Blob\" TYPE JSONB USING regexp_replace(convert_from(\"Blob\",'UTF8'), '\\\\u0000', '', 'g')::JSONB");
- migrationBuilder.Sql("ALTER TABLE \"Payouts\" ALTER COLUMN \"Proof\" TYPE JSONB USING regexp_replace(convert_from(\"Proof\",'UTF8'), '\\\\u0000', '', 'g')::JSONB");
- migrationBuilder.Sql("ALTER TABLE \"PullPayments\" ALTER COLUMN \"Blob\" TYPE JSONB USING regexp_replace(convert_from(\"Blob\",'UTF8'), '\\\\u0000', '', 'g')::JSONB");
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- }
- }
-}
### BTCPayServer.Data/Migrations/20240229092905_AddManagerAndEmployeeToStoreRoles.cs
@@ -1,89 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-using Newtonsoft.Json;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240229092905_AddManagerAndEmployeeToStoreRoles")]
- public partial class AddManagerAndEmployeeToStoreRoles : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.InsertData(
- "StoreRoles",
- columns: new[] { "Id", "Role", "Permissions" },
- columnTypes: new[] { "TEXT", "TEXT", "TEXT[]" },
- values: new object[,]
- {
- {
- "Manager", "Manager", new[]
- {
- "btcpay.store.canviewstoresettings",
- "btcpay.store.canmodifyinvoices",
- "btcpay.store.webhooks.canmodifywebhooks",
- "btcpay.store.canmodifypaymentrequests",
- "btcpay.store.canmanagepullpayments",
- "btcpay.store.canmanagepayouts"
- }
- },
- {
- "Employee", "Employee", new[]
- {
- "btcpay.store.canmodifyinvoices",
- "btcpay.store.canmodifypaymentrequests",
- "btcpay.store.cancreatenonapprovedpullpayments",
- "btcpay.store.canviewpayouts",
- "btcpay.store.canviewpullpayments"
- }
- }
- });
-
- migrationBuilder.UpdateData(
- "StoreRoles",
- keyColumns: new[] { "Id" },
- keyColumnTypes: new[] { "TEXT" },
- keyValues: new[] { "Guest" },
- columns: new[] { "Permissions" },
- columnTypes: new[] { "TEXT[]" },
- values: new object[]
- {
- new[]
- {
- "btcpay.store.canmodifyinvoices",
- "btcpay.store.canviewpaymentrequests",
- "btcpay.store.canviewpullpayments",
- "btcpay.store.canviewpayouts"
- }
- });
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DeleteData("StoreRoles", "Id", "Manager");
- migrationBuilder.DeleteData("StoreRoles", "Id", "Employee");
-
- migrationBuilder.UpdateData(
- "StoreRoles",
- keyColumns: new[] { "Id" },
- keyColumnTypes: new[] { "TEXT" },
- keyValues: new[] { "Guest" },
- columns: new[] { "Permissions" },
- columnTypes: new[] { "TEXT[]" },
- values: new object[]
- {
- new[]
- {
- "btcpay.store.canviewstoresettings",
- "btcpay.store.canmodifyinvoices",
- "btcpay.store.canviewcustodianaccounts",
- "btcpay.store.candeposittocustodianaccount"
- }
- });
- }
- }
-}
### BTCPayServer.Data/Migrations/20240304003640_addinvoicecolumns.cs
@@ -1,43 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- /// <inheritdoc />
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240304003640_addinvoicecolumns")]
- public partial class addinvoicecolumns : Migration
- {
- /// <inheritdoc />
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<decimal>(
- name: "Amount",
- table: "Invoices",
- type: "NUMERIC",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Currency",
- table: "Invoices",
- type: "TEXT",
- nullable: true);
- }
-
- /// <inheritdoc />
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Amount",
- table: "Invoices");
-
- migrationBuilder.DropColumn(
- name: "Currency",
- table: "Invoices");
- }
- }
-}
### BTCPayServer.Data/Migrations/20240317024757_payments_refactor.cs
@@ -1,67 +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("20240317024757_payments_refactor")]
- public partial class payments_refactor : Migration
- {
- /// <inheritdoc />
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<decimal>(
- name: "Amount",
- table: "Payments",
- type: "NUMERIC",
- nullable: true);
-
- migrationBuilder.AddColumn<DateTimeOffset>(
- name: "Created",
- table: "Payments",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Currency",
- table: "Payments",
- type: "TEXT",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Status",
- table: "Payments",
- type: "TEXT",
- nullable: true);
-
- migrationBuilder.AlterColumn<bool?>(
- name: "Accounted",
- table: "Payments",
- nullable: true);
- }
-
- /// <inheritdoc />
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Amount",
- table: "Payments");
-
- migrationBuilder.DropColumn(
- name: "Created",
- table: "Payments");
-
- migrationBuilder.DropColumn(
- name: "Currency",
- table: "Payments");
-
- migrationBuilder.DropColumn(
- name: "Status",
- table: "Payments");
- }
- }
-}
### BTCPayServer.Data/Migrations/20240325095923_RemoveCustodian.cs
@@ -1,54 +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("20240325095923_RemoveCustodian")]
- public partial class RemoveCustodian : Migration
- {
- /// <inheritdoc />
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropTable(
- name: "CustodianAccount");
- }
-
- /// <inheritdoc />
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.CreateTable(
- name: "CustodianAccount",
- columns: table => new
- {
- Id = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
- StoreId = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
- Blob = table.Column<byte[]>(type: "BLOB", nullable: true),
- Blob2 = table.Column<string>(type: "TEXT", nullable: true),
- CustodianCode = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
- Name = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false)
- },
- 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");
- }
- }
-}
### BTCPayServer.Data/Migrations/20240405004015_cleanup_invoice_events.cs
@@ -1,30 +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("20240405004015_cleanup_invoice_events")]
- public partial class cleanup_invoice_events : Migration
- {
- /// <inheritdoc />
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql(@"
- ALTER TABLE ""InvoiceEvents"" DROP CONSTRAINT IF EXISTS ""PK_InvoiceEvents"";
- ALTER TABLE ""InvoiceEvents"" DROP COLUMN IF EXISTS ""UniqueId"";
- CREATE INDEX IF NOT EXISTS ""IX_InvoiceEvents_InvoiceDataId"" ON ""InvoiceEvents""(""InvoiceDataId"");
- ");
- }
-
- /// <inheritdoc />
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- }
- }
-}
### BTCPayServer.Data/Migrations/20240501015052_noperiod.cs
@@ -1,31 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240501015052_noperiod")]
- public partial class noperiod : Migration
- {
- /// <inheritdoc />
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Period",
- table: "PullPayments");
- }
-
- /// <inheritdoc />
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<long>(
- name: "Period",
- table: "PullPayments",
- type: "bigint",
- nullable: true);
- }
- }
-}
### BTCPayServer.Data/Migrations/20240508015052_fileid.cs
@@ -1,61 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240508015052_fileid")]
- public partial class fileid : Migration
- {
- /// <inheritdoc />
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.Sql("""
-UPDATE "Settings"
-SET "Value" = jsonb_set(
- "Value",
- '{LogoUrl}',
- to_jsonb('fileid:' || ("Value"->>'LogoFileId'))) - 'LogoFileId'
-WHERE "Id" = 'BTCPayServer.Services.ThemeSettings'
-AND "Value"->>'LogoFileId' IS NOT NULL;
-
-UPDATE "Settings"
-SET "Value" = jsonb_set(
- "Value",
- '{CustomThemeCssUrl}',
- to_jsonb('fileid:' || ("Value"->>'CustomThemeFileId'))) - 'CustomThemeFileId'
-WHERE "Id" = 'BTCPayServer.Services.ThemeSettings'
-AND "Value"->>'CustomThemeFileId' IS NOT NULL;
-
-UPDATE "Stores"
-SET "StoreBlob" = jsonb_set(
- "StoreBlob",
- '{logoUrl}',
- to_jsonb('fileid:' || ("StoreBlob"->>'logoFileId'))) - 'logoFileId'
-WHERE "StoreBlob"->>'logoFileId' IS NOT NULL;
-
-UPDATE "Stores"
-SET "StoreBlob" = jsonb_set(
- "StoreBlob",
- '{cssUrl}',
- to_jsonb('fileid:' || ("StoreBlob"->>'cssFileId'))) - 'cssFileId'
-WHERE "StoreBlob"->>'cssFileId' IS NOT NULL;
-
-UPDATE "Stores"
-SET "StoreBlob" = jsonb_set(
- "StoreBlob",
- '{paymentSoundUrl}',
- to_jsonb('fileid:' || ("StoreBlob"->>'soundFileId'))) - 'soundFileId'
-WHERE "StoreBlob"->>'soundFileId' IS NOT NULL;
-""");
- }
-
- /// <inheritdoc />
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- }
- }
-}
### BTCPayServer.Data/Migrations/20240826065950_removeinvoicecols.cs
@@ -1,35 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240826065950_removeinvoicecols")]
- [DBScript("001.InvoiceFunctions.sql")]
- public partial class removeinvoicecols : DBScriptsMigration
- {
- /// <inheritdoc />
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropIndex(
- name: "IX_Invoices_OrderId",
- table: "Invoices");
-
- migrationBuilder.DropColumn(
- name: "ItemCode",
- table: "Invoices");
-
- migrationBuilder.DropColumn(
- name: "OrderId",
- table: "Invoices");
-
- migrationBuilder.DropColumn(
- name: "CustomerEmail",
- table: "Invoices");
- base.Up(migrationBuilder);
- }
- }
-}
### BTCPayServer.Data/Migrations/20240827034505_migratepayouts.cs
@@ -1,40 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240827034505_migratepayouts")]
- [DBScript("002.RefactorPayouts.sql")]
- public partial class migratepayouts : DBScriptsMigration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- base.Up(migrationBuilder);
- migrationBuilder.RenameColumn(
- name: "Destination",
- table: "Payouts",
- newName: "DedupId");
- migrationBuilder.RenameIndex(
- name: "IX_Payouts_Destination_State",
- table: "Payouts",
- newName: "IX_Payouts_DedupId_State");
- migrationBuilder.RenameColumn(
- name: "PaymentMethod",
- table: "PayoutProcessors",
- newName: "PayoutMethodId");
-
- migrationBuilder.Sql("""
- UPDATE "PayoutProcessors"
- SET
- "PayoutMethodId" = CASE WHEN STRPOS("PayoutMethodId", '_') = 0 THEN "PayoutMethodId" || '-CHAIN'
- WHEN STRPOS("PayoutMethodId", '_LightningLike') > 0 THEN split_part("PayoutMethodId", '_LightningLike', 1) || '-LN'
- WHEN STRPOS("PayoutMethodId", '_LNURLPAY') > 0 THEN split_part("PayoutMethodId",'_LNURLPAY', 1) || '-LN'
- ELSE "PayoutMethodId" END
- """);
- }
- }
-}
### BTCPayServer.Data/Migrations/20240904092905_UpdateStoreOwnerRole.cs
@@ -1,54 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-using Newtonsoft.Json;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240904092905_UpdateStoreOwnerRole")]
- public partial class UpdateStoreOwnerRole : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.UpdateData(
- "StoreRoles",
- keyColumns: new[] { "Id" },
- keyColumnTypes: new[] { "TEXT" },
- keyValues: new[] { "Owner" },
- columns: new[] { "Permissions" },
- columnTypes: new[] { "TEXT[]" },
- values: new object[]
- {
- new[]
- {
- "btcpay.store.canmodifystoresettings"
- }
- });
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.UpdateData(
- "StoreRoles",
- keyColumns: new[] { "Id" },
- keyColumnTypes: new[] { "TEXT" },
- keyValues: new[] { "Owner" },
- columns: new[] { "Permissions" },
- columnTypes: new[] { "TEXT[]" },
- values: new object[]
- {
- new[]
- {
- "btcpay.store.canmodifystoresettings",
- "btcpay.store.cantradecustodianaccount",
- "btcpay.store.canwithdrawfromcustodianaccount",
- "btcpay.store.candeposittocustodianaccount"
- }
- });
- }
- }
-}
### BTCPayServer.Data/Migrations/20240913034505_refactorpendinginvoicespayments.cs
@@ -1,15 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240913034505_refactorpendinginvoicespayments")]
- [DBScript("003.RefactorPendingInvoicesPayments.sql")]
- public partial class refactorpendinginvoicespayments : DBScriptsMigration
- {
- }
-}
### BTCPayServer.Data/Migrations/20240919085726_refactorinvoiceaddress.cs
@@ -1,79 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240919085726_refactorinvoiceaddress")]
- public partial class refactorinvoiceaddress : Migration
- {
- /// <inheritdoc />
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropPrimaryKey(
- name: "PK_AddressInvoices",
- table: "AddressInvoices");
-
- migrationBuilder.AddColumn<string>(
- name: "PaymentMethodId",
- table: "AddressInvoices",
- type: "text",
- nullable: false,
- defaultValue: "");
-
- migrationBuilder.Sql("""
- UPDATE "AddressInvoices"
- SET
- "Address" = (string_to_array("Address", '#'))[1],
- "PaymentMethodId" = CASE WHEN (string_to_array("Address", '#'))[2] IS NULL THEN 'BTC-CHAIN'
- WHEN STRPOS((string_to_array("Address", '#'))[2], '_') = 0 THEN (string_to_array("Address", '#'))[2] || '-CHAIN'
- WHEN STRPOS((string_to_array("Address", '#'))[2], '_MoneroLike') > 0 THEN replace((string_to_array("Address", '#'))[2],'_MoneroLike','-CHAIN')
- WHEN STRPOS((string_to_array("Address", '#'))[2], '_ZcashLike') > 0 THEN replace((string_to_array("Address", '#'))[2],'_ZcashLike','-CHAIN')
- ELSE '' END;
- ALTER TABLE "AddressInvoices" DROP COLUMN IF EXISTS "CreatedTime";
- DELETE FROM "AddressInvoices" WHERE "PaymentMethodId" = '';
- """);
- migrationBuilder.AddPrimaryKey(
- name: "PK_AddressInvoices",
- table: "AddressInvoices",
- columns: new[] { "Address", "PaymentMethodId" });
- }
-
- /// <inheritdoc />
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropPrimaryKey(
- name: "PK_AddressInvoices",
- table: "AddressInvoices");
-
- migrationBuilder.DropColumn(
- name: "PaymentMethodId",
- table: "AddressInvoices");
-
- migrationBuilder.AddPrimaryKey(
- name: "PK_AddressInvoices",
- table: "AddressInvoices",
- column: "Address");
-
- migrationBuilder.CreateTable(
- name: "PendingInvoices",
- columns: table => new
- {
- Id = table.Column<string>(type: "text", nullable: false)
- },
- constraints: table =>
- {
- table.PrimaryKey("PK_PendingInvoices", x => x.Id);
- table.ForeignKey(
- name: "FK_PendingInvoices_Invoices_Id",
- column: x => x.Id,
- principalTable: "Invoices",
- principalColumn: "Id",
- onDelete: ReferentialAction.Cascade);
- });
- }
- }
-}
### BTCPayServer.Data/Migrations/20240923065254_refactorpayments.cs
@@ -1,38 +0,0 @@
-using BTCPayServer.Data;
-using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Migrations;
-
-#nullable disable
-
-namespace BTCPayServer.Migrations
-{
-
- [DbContext(typeof(ApplicationDbContext))]
- [Migration("20240923065254_refactorpayments")]
- public partial class refactorpayments : DBScriptsMigration
- {
- /// <inheritdoc />
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropPrimaryKey(
- name: "PK_Payments",
- table: "Payments");
-
- migrationBuilder.RenameColumn(
- name: "Type",
- table: "Payments",
- newName: "PaymentMethodId");
- migrationBuilder.Sql("UPDATE \"Payments\" SET \"PaymentMethodId\"='' WHERE \"PaymentMethodId\" IS NULL;");
- migrationBuilder.AddPrimaryKey(
- name: "PK_Payments",
- table: "Payments",
- columns: new[] { "Id", "PaymentMethodId" });
- base.Up(migrationBuilder);
- }
-
- /// <inheritdoc />
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- }
- }
-}
### BTCPayServer.Data/Migrations/20240924065254_monitoredinvoices.cs
@@ -8,7 +8,8 @@ namespace BTCPayServer.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20240924065254_monitoredinvoices")]
- [DBScript("004.MonitoredInvoices.sql")]
+ [DBScript("000.Init.sql")]
+ // Consolidated through 2.0.0. Keep the original ID so existing databases skip initialization.
public partial class monitoredinvoices : DBScriptsMigration
{
}
### BTCPayServer.Tests/DatabaseTests.cs
@@ -433,26 +433,5 @@ await ctx.Database.GetDbConnection().ExecuteAsync("""
}
}
- [Fact]
- public async Task CanMigrateInvoiceAddresses()
- {
- var tester = CreateDBTester();
- await tester.MigrateUntil("20240919085726_refactorinvoiceaddress");
- await using var ctx = tester.CreateContext();
- var conn = ctx.Database.GetDbConnection();
- await conn.ExecuteAsync("INSERT INTO \"Invoices\" (\"Id\", \"Created\") VALUES ('i', NOW())");
- await conn.ExecuteAsync(
- "INSERT INTO \"AddressInvoices\" VALUES ('aaa#BTC', 'i'),('bbb','i'),('ccc#BTC_LNU', 'i'),('ddd#XMR_MoneroLike', 'i'),('eee#ZEC_ZcashLike', 'i')");
- await tester.CompleteMigrations();
- foreach (var v in new[] { ("aaa", "BTC-CHAIN"), ("bbb", "BTC-CHAIN"), ("ddd", "XMR-CHAIN") , ("eee", "ZEC-CHAIN") })
- {
- var ok = await conn.ExecuteScalarAsync<bool>("SELECT 't'::BOOLEAN FROM \"AddressInvoices\" WHERE \"Address\"=@a AND \"PaymentMethodId\"=@b", new { a = v.Item1, b = v.Item2 });
- Assert.True(ok);
- }
- var notok = await conn.ExecuteScalarAsync<bool>("SELECT 't'::BOOLEAN FROM \"AddressInvoices\" WHERE \"Address\"='ccc'");
- Assert.False(notok);
- }
-
-
}
}
### BTCPayServer.Tests/FastTests.cs
@@ -2837,122 +2837,6 @@ public void CanParseMetadata()
Assert.Null(metadata.PosData);
}
- class CanOldMigrateInvoicesBlobVector
- {
- public string Type { get; set; }
- public JObject Input { get; set; }
- public JObject Expected { get; set; }
- public bool SkipRountripTest { get; set; }
- public Dictionary<string, string> ExpectedProperties { get; set; }
- }
- [Fact]
- public void CanOldMigrateInvoicesBlob()
- {
- Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
- Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
- int i = 0;
- var vectors = JsonConvert.DeserializeObject<CanOldMigrateInvoicesBlobVector[]>(File.ReadAllText(TestUtils.GetTestDataFullPath("InvoiceMigrationTestVectors.json")));
- foreach (var v in vectors)
- {
- TestLogs.LogInformation("Test " + i++);
- object obj = null;
- if (v.Type == "invoice")
- {
- Data.InvoiceData data = new Data.InvoiceData();
- obj = data;
- data.Blob2 = v.Input.ToString();
- data.TryMigrate();
- var actual = JObject.Parse(data.Blob2);
- AssertSameJson(v.Expected, actual);
- if (!v.SkipRountripTest)
- {
- // Check that we get the same as when setting blob again
- var entity = data.GetBlob();
- entity.AdditionalData?.Clear();
- entity.SetPaymentPrompts(entity.GetPaymentPrompts()); // Cleanup
- data.SetBlob(entity);
- actual = JObject.Parse(data.Blob2);
- AssertSameJson(v.Expected, actual);
- }
- }
- else if (v.Type == "payment")
- {
- Data.PaymentData data = new Data.PaymentData();
- //data.
- obj = data;
- data.Blob2 = v.Input.ToString();
- data.TryMigrate();
- var actual = JObject.Parse(data.Blob2);
- AssertSameJson(v.Expected, actual);
- if (!v.SkipRountripTest)
- {
- // Check that we get the same as when setting blob again
- var entity = data.GetBlob();
- data.SetBlob(entity);
- actual = JObject.Parse(data.Blob2);
- AssertSameJson(v.Expected, actual);
- }
- }
- else
- {
- Assert.Fail("Unknown vector type");
- }
- if (v.ExpectedProperties is not null)
- {
- foreach (var kv in v.ExpectedProperties)
- {
- if (kv.Key == "CreatedInMs")
- {
- var actual = PaymentData.DateTimeToMilliUnixTime(((DateTimeOffset)obj.GetType().GetProperty("Created").GetValue(obj)).UtcDateTime);
- Assert.Equal(long.Parse(kv.Value), actual);
- }
- else
- {
- var actual = obj.GetType().GetProperty(kv.Key).GetValue(obj);
- Assert.Equal(kv.Value, actual?.ToString());
- }
- }
- }
- }
- }
-
- private void AssertSameJson(JToken expected, JToken actual, List<string> path = null)
- {
- var ok = JToken.DeepEquals(expected, actual);
- if (ok)
- return;
- var e = NormalizeJsonString((JObject)expected);
- var a = NormalizeJsonString((JObject)actual);
- Assert.Equal(e, a);
- }
- public static string NormalizeJsonString(JObject parsedObject)
- {
- var normalizedObject = SortPropertiesAlphabetically(parsedObject);
- return JsonConvert.SerializeObject(normalizedObject);
- }
-
- private static JObject SortPropertiesAlphabetically(JObject original)
- {
- var result = new JObject();
-
- foreach (var property in original.Properties().ToList().OrderBy(p => p.Name))
- {
- var value = property.Value as JObject;
-
- if (value != null)
- {
- value = SortPropertiesAlphabetically(value);
- result.Add(property.Name, value);
- }
- else
- {
- result.Add(property.Name, property.Value);
- }
- }
-
- return result;
- }
-
[Fact]
public void CanSafelyRoundTripJsonBlobs()
{
@@ -2987,58 +2871,6 @@ public void CanSafelyRoundTripJsonBlobs()
Assert.Equal(date, payment.GetBlob().Destination);
}
- [Fact]
- public void CanParseInvoiceEntityDerivationStrategies()
- {
- var serializer = BlobSerializer.CreateSerializer(new NBXplorer.NBXplorerNetworkProvider(ChainName.Regtest).GetBTC()).Serializer;
- // We have 3 ways of serializing the derivation strategies:
- // through "derivationStrategy", through "derivationStrategies" as a string, through "derivationStrategies" as JObject
- // Let's check that InvoiceEntity is similar in all cases.
- var legacy = new JObject()
- {
- ["derivationStrategy"] = "tpubDDLQZ1WMdy5YJAJWmRNoTJ3uQkavEPXCXnmD4eAuo9BKbzFUBbJmVHys5M3ku4Qw1C165wGpVWH55gZpHjdsCyntwNzhmCAzGejSL6rzbyf-[p2sh]"
- };
- var scheme = DerivationSchemeSettings.Parse("tpubDDLQZ1WMdy5YJAJWmRNoTJ3uQkavEPXCXnmD4eAuo9BKbzFUBbJmVHys5M3ku4Qw1C165wGpVWH55gZpHjdsCyntwNzhmCAzGejSL6rzbyf-[p2sh]", CreateNetworkProvider(ChainName.Regtest).BTC);
- Assert.True(scheme.AccountDerivation is P2SHDerivationStrategy);
- scheme.Source = "ManualDerivationScheme";
- scheme.AccountOriginal = "tpubDDLQZ1WMdy5YJAJWmRNoTJ3uQkavEPXCXnmD4eAuo9BKbzFUBbJmVHys5M3ku4Qw1C165wGpVWH55gZpHjdsCyntwNzhmCAzGejSL6rzbyf-[p2sh]";
- var legacy2 = new JObject()
- {
- ["derivationStrategies"] = new JObject()
- {
- ["BTC"] = JToken.FromObject(scheme, serializer)
- }
- };
-
- var newformat = new JObject()
- {
- ["derivationStrategies"] = new JObject()
- {
- ["BTC"] = JToken.FromObject(scheme, serializer)
- }
- };
-
- //new BTCPayNetworkProvider(ChainName.Regtest)
- var formats = new[] { legacy, legacy2, newformat }
- .Select(o =>
- {
- o.Add("currency", "USD");
- o.Add("price", "0.0");
- o.Add("cryptoData", new JObject()
- {
- ["BTC"] = new JObject()
- });
- var data = new Data.InvoiceData();
- data.Blob2 = o.ToString();
- data.TryMigrate();
- var migrated = JObject.Parse(data.Blob2);
- return migrated["prompts"]["BTC-CHAIN"]["details"]["accountDerivation"].Value<string>();
- })
- .ToHashSet();
- var v = Assert.Single(formats);
- Assert.NotNull(v);
- }
-
[Fact]
public void PaymentMethodIdConverterIsGraceful()
{
### BTCPayServer.Tests/GreenfieldAPITests.cs
@@ -396,9 +396,9 @@ public async Task CanCreateReadAndDeleteFiles()
Assert.Empty(await client.GetFiles());
// Upload
- var filePath = TestUtils.GetTestDataFullPath("OldInvoices.csv");
+ var filePath = TestUtils.GetTestDataFullPath("Upload.csv");
var upload = await client.UploadFile(filePath, "text/csv");
- Assert.Equal("OldInvoices.csv", upload.OriginalName);
+ Assert.Equal("Upload.csv", upload.OriginalName);
Assert.NotNull(upload.Uri);
Assert.NotNull(upload.Url);
@@ -407,7 +407,7 @@ public async Task CanCreateReadAndDeleteFiles()
// Single file endpoint
var singleFile = await client.GetFile(upload.Id);
- Assert.Equal("OldInvoices.csv", singleFile.OriginalName);
+ Assert.Equal("Upload.csv", singleFile.OriginalName);
Assert.NotNull(singleFile.Uri);
Assert.NotNull(singleFile.Url);
### BTCPayServer.Tests/LightningTests.cs
@@ -972,65 +972,20 @@ public async Task CanSetPaymentMethodLimitsLightning()
[Trait("Integration", "Integration")]
[Fact]
- public async Task CanMigratePaymentMethodConfigs()
+ public async Task CanMigrateOldDerivationSchemes()
{
using var tester = CreateServerTester(newDb: true);
- tester.ActivateLightning(LightningTestImplementation.CoreLightning);
await tester.StartAsync();
var acc = tester.NewAccount();
await acc.GrantAccessAsync(true);
await acc.CreateStoreAsync();
var handlers = tester.PayTester.GetService<PaymentMethodHandlerDictionary>();
- await acc.RegisterLightningNodeAsync("BTC", LightningTestImplementation.CoreLightning);
var store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
-
- var pmi = PaymentTypes.LN.GetPaymentMethodId("BTC");
- Assert.NotNull(store);
- var lnMethod = store.GetPaymentMethodConfig<LightningPaymentMethodConfig>(pmi, handlers);
- var originalConnectionString = lnMethod?.GetExternalLightningUrl();
- Assert.NotNull(originalConnectionString);
- var conf = store.GetPaymentMethodConfig(pmi);
- Assert.NotNull(conf);
- conf["LightningConnectionString"] = conf["connectionString"]!.Value<string>();
- conf["DisableBOLT11PaymentOption"] = true;
- ((JObject)conf).Remove("connectionString");
- store.SetPaymentMethodConfig(pmi, conf);
- 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.Equal(originalConnectionString, lnMethod?.GetExternalLightningUrl());
- Assert.False(lnMethod?.IsInternalNode);
- conf = store.GetPaymentMethodConfig(pmi);
- Assert.NotNull(conf);
- Assert.Null(conf["CryptoCode"]); // Osolete
- Assert.Equal(originalConnectionString, conf["connectionString"]?.Value<string>());
- Assert.Null(conf["DisableBOLT11PaymentOption"]); // Old garbage cleaned
-
- store.SetPaymentMethodConfig(PaymentMethodId.Parse("BTC-LNURL"),
- new JObject()
- {
- ["CryptoCode"] = "BTC",
- ["LUD12Enabled"] = true,
- ["UseBech32Scheme"] = false,
- });
- await tester.PayTester.StoreRepository.UpdateStore(store);
- await tester.RestartMigration();
- store = await tester.PayTester.StoreRepository.FindStore(acc.StoreId);
- Assert.NotNull(store);
- conf = store.GetPaymentMethodConfig(PaymentMethodId.Parse("BTC-LNURL"));
- Assert.NotNull(conf);
- Assert.Null(conf["CryptoCode"]);
- Assert.True(conf["lud12Enabled"]?.Value<bool>());
- Assert.Null(conf["useBech32Scheme"]); // default stripped
-
- // String-valued derivation schemes still need the newer store-config migration.
+ // This repair was added after 2.0.0 and is still needed by supported upgrades.
var xpub = "tpubDDmH1briYfZcTDMEc7uMEA5hinzjUTzR9yMC1drxTMeiWyw1VyCqTuzBke6df2sqbfw9QG6wbgTLF5yLjcXsZNaXvJMZLwNEwyvmiFWcLav";
var derivation = $"{xpub}-[legacy]";
- pmi = PaymentTypes.CHAIN.GetPaymentMethodId("BTC");
+ var pmi = PaymentTypes.CHAIN.GetPaymentMethodId("BTC");
store.DerivationStrategies = new JObject { [pmi.ToString()] = derivation }.ToString();
await tester.PayTester.StoreRepository.UpdateStore(store);
await tester.RestartMigration();
### BTCPayServer.Tests/PullPaymentsTests.cs
@@ -707,86 +707,6 @@ await TestUtils.EventuallyAsync(async () =>
});
}
- [Fact]
- [Trait("Integration", "Integration")]
- public async Task CanMigratePayoutsAndPullPayments()
- {
- var tester = CreateDBTester();
- await tester.MigrateUntil("20240827034505_migratepayouts");
-
- await using var ctx = tester.CreateContext();
- var conn = ctx.Database.GetDbConnection();
- await conn.ExecuteAsync("INSERT INTO \"Stores\"(\"Id\", \"SpeedPolicy\") VALUES (@store, 0)", new { store = "store1" });
- var param = new
- {
- Id = "pp1",
- StoreId = "store1",
- Blob =
- "{\"Name\": \"CoinLottery\", \"View\": {\"Email\": null, \"Title\": \"\", \"Description\": \"\", \"EmbeddedCSS\": null, \"CustomCSSLink\": null}, \"Limit\": \"10.00\", \"Period\": null, \"Currency\": \"GBP\", \"Description\": \"\", \"Divisibility\": 0, \"MinimumClaim\": \"0\", \"AutoApproveClaims\": false, \"SupportedPaymentMethods\": [\"BTC\", \"BTC_LightningLike\"]}"
- };
- await conn.ExecuteAsync(
- "INSERT INTO \"PullPayments\"(\"Id\", \"StoreId\", \"Blob\", \"StartDate\", \"Archived\") VALUES (@Id, @StoreId, @Blob::JSONB, NOW(), 'f')", param);
- var parameters = new[]
- {
- new
- {
- Id = "p1",
- StoreId = "store1",
- PullPaymentDataId = "pp1",
- PaymentMethodId = "BTC",
- Blob = "{\"Amount\": \"10.0\", \"Revision\": 0, \"Destination\": \"address\", \"CryptoAmount\": \"0.00012225\", \"MinimumConfirmation\": 1}"
- },
- new
- {
- Id = "p2",
- StoreId = "store1",
- PullPaymentDataId = "pp1",
- PaymentMethodId = "BTC_LightningLike",
- Blob = "{\"Amount\": \"10.0\", \"Revision\": 0, \"Destination\": \"address\", \"CryptoAmount\": null, \"MinimumConfirmation\": 1}"
- },
- new
- {
- Id = "p3",
- StoreId = "store1",
- PullPaymentDataId = null as string,
- PaymentMethodId = "BTC_LightningLike",
- Blob = "{\"Amount\": \"10.0\", \"Revision\": 0, \"Destination\": \"address\", \"CryptoAmount\": null, \"MinimumConfirmation\": 1}"
- },
- new
- {
- Id = "p4",
- StoreId = "store1",
- PullPaymentDataId = null as string,
- PaymentMethodId = "BTC_LightningLike",
- Blob = "{\"Amount\": \"-10.0\", \"Revision\": 0, \"Destination\": \"address\", \"CryptoAmount\": null, \"MinimumConfirmation\": 1}"
- }
- };
- await conn.ExecuteAsync(
- "INSERT INTO \"Payouts\"(\"Id\", \"StoreDataId\", \"PullPaymentDataId\", \"PaymentMethodId\", \"Blob\", \"State\", \"Date\") VALUES (@Id, @StoreId, @PullPaymentDataId, @PaymentMethodId, @Blob::JSONB, 'state', NOW())",
- parameters);
- await tester.CompleteMigrations();
-
- var migrated = await conn.ExecuteScalarAsync<bool>(
- "SELECT 't'::BOOLEAN FROM \"PullPayments\" WHERE \"Id\"='pp1' AND \"Limit\"=10.0 AND \"Currency\"='GBP' AND \"Blob\"->>'SupportedPayoutMethods'='[\"BTC-CHAIN\", \"BTC-LN\"]'");
- Assert.True(migrated);
-
- migrated = await conn.ExecuteScalarAsync<bool>(
- "SELECT 't'::BOOLEAN FROM \"Payouts\" WHERE \"Id\"='p1' AND \"Amount\"= 0.00012225 AND \"OriginalAmount\"=10.0 AND \"OriginalCurrency\"='GBP' AND \"PayoutMethodId\"='BTC-CHAIN'");
- Assert.True(migrated);
-
- migrated = await conn.ExecuteScalarAsync<bool>(
- "SELECT 't'::BOOLEAN FROM \"Payouts\" WHERE \"Id\"='p2' AND \"Amount\" IS NULL AND \"OriginalAmount\"=10.0 AND \"OriginalCurrency\"='GBP' AND \"PayoutMethodId\"='BTC-LN'");
- Assert.True(migrated);
-
- migrated = await conn.ExecuteScalarAsync<bool>(
- "SELECT 't'::BOOLEAN FROM \"Payouts\" WHERE \"Id\"='p3' AND \"Amount\" IS NULL AND \"OriginalAmount\"=10.0 AND \"OriginalCurrency\"='BTC'");
- Assert.True(migrated);
-
- migrated = await conn.ExecuteScalarAsync<bool>(
- "SELECT 't'::BOOLEAN FROM \"Payouts\" WHERE \"Id\"='p4' AND \"Amount\" IS NULL AND \"OriginalAmount\"=-10.0 AND \"OriginalCurrency\"='BTC' AND \"PayoutMethodId\"='TOPUP'");
- Assert.True(migrated);
- }
-
[Fact]
[Trait("Integration", "Integration")]
public async Task CanUsePullPaymentViaAPI()
### BTCPayServer.Tests/TestAccount.cs
@@ -1,10 +1,8 @@
using System;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
-using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.BIP78.Sender;
@@ -26,14 +24,12 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using NBitcoin;
-using NBitcoin.DataEncoders;
using NBitcoin.Payment;
using NBitpayClient;
using NBXplorer.DerivationStrategy;
using NBXplorer.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
-using Npgsql;
using Xunit;
using Xunit.Sdk;
@@ -660,55 +656,5 @@ public async Task<string> CreateLNAddress()
return lnAddrUser;
}
- public async Task ImportOldInvoices(string storeId = null)
- {
- storeId ??= StoreId;
- var oldInvoices = File.ReadAllLines(TestUtils.GetTestDataFullPath("OldInvoices.csv"));
- var oldPayments = File.ReadAllLines(TestUtils.GetTestDataFullPath("OldPayments.csv"));
- var dbContext = this.parent.PayTester.GetService<ApplicationDbContextFactory>().CreateContext();
- var db = (NpgsqlConnection)dbContext.Database.GetDbConnection();
- await db.OpenAsync();
- bool isHeader = true;
- using (var writer = db.BeginTextImport("COPY \"Invoices\" (\"Id\",\"Blob\",\"Created\",\"ExceptionStatus\",\"Status\",\"StoreDataId\",\"Archived\",\"Blob2\") FROM STDIN DELIMITER ',' CSV HEADER"))
- {
- foreach (var invoice in oldInvoices)
- {
- if (isHeader)
- {
- isHeader = false;
- await writer.WriteLineAsync(invoice);
- }
- else
- {
- var localInvoice = invoice.Replace("3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd", storeId);
- var fields = localInvoice.Split(',');
- var blob1 = ZipUtils.Unzip(Encoders.Hex.DecodeData(fields[1].Substring(2)));
- var matched = Regex.Match(blob1, "xpub[^\\\"-]*");
- if (matched.Success)
- {
- var xpub = (BitcoinExtPubKey)Network.Main.Parse(matched.Value);
- var xpubTestnet = xpub.ExtPubKey.GetWif(Network.RegTest).ToString();
- blob1 = blob1.Replace(xpub.ToString(), xpubTestnet);
- fields[1] = $"\\x{Encoders.Hex.EncodeData(ZipUtils.Zip(blob1))}";
- localInvoice = string.Join(',', fields);
- }
- await writer.WriteLineAsync(localInvoice);
- }
- }
- await writer.FlushAsync();
- }
- isHeader = true;
- using (var writer = db.BeginTextImport("COPY \"Payments\" (\"Id\",\"Blob\",\"InvoiceDataId\",\"Accounted\",\"Blob2\",\"PaymentMethodId\") FROM STDIN DELIMITER ',' CSV HEADER"))
- {
- foreach (var invoice in oldPayments)
- {
- var localPayment = invoice.Replace("3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd", storeId);
- // Old data could have Type to null.
- localPayment += "UNKNOWN";
- await writer.WriteLineAsync(localPayment);
- }
- await writer.FlushAsync();
- }
- }
}
}
### BTCPayServer.Tests/TestData/InvoiceMigrationTestVectors.json
@@ -1,763 +0,0 @@
-[
- {
- "type": "invoice",
- "input": {
- "id": "HuzCsv9hghew2FD6zVqUyY",
- "storeId": "3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd",
- "orderId": "CustomOrderId",
- "speedPolicy": 0,
- "rate": 5672.82929871779,
- "invoiceTime": 1538395793,
- "expirationTime": 1538396693,
- "depositAddress": "39mWwvUDoZ5CxXa6CmgaUda19qYj9LpQD1",
- "productInformation": {
- "itemDesc": "Masternode Staking",
- "itemCode": null,
- "physical": false,
- "price": 100.0,
- "currency": "EUR",
- "taxIncluded": 0.0
- },
- "buyerInformation": {
- "buyerName": null,
- "buyerEmail": "customer@example.com",
- "buyerCountry": null,
- "buyerZip": null,
- "buyerState": null,
- "buyerCity": null,
- "buyerAddress2": null,
- "buyerAddress1": null,
- "buyerPhone": null
- },
- "posData": null,
- "derivationStrategy": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR-[p2sh]",
- "derivationStrategies": "{\"BTC\":\"xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR-[p2sh]\"}",
- "status": "new",
- "exceptionStatus": null,
- "payments": [],
- "refundable": false,
- "refundMail": "customer@example.com",
- "redirectURL": "https://example.com/thanksyou",
- "txFee": 100,
- "fullNotifications": true,
- "notificationEmail": "legacy@example.com",
- "notificationURL": "https://example.com/callbacks",
- "serverUrl": "https://mainnet.demo.btcpayserver.org",
- "cryptoData": {
- "BTC": {
- "rate": 5672.82929871779,
- "paymentMethod": {},
- "feeRate": 1,
- "txFee": 100,
- "depositAddress": "39mWwvUDoZ5CxXa6CmgaUda19qYj9LpQD1"
- }
- },
- "monitoringExpiration": 1538400293,
- "historicalAddresses": null,
- "availableAddressHashes": null,
- "extendedNotifications": false,
- "events": null,
- "paymentTolerance": 1.0
- },
- "expected": {
- "version": 3,
- "metadata": {
- "orderId": "CustomOrderId",
- "itemDesc": "Masternode Staking",
- "physical": false,
- "buyerEmail": "customer@example.com",
- "taxIncluded": 0.0
- },
- "rates": { "BTC": "5672.82929871779" },
- "serverUrl": "https://mainnet.demo.btcpayserver.org",
- "prompts": {
- "BTC-CHAIN": {
- "currency": "BTC",
- "paymentMethodFee": "0.000001",
- "details": {
- "paymentMethodFeeRate": 1,
- "recommendedFeeRate": 1,
- "accountDerivation": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR-[p2sh]"
- },
- "divisibility": 8,
- "destination": "39mWwvUDoZ5CxXa6CmgaUda19qYj9LpQD1"
- }
- },
- "redirectURL": "https://example.com/thanksyou",
- "receiptOptions": {},
- "internalTags": [],
- "expirationTime": 1538396693,
- "notificationURL": "https://example.com/callbacks",
- "paymentTolerance": 1.0,
- "fullNotifications": true,
- "monitoringExpiration": 1538400293
- }
- },
- {
- "type": "invoice",
- "input": {
- "id": "ANjq7kkV4mqDRPr5F8EmLZ",
- "rate": "66823.066",
- "price": "30",
- "txFee": 0,
- "events": null,
- "status": "new",
- "refunds": null,
- "storeId": "8Ja5pfPydLZTt3YLWhZuZ5vfXT2bNfvk1krUhF8ykCyt",
- "version": 2,
- "customerEmail": "toto@toto.com",
- "archived": false,
- "currency": "USD",
- "metadata": {
- "orderId": "CC",
- "itemDesc": "CC"
- },
- "payments": [],
- "serverUrl": "https://mainnet.demo.btcpayserver.org",
- "cryptoData": {
- "BTC": {
- "rate": 66823.066,
- "txFee": 0,
- "feeRate": 15.13,
- "paymentMethod": {
- "keyPath": "0/25903",
- "activated": true,
- "networkFeeRate": 12.319,
- "payjoinEnabled": false
- },
- "depositAddress": "bc1quf9l42tnma7zws9vusrvun4wchau0ue4zj838g"
- }
- },
- "paidAmount": {
- "net": 0.0,
- "gross": 0.0,
- "currency": "USD"
- },
- "refundMail": null,
- "invoiceTime": 1709806449,
- "isUnderPaid": true,
- "redirectURL": "https://test/",
- "speedPolicy": 1,
- "checkoutType": null,
- "internalTags": [],
- "depositAddress": "bc1quf9l42tnma7zws9vusrvun4wchau0ue4zj838g",
- "expirationTime": 1709808249,
- "receiptOptions": {
- "showQR": null,
- "enabled": null,
- "showPayments": null
- },
- "defaultLanguage": null,
- "exceptionStatus": "",
- "notificationURL": null,
- "storeSupportUrl": null,
- "paymentTolerance": 0.0,
- "fullNotifications": true,
- "lazyPaymentMethods": false,
- "requiresRefundEmail": null,
- "defaultPaymentMethod": "BTC",
- "derivationStrategies": {
- "BTC": {
- "label": null,
- "source": "ManualDerivationScheme",
- "signingKey": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR-[p2sh]",
- "isHotWallet": false,
- "accountOriginal": null,
- "accountDerivation": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR-[p2sh]",
- "accountKeySettings": [
- {
- "accountKey": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR-[p2sh]",
- "accountKeyPath": "84/0'/0'",
- "rootFingerprint": "312e13db"
- }
- ]
- }
- },
- "monitoringExpiration": 1709894649,
- "extendedNotifications": false,
- "redirectAutomatically": false,
- "availableAddressHashes": null
- },
- "expected": {
- "version": 3,
- "metadata": {
- "orderId": "CC",
- "itemDesc": "CC",
- "buyerEmail": "toto@toto.com"
- },
- "serverUrl": "https://mainnet.demo.btcpayserver.org",
- "rates": { "BTC": "66823.066" },
- "prompts": {
- "BTC-CHAIN": {
- "currency": "BTC",
- "destination": "bc1quf9l42tnma7zws9vusrvun4wchau0ue4zj838g",
- "details": {
- "recommendedFeeRate": 15.13,
- "paymentMethodFeeRate": 12.319,
- "keyPath": "0/25903",
- "accountDerivation": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR-[p2sh]"
- },
- "divisibility": 8
- }
- },
- "receiptOptions": {},
- "redirectURL": "https://test/",
- "speedPolicy": 1,
- "internalTags": [],
- "expirationTime": 1709808249,
- "fullNotifications": true,
- "defaultPaymentMethod": "BTC-CHAIN",
- "monitoringExpiration": 1709894649
- }
- },
- {
- "type": "invoice",
- "input": {
- "currency": "USD",
- "price": 0.0,
- "cryptoData": {
- "BTC": {
- "feeRate": 10.0,
- "paymentMethod": {
- },
- "depositAddress": "bc1q9l42tnma7zws9vusrvun4wchau0ue4zj838g"
- }
- }
- },
- "expected": {
- "internalTags": [],
- "metadata": {},
- "version": 3,
- "prompts": {
- "BTC-CHAIN": {
- "currency": "BTC",
- "details": {
- "paymentMethodFeeRate": 10.0,
- "recommendedFeeRate": 10.0
- },
- "divisibility": 8,
- "destination": "bc1q9l42tnma7zws9vusrvun4wchau0ue4zj838g"
- }
- },
- "receiptOptions": {}
- },
- "skipRountripTest" : true
- },
- {
- "type": "invoice",
- "input": {
- "currency": "USD",
- "price": 0.0,
- "cryptoData": {
- "BTC": {
- "feeRate": 4.0,
- "paymentMethod": {
- "networkFeeMode": 2
- },
- "depositAddress": "bc1q9l42tnma7zws9vusrvun4wchau0ue4zj838g"
- }
- }
- },
- "expected": {
- "internalTags": [],
- "metadata": {},
- "version": 3,
- "prompts": {
- "BTC-CHAIN": {
- "currency": "BTC",
- "details": {
- "feeMode": "Never",
- "recommendedFeeRate": 4.0
- },
- "divisibility": 8,
- "destination": "bc1q9l42tnma7zws9vusrvun4wchau0ue4zj838g"
- }
- },
- "receiptOptions": {}
- },
- "skipRountripTest": true
- },
- {
- "type": "invoice",
- "input": {
- "id": "AmoigMwzbaBNNCfo21yns1",
- "rate": "67056.018",
- "price": "13",
- "txFee": null,
- "events": null,
- "status": "new",
- "refunds": null,
- "storeId": "2b4H99crZ4JuPiRQwUuYpLQsjtHWASLVWHHkQQ2moiED",
- "version": 2,
- "archived": false,
- "currency": "USD",
- "metadata": {},
- "payments": [],
- "serverUrl": "https://mainnet.demo.btcpayserver.org",
- "cryptoData": {
- "BTC": {
- "rate": 67056.018,
- "txFee": null,
- "feeRate": null,
- "paymentMethod": {
- "keyPath": null,
- "activated": false,
- "networkFeeMode": 0,
- "networkFeeRate": null,
- "payjoinEnabled": false
- },
- "depositAddress": null
- },
- "BTC_LNURLPAY": {
- "rate": 67056.018,
- "txFee": null,
- "feeRate": null,
- "paymentMethod": {
- "BOLT11": null,
- "NodeInfo": "03d2a44997a0fb6deee0a31c389d9d6bcb6f929f1dd0ba67201d195f2b3c76087c@170.75.160.16:9735",
- "Preimage": {},
- "Activated": true,
- "InvoiceId": null,
- "Bech32Mode": true,
- "PayRequest": null,
- "PaymentHash": {},
- "ProvidedComment": null,
- "GeneratedBoltAmount": null,
- "ConsumedLightningAddress": null,
- "LightningSupportedPaymentMethod": {
- "CryptoCode": "BTC",
- "InternalNodeRef": "Internal Node"
- }
- },
- "depositAddress": null
- },
- "BTC_LightningLike": {
- "rate": 67056.018,
- "txFee": null,
- "feeRate": null,
- "paymentMethod": {
- "BOLT11": null,
- "NodeInfo": null,
- "Preimage": null,
- "Activated": false,
- "InvoiceId": null,
- "PaymentHash": null
- },
- "depositAddress": null
- }
- },
- "paidAmount": {
- "net": 0.0,
- "gross": 0.0,
- "currency": "USD"
- },
- "refundMail": null,
- "invoiceTime": 1709864059,
- "isUnderPaid": true,
- "redirectURL": null,
- "speedPolicy": 1,
- "checkoutType": null,
- "internalTags": [],
- "depositAddress": null,
- "expirationTime": 1709864959,
- "receiptOptions": {
- "showQR": null,
- "enabled": null,
- "showPayments": null
- },
- "defaultLanguage": null,
- "exceptionStatus": "",
- "notificationURL": null,
- "storeSupportUrl": null,
- "paymentTolerance": 0.0,
- "fullNotifications": true,
- "lazyPaymentMethods": true,
- "requiresRefundEmail": false,
- "defaultPaymentMethod": "BTC",
- "derivationStrategies": {
- "BTC": {
- "label": null,
- "source": "NBXplorerGenerated",
- "signingKey": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR",
- "isHotWallet": true,
- "accountOriginal": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR",
- "accountDerivation": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR",
- "accountKeySettings": [
- {
- "accountKey": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR",
- "accountKeyPath": "84'/0'/0'",
- "rootFingerprint": "312e13db"
- }
- ]
- },
- "BTC_LNURLPAY": {
- "CryptoCode": "BTC",
- "LUD12Enabled": false,
- "UseBech32Scheme": true
- },
- "BTC_LightningLike": {
- "CryptoCode": "BTC",
- "InternalNodeRef": "Internal Node"
- }
- },
- "monitoringExpiration": 1709951359,
- "extendedNotifications": false,
- "redirectAutomatically": false,
- "availableAddressHashes": null
- },
- "expected": {
- "version": 3,
- "metadata": {},
- "serverUrl": "https://mainnet.demo.btcpayserver.org",
- "rates": { "BTC": "67056.018" },
- "prompts": {
- "BTC-CHAIN": {
- "inactive": true,
- "currency": "BTC",
- "details": {
- "accountDerivation": "xpub6DAbghfuRCW6Qqr3KfSDjik4kEUivAkfhcGHMkVEe4bZq53VQz79k44EoQ5MDpLJKKAPK5vVV6Px7U1R39eQibnbhDsW9uEQ1Kdh9CDbmgR"
- },
- "divisibility": 8
- },
- "BTC-LNURL": {
- "currency": "BTC",
- "divisibility": 11,
- "details": {
- "nodeInfo": "03d2a44997a0fb6deee0a31c389d9d6bcb6f929f1dd0ba67201d195f2b3c76087c@170.75.160.16:9735",
- "bech32Mode": true
- }
- },
- "BTC-LN": {
- "currency": "BTC",
- "divisibility": 11,
- "inactive": true,
- "details": {}
- }
- },
- "speedPolicy": 1,
- "expirationTime": 1709864959,
- "receiptOptions": {},
- "fullNotifications": true,
- "lazyPaymentMethods": true,
- "defaultPaymentMethod": "BTC-CHAIN",
- "internalTags": [],
- "monitoringExpiration": 1709951359
- }
- },
- {
- "type": "invoice",
- "input": {
- "id": "ULzMvaSEpvV4XxGb6F78LZ",
- "rate": "0",
- "type": "TopUp",
- "price": "0.0",
- "txFee": null,
- "events": null,
- "status": "new",
- "refunds": null,
- "storeId": "EBeAyDVUwBSNa6bdZNrytay9ARNL5UB9xnvNPh5xdnhy",
- "version": 2,
- "archived": false,
- "currency": "USD",
- "metadata": {
- },
- "payments": [
- ],
- "serverUrl": "https://donate.nicolas-dorier.com",
- "cryptoData": {
- "BTC_LNURLPAY": {
- "rate": 29501.4,
- "txFee": null,
- "feeRate": null,
- "paymentMethod": {
- "BOLT11": "lnbc10n1pjn9nmzpp5a7znt4tv9gy5v6342xrgnntltkljffp255dph40vaf6964j27pvqhp59ly2g7flsy97vqahh9yue8qz7u6tvlpjfh9r0m9nzfezhm6fgmqscqzzsxqzursp55l9zht4zya3jyjdr9khr22z6afvjqdcw06l7vyd6tksdtsc8ezqs9qyyssqwswp9dnz9txv8t8zjrrts9rv4agu40ufqc04434f6lszdwvlhjk45m3pdcpqzghswkrcvgeaztcr6h82xp35suu64hnk4ms929pcahgpfg7sza",
- "NodeInfo": "03d2a44997a0fb6deee0a31c389d9d6bcb6f929f1dd0ba67201d195f2b3c76087c@170.75.160.16:9735",
- "Preimage": null,
- "Activated": true,
- "InvoiceId": "ef8535d56c2a09466a35518689cd7f5dbf24a42aa51a1bd5ecea745d564af058",
- "Bech32Mode": true,
- "PayRequest": {
- "tag": "payRequest",
- "callback": "https://donate.nicolas-dorier.com/BTC/UILNURL/pay/i/ULzMvaSEpvV4XxGb6F78LZ",
- "metadata": "[[\"text/identifier\",\"donate@donate.nicolas-dorier.com\"],[\"text/plain\",\"Paid to Nicolas Donation Store (Order ID: )\"]]",
- "maxSendable": 612000000000,
- "minSendable": 1000,
- "commentAllowed": 0
- },
- "PaymentHash": "ef8535d56c2a09466a35518689cd7f5dbf24a42aa51a1bd5ecea745d564af058",
- "ProvidedComment": null,
- "GeneratedBoltAmount": "1000",
- "ConsumedLightningAddress": "donate@donate.nicolas-dorier.com",
- "LightningSupportedPaymentMethod": {
- "CryptoCode": "BTC",
- "InternalNodeRef": "Internal Node"
- }
- },
- "depositAddress": null
- }
- },
- "paidAmount": {
- "net": 0.0,
- "gross": 0.0,
- "currency": "USD"
- },
- "refundMail": null,
- "invoiceTime": 1697828706,
- "isUnderPaid": false,
- "redirectURL": null,
- "speedPolicy": 1,
- "checkoutType": null,
- "internalTags": [
- ],
- "depositAddress": null,
- "expirationTime": 1697829606,
- "receiptOptions": {
- "showQR": null,
- "enabled": null,
- "showPayments": null
- },
- "defaultLanguage": null,
- "exceptionStatus": "",
- "notificationURL": null,
- "storeSupportUrl": null,
- "paymentTolerance": 0.0,
- "fullNotifications": false,
- "lazyPaymentMethods": false,
- "requiresRefundEmail": null,
- "defaultPaymentMethod": "BTC",
- "derivationStrategies": {
- "BTC_LNURLPAY": {
- "CryptoCode": "BTC",
- "LUD12Enabled": false,
- "UseBech32Scheme": true
- }
- },
- "monitoringExpiration": 1697833206,
- "extendedNotifications": false,
- "redirectAutomatically": false,
- "availableAddressHashes": null
- },
- "expected": {
- "type": "TopUp",
- "version": 3,
- "rates": {
- "BTC": "29501.4"
- },
- "metadata": {
- },
- "serverUrl": "https://donate.nicolas-dorier.com",
- "prompts": {
- "BTC-LNURL": {
- "currency": "BTC",
- "divisibility": 11,
- "destination": "lnbc10n1pjn9nmzpp5a7znt4tv9gy5v6342xrgnntltkljffp255dph40vaf6964j27pvqhp59ly2g7flsy97vqahh9yue8qz7u6tvlpjfh9r0m9nzfezhm6fgmqscqzzsxqzursp55l9zht4zya3jyjdr9khr22z6afvjqdcw06l7vyd6tksdtsc8ezqs9qyyssqwswp9dnz9txv8t8zjrrts9rv4agu40ufqc04434f6lszdwvlhjk45m3pdcpqzghswkrcvgeaztcr6h82xp35suu64hnk4ms929pcahgpfg7sza",
- "details": {
- "nodeInfo": "03d2a44997a0fb6deee0a31c389d9d6bcb6f929f1dd0ba67201d195f2b3c76087c@170.75.160.16:9735",
- "invoiceId": "ef8535d56c2a09466a35518689cd7f5dbf24a42aa51a1bd5ecea745d564af058",
- "bech32Mode": true,
- "payRequest": {
- "tag": "payRequest",
- "callback": "https://donate.nicolas-dorier.com/BTC/UILNURL/pay/i/ULzMvaSEpvV4XxGb6F78LZ",
- "metadata": "[[\"text/identifier\",\"donate@donate.nicolas-dorier.com\"],[\"text/plain\",\"Paid to Nicolas Donation Store (Order ID: )\"]]",
- "maxSendable": 612000000000,
- "minSendable": 1000,
- "commentAllowed": 0
- },
- "paymentHash": "ef8535d56c2a09466a35518689cd7f5dbf24a42aa51a1bd5ecea745d564af058",
- "generatedBoltAmount": "1000",
- "consumedLightningAddress": "donate@donate.nicolas-dorier.com"
- }
- }
- },
- "speedPolicy": 1,
- "internalTags": [],
- "expirationTime": 1697829606,
- "receiptOptions": {},
- "defaultPaymentMethod": "BTC-CHAIN",
- "monitoringExpiration": 1697833206
- }
- },
- {
- "type": "payment",
- "input": {
- "version": 1,
- "receivedTime": 1556044076,
- "networkFee": 0.000002,
- "outpoint": "552b74ff2fc2c8564de40c8cbefd8eb78f1bef5d3010009c643ff889e159663a3d000000",
- "output": "7a636f000000000017a914fd2a2d1d15eb6a490512953c12d6db0de662741d87",
- "accounted": true,
- "cryptoCode": "BTC",
- "cryptoPaymentData": "{\"ConfirmationCount\":1414,\"RBF\":false,\"NetworkFee\":0.0,\"Legacy\":false}",
- "cryptoPaymentDataType": "BTCLike"
- },
- "expected": {
- "version": 2,
- "destination": "3QmdQXq3tSMqiuwNy2ZcbFEHxZ5De4SBYJ",
- "paymentMethodFee": "0.000002",
- "divisibility": 8,
- "details": {
- "confirmationCount": 1414,
- "outpoint": "3a6659e189f83f649c0010305def1b8fb78efdbe8c0ce44d56c8c22fff742b55-61"
- }
- },
- "expectedProperties": {
- "Created": "04/23/2019 18:27:56 +00:00",
- "PaymentMethodId": "BTC-CHAIN",
- "Currency": "BTC",
- "Status": "Settled",
- "Amount": "0.07299962",
- "Accounted": null
- }
- },
- {
- "type": "payment",
- "input": {
- "receivedTime": 1538403202,
- "outpoint": "3211391d9dd2d01c8d9f164d0231f72a166c9b27b15fb2603f58a193ca47bea800000000",
- "output": "c74500000000000017a9145d741911858531a4e0a8b6a58bf5036d7f68857587",
- "accounted": true,
- "cryptoCode": "BTC",
- "cryptoPaymentData": "{\"ConfirmationCount\":19,\"RBF\":true,\"Legacy\":false}",
- "cryptoPaymentDataType": "BTCLike"
- },
- "expected": {
- "destination": "3AD9r1UyXXNFA2o3cucBwqX58xNaXvrdsv",
- "divisibility": 8,
- "details": {
- "confirmationCount": 19,
- "rbf": true,
- "outpoint": "a8be47ca93a1583f60b25fb1279b6c162af731024d169f8d1cd0d29d1d391132-0"
- },
- "version": 2
- },
- "expectedProperties": {
- "Created": "10/01/2018 14:13:22 +00:00",
- "PaymentMethodId": "BTC-CHAIN",
- "Currency": "BTC",
- "Status": "Settled",
- "Amount": "0.00017863",
- "Accounted": null
- }
- },
- {
- "type": "payment",
- "input": {
- "output": null,
- "version": 1,
- "outpoint": null,
- "accounted": true,
- "cryptoCode": "BTC",
- "networkFee": 0.0,
- "receivedTimeMs": 1711005875969,
- "cryptoPaymentData": "{\"amount\":1000,\"bolT11\":\"lnbc10n1pjlhc90pp5smwdey0c5skr758lpm0w7tf56cafmdd0hey2nylwfl9q398jgf5shp5qra0y2q5w98at2vv0upux3sn2p0efrxs4h2nyzghqcj7009nqpsqcqzzsxqyz5vqsp5y8fvj3dxnwdaavx89nc5vykuywcmzdefh7x7z62q873hmawh7pws9qyyssq8f7ptu037y2vcclwst6nj8cy8ndhrcxj729ea4ntwdmpgtrwfqun5jnh4zul9s7vvtqd58wurdzk9e3xpzs3ykm0umjdwcttfussaxqqayadfs\",\"paymentHash\":\"86dcdc91f8a42c3f50ff0edeef2d34d63a9db5afbe48a993ee4fca0894f24269\",\"paymentType\":\"LNURLPAY\",\"networkFee\":0.0}",
- "cryptoPaymentDataType": "LNURLPAY"
- },
- "expected": {
- "version": 2,
- "divisibility": 11,
- "destination": "lnbc10n1pjlhc90pp5smwdey0c5skr758lpm0w7tf56cafmdd0hey2nylwfl9q398jgf5shp5qra0y2q5w98at2vv0upux3sn2p0efrxs4h2nyzghqcj7009nqpsqcqzzsxqyz5vqsp5y8fvj3dxnwdaavx89nc5vykuywcmzdefh7x7z62q873hmawh7pws9qyyssq8f7ptu037y2vcclwst6nj8cy8ndhrcxj729ea4ntwdmpgtrwfqun5jnh4zul9s7vvtqd58wurdzk9e3xpzs3ykm0umjdwcttfussaxqqayadfs",
- "details": {
- "paymentHash": "86dcdc91f8a42c3f50ff0edeef2d34d63a9db5afbe48a993ee4fca0894f24269"
- }
- },
- "expectedProperties": {
- "Created": "03/21/2024 07:24:35 +00:00",
- "CreatedInMs": "1711005875969",
- "Amount": "0.00000001",
- "PaymentMethodId": "BTC-LNURL",
- "Currency": "BTC"
- }
- },
- {
- "type": "payment",
- "input": {
- "output": null,
- "version": 1,
- "outpoint": "2e0ee2cccec304926677621ab5c1c80723f695740f1aed6915b4e72995d8172016000000",
- "accounted": true,
- "cryptoCode": "BTC",
- "networkFee": 0.0,
- "receivedTimeMs": 1710974348741,
- "cryptoPaymentData": "{\"confirmationCount\":6,\"rbf\":false,\"address\":\"bc1qdamnd0fjegj4a5efrwx4gvjc69zufmu7ntf5ft\",\"keyPath\":\"0/708\",\"value\":197864,\"legacy\":false}",
- "cryptoPaymentDataType": "BTCLike"
- },
- "expected": {
- "destination": "bc1qdamnd0fjegj4a5efrwx4gvjc69zufmu7ntf5ft",
- "divisibility": 8,
- "details": {
- "confirmationCount": 6,
- "keyPath": "0/708",
- "outpoint": "2017d89529e7b41569ed1a0f7495f62307c8c1b51a6277669204c3cecce20e2e-22"
- },
- "version": 2
- },
- "expectedProperties": {
- "Created": "03/20/2024 22:39:08 +00:00",
- "CreatedInMs": "1710974348741",
- "Amount": "0.00197864",
- "PaymentMethodId": "BTC-CHAIN",
- "Currency": "BTC",
- "Status": "Settled",
- "Accounted": null
- }
- },
- {
- "type": "payment",
- "input": {
- "output": null,
- "version": 1,
- "outpoint": "2e0ee2cccec304926677621ab5c1c80723f695740f1aed6915b4e72995d8172016000000",
- "accounted": true,
- "cryptoCode": "BTC",
- "networkFee": 0.0,
- "receivedTimeMs": 1710974348741,
- "cryptoPaymentData": "{\"confirmationCount\":6,\"rbf\":true,\"address\":\"bc1qdamnd0fjegj4a5efrwx4gvjc69zufmu7ntf5ft\",\"keyPath\":\"0/708\",\"value\":197864,\"legacy\":false}",
- "cryptoPaymentDataType": "BTCLike"
- },
- "expected": {
- "divisibility": 8,
- "destination": "bc1qdamnd0fjegj4a5efrwx4gvjc69zufmu7ntf5ft",
- "details": {
- "confirmationCount": 6,
- "keyPath": "0/708",
- "outpoint": "2017d89529e7b41569ed1a0f7495f62307c8c1b51a6277669204c3cecce20e2e-22",
- "RBF": true
- },
- "version": 2
- }
- },
- {
- "type": "payment",
- "input": {
- "output": null,
- "version": 1,
- "outpoint": null,
- "accounted": true,
- "cryptoCode": "XMR",
- "networkFee": 0.0000000019,
- "receivedTimeMs": 1705500405468,
- "cryptoPaymentData": "{\"Amount\":62700000000,\"Address\":\"85CjjvQyW7PjNmiFRKZuEHKzZjiB3rjSu6n8zPzji4PtQxw1CyEY5H5FBge6GRUMJqR7FqsgBHU7H1FpEppvZXS6HGpFF6t\",\"SubaddressIndex\":23,\"SubaccountIndex\":0,\"BlockHeight\":3063946,\"ConfirmationCount\":10,\"TransactionId\":\"cc2e9ef03864c6af5e0d6f1c730ba142144f6588c50035b2996a59a6f3771b06\",\"LockTime\":0}",
- "cryptoPaymentDataType": "MoneroLike"
- },
- "expected": {
- "divisibility": 12,
- "destination": "85CjjvQyW7PjNmiFRKZuEHKzZjiB3rjSu6n8zPzji4PtQxw1CyEY5H5FBge6GRUMJqR7FqsgBHU7H1FpEppvZXS6HGpFF6t",
- "details": {
- "blockHeight": 3063946,
- "confirmationCount": 10,
- "lockTime": 0,
- "subaccountIndex": 0,
- "subaddressIndex": 23,
- "transactionId": "cc2e9ef03864c6af5e0d6f1c730ba142144f6588c50035b2996a59a6f3771b06"
- },
- "version": 2
- },
- "expectedProperties": {
- "Amount": "0.0627",
- "PaymentMethodId": "XMR-CHAIN",
- "Currency": "XMR",
- "Status": "Settled",
- "Accounted": null
- }
- }
-]
### BTCPayServer.Tests/TestData/OldInvoices.csv
@@ -1,11 +0,0 @@
-Id,Blob,Created,ExceptionStatus,Status,StoreDataId,Archived,Blob2
-Q7RqoHLngK9svM4MgRyi9y,\x1f8b080000000000000ac454cb76da400cfd97595302b1c1981d6012124c0e8f104e12b2f043b627d833663c767073f2655df493fa0bd50049714fbae9262b1f4ba3ab2be94abf7efc7c25d4275d3233e65b3eb2593836b362a24fc27949cd92d44826b9802bf544cbc2e5602097fdb0bde8d8d71be1fa416fe566d7936dbfbcb08362b17dbe6cefc6fdd5d0c7402e7c102a90e5718c3829803fe531f54ad26dd4887024906ebb65b6eb9a6e187adbd0b4965e2394159c7a704b1374375b5a4733b596765e23b04b290651ce4e7dbaae7c3ea43ca3b2e7fb02b24c71ed9b634b338ca56d19c3fb6075afcd4661b0ea5ce8fd17695ba14d91612ab89f7bf28a055c247b64d2c57648482cc83c44710104be539601f7e1bd94342a33ea3931e9064e9c810242c6a46bd4b12e2f1702982a922c171679ab11372fb111d5247bdb8d937c60ee0dc3c4a171c532e03993a2acd81e685af95fc87d2b4fa3a8ac861c1b73fe99b159314e23ce8e60481dbb6a39d2797f8103a5c5be868554f30b5595bb3477db56cf0da3209f0f56edd95668e360613dd38dbe192e69d1db049177399a6cee86a0bb0fdb967637fb6e981b5d1ff2596b62a5f6f578dc9b8e5bc5dd5d7bba3396cdb966c28cbacc8dac6c65e6c35973ec47e6c0729370feed313dcfa227f2091b0a6af4af6bd2bf1dac4977fd45d4d6e46dbf378ecc151f062ff80b3b0fd203d783fd2825a74c8049fc7f7cc29d802067bee3c6f021ad836972a20b013e15e0c9e5dc46f448ca34eb9e9d254e264130542926de5016d63d9e605eb9bb00b52c0d946680f1375cd200c5aba8605629724cc24e8c7bd8e3ca8228402c455cc943190359f721e175577a58c0e1599d8b10f379a24c253f88e6550d427dfeb5ebc7ea2720238e87e215151700ccf7af9b55eeffb3e108677f3103c44b38a378437124c38f0bf67ebd3a0d75bd22aa8eacba284770a5e3c3089c0227af0471f48c9c2cfae3859d04e683ffd7508fd281e2a0ac8ad26e790cc261ea5c35eb8db7df000000ffff0300d1083b8e01060000,2018-10-01 11:32:12+00,,expired,3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd,f,
-Ka6GHBrFJPRwFRga1RD6Yz,\x1f8b0800000000000003c454cd769a4014dee7297258b74682a066a7427e24e6284a729a9fc5001798083364188826c727eba28fd457e830101353db45375dcef7cdbdf7bbbf3fbfff783d383c5470a09c1c2a3632cece87ec743c759e4f9d08a98e697c7b51be543f724e195cc86f5a1eb9a31177879131ef5d8e97cc0bc2c18d978f274fc3f5e96558ce9f1ecf8c953dbcb182da98b2009834264592d4fe3280604a13ecaf05dc9618431cc44337ba46abad6aed76db50b5635d72989414fbb0c069f545d5b59ed6eff4f4da10561916c698921d5eef367c0019cd311f0401833c973998b7a5e742ef7110a7fd65e9f62889c7b6f5726b777d3fc25c9fd5ca334683c2e71724a42c9511847555b24a1287d484dcaffc9d310072b80024cd1a724403f89073e52e5ee7d84789404394e4f00633915a558656fbb881fc823120b2388ae53a8a4037529157ac452df7e991cc154a3fc594b095229cecc147b4209cadf730b738db83ce79dda3dffc60becf4953f1e33f53ea1e6a1a53f216649bb7e8a08938fa384362a870298b30e7d5ec44b25aabacf00c73e045715838a31b63f6c4343b9c9b8f78d9595a2e2e07cb30f6cfce27cb6b0b3adeed93ae5dcf5ebafd65a763d1993e31b3cbb16d0fa6b65e5e5f1bd355d7551dad0f33ec112f36f39b7e61cd543b88fb23d34b23e7eb5d769cc70fca7e4518e4b8bdde2bc3c5e85e39b9ff4ff2ee95cddb1e235e484d049e95667b7cc86acd0db7ad7086d629105e61770ff58e4258900079097c9ce1069eec0e994003ccc0e7ae7359458c39cff293a3a314e51c1811db21d42c31895a3e4d6b2d7c750a7281dbf5e686c2d515e538145b5349ac947056d441c907a20ef17e5e8095c05c96ecc6c584006f0590d296c77d915dfdaf455954c7f7d93ae3b419b466af44e7b68fbf5fa97a99eb9a4d80c7b43a79af9b2d150238b5b5bac53e652cb17fba57d278b3dd9794122c6eb6a8aeb5bd8edbcbd8d79acb18e3eab05727a909063bfd47a5e868d5ec863d4779bcfb03561c4800c1e726bd8f0694cd047d9eaa054d8021222f9fda6a1f6c7e010000ffff0300ddecc9e08e060000,2018-10-01 11:54:10+00,,expired,3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd,f,
-Q3kZ3F8cUD57WUqcc8QLs2,\x1f8b0800000000000003c4544972da4014ddfb1494d6099110a377806463a662b0c085f142c3176a23758b564b86b83859163952ae90564b96812259649365bff77ffff9fdfaf1f3fda654929023dd96a4a9ba5da9774ddbd06a8da5b1b3ede6741855a42fa945c408850761a6461ba3db654667539f3787fd2db51cb7bdb4a2fe68d739dc0ddd64be7bbdafef079da5ee64ce843a4085338e7d3ffb2f047026c447f681c3b2c0a8c9803f6af546bd2c2baa2ccb7545add404877042900d8f28484d949ada545bd566a32248d887883b2382cff85a23e71d08498458db71284491a861921876af3f1ec361bc5bb4d427dadb57bcfba145f4fd66fe36795a6599879438b1cd1eb04b68202270efb465694a0c020d223bfd6f64460c28260e94e6ccdc22bc11feb95597e327c5a7ff7a8708d9a6cf51d7f423f88029af916395b29c23764c2960d12449376612478f22332b3ef09e5ecb4b306333b80829603d30917f05ef9218337ab8c2ac507805e545b26bff7711bbf649def9ca9f29e50a35f108fe0852d4cd27a999cc3cdd25be5c28114d98b3748736a25bfb30b6ea5adbda786e3ceb2eebd31d5507ee5c7b45dbea563750d2deba9e7ddf1b6d173a54add5aea62ea6df1bad6db5aa93696da485c3fe60d09e0c6ac962519fec1b8632535b304516b63c2d5ab6627daa0c1cafd5d5ac6033fbfa1c5622ef45ba9e1102b176ef6ba9f3d85d4bb7ebff94de5a3a7edcb3c9629113863729bf221bc22ce79c2b3a1c9a8700304bb1e797ec56c18db1635a3e9cae700e8fce978ca30ea2603363364c237a8c85d1edb76f417134517633659b04592e6c7f07e290e54c1a5cfed59830e4f2a349534c336134ce82e213220bf129334013a006f5cfe3228c81951d0848d96236af2eb32b139addad64d343c848be68f95df1c9158fbfab5576cb59cf46c03c924adffbb1a05c8059e6ad14d845c502fb27dd12cec7e25e028211d76ede5dbd50c942215b6aae901e4a053e55a43c189ccddf4cf844d361e76ccf8cbc730bd833c00e389743fa5c0d48f20dbadcaa47e20335b1103ea52cdf1c7f030000ffff03003e6b8efb96060000,2018-10-01 11:54:32+00,,expired,3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd,f,
-FSktP1Nrxu7arh7TUFAgTZ,\x1f8b0800000000000003c4554b72e33610ddcf295c5c27b23e16297a1599923c63591efd55f1781620d1143124011a0035545c3a59163952ae10008415d9a54caab2c992af5f773ff48f7ffefec7cb878b0b8760e7fac2192d52396d3df0aaf4104fbce56ad4df2e1f9d9f344348c6e193a175c47615047275b37517bdfbbb948738ee6f42713779bed98feee3dde2f9dbad5b8d6f36435c3b338e81d7ce41a922e59f2d50872e00f0946524da2b46d3601c49501f5dd76b377a6dbfedf7bc96e7f9c646e88e91089624d79456b7d3ebf8dd66a76b8c501544391346dfda7d6bc7503041641f630e4298e70c969bd093de7886d63de1a2ea7b67ddc28fb76595dcfdba1db9eeb296597086cb487ea231e3b9c9a0bc75f5b42409f90044a4e34d9090c029c370b1902825746bfc2d2b50b862d132cb2c5a247b41229429344699805798ab376afdcd66a369b1a8e41ca82993335ccd1d851e8cb6b0dcab7a9e53662c0f287f97d4c0c31c119d56c5d54d01fe0b54282f3268442c774e99012ba9e4fb33311e497106550f97e73206449e0b62bbd1fe6753eb8c699a30fa9ae45809d5dd0192e884ae5acec9ce946521f55c6d4dfdaaa20cdd413fdc2671390f36eeec9977c6f162f08da457e9704576fd344ea2db8f93743d84abf0f1b9db59cf7ef3fcf4ea6ac866ddc9a0b8bf1b8ffbd37177b75ebbd3ca5bb5e61d1f6624a46132101bbf1cce5a639cf8c120ccb7f39fbf146d917c75ce2b226046f1e5c9b959064fcef5d3ff24efc939bcae3b92a5d144e1bb63372b82a2d66c6dc70a17689f03951afbf2b5de5f884b8a5198c1e9585b78f26f63a778987088e46a7eaf89899485b8bebc3ce15dca04d154ec59597bc86a04765dcc77acb43d304962b55a5ab4d6267959cba027861fa4504b9985284a85ad09f01df015cf4ef96a852805d9c090b3462823558a9ad760bc5e7c27e2fb42323b95762d559b8f1f3f3e77f531a80b3c0199307d465f0e47530c30afbd5b47ec5d310cf69f0e9f713e1c972b6794a8ff803a69c3e3993d9e58bf6b4f6c42f4cf429f349b0cde0c0bdaa9f6ebc9b0d68f48246f195049a018f0fbfefd3d47b0b3e3f67e04972c038e687d391bcd0f87bf000000ffff030075db901fe2060000,2018-10-01 11:57:15+00,,expired,3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd,f,
-HuzCsv9hghew2FD6zVqUyY,\x1f8b0800000000000003c455cb76d33010ddf3153d5e439aa75377456aa794268126a913286521dbe358b52d3992ecc6edc997b1e093f80564590d694f8073d8b0f49d3b3357f3f28f6fdf1f5f1d1d1938304e8f8c8bfcc1e68515ad22b86f9f3be6c362ed969f8dd715830bcae0bda275f8cab56de19eadccf9c9f832665e100e961ebf9caccfcaf37158ccd777efcccde86c390c6a67ca0260b5b39dcb48e9470dd4a13380e08a26d82f25a3a9308604c88f9ed96f374eda56db3ae9b7fa7d4bd9302928f6e11aa715a5d5eb9c74ac5edfea28236c322c9d3125cfeca6a9ed01649463310802069cabe758e9f2be701d7ad3b3379f9069a72be406a865ad3fdf59e36ceab46a9919a341ee8bf724a42c5519a47755bd4a9280d401ee57f126880b60840670341728c664a5fc35cb96b864913c49349a4525c73e4a241aa284c313cce41b2bfdcd66a3a9313f670c882a933174678644b74a9b9797b29e879429cb0794be48aae0618a709556c6ad9a02ec2d6c509a25d0f0696aec336d9a13c1ca03316e707600950f178732da581c0aa2bbd1febda975c0741551f294645709d95d0709b447972d67b85065998b6aae56aa7e9b2cf74c67e0ada2309fd94b73ba669d513877ee70dc8d872e2e067118f9ef2e26f162085def66ddeb2ca60f7d2bee768774da9b38d9f872341a5c8d7ac562615e6dfa6e6bd6b1608a3de2450e5f5af970da1a0591653b5eba9abdf992b579f4d538ac08831ac5c75be3ecdabe354e6fff93bc5b63fbb4ee48e44a13817b436f960f59ad59db7615ce5099021115f6e56bbdbf10e624405e02fb63ade1c9dfc64ef202ccc017ee6c5c112321327e7a7cbcc73b161122312f695e7b88cd39e87551dfa1d4f6810a1ccad5aa4457da04cb6b1964cff087147229130ff931d7350156007359b2cf972b4408884600296d78c297a5a8790dcaeac5377c566682eaa9d46b29dbbcfbf8f3b9ab8f415de00988885667f471bb338500b3dabbb5c35e144361ff74f894f376b75c292558fe07e4491beeceac3eb1dd66b3ad4f6c84ab9f4575d2743278362ca890edaf26435b2f108f9e336023800410bcecdfaf3982428fdbcb11bca6093044eacbd968bedafe040000ffff030069b828dae2060000,2018-10-01 12:09:53+00,,expired,3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd,f,
-YZV1PQasUKEXdSkSV69XDL,\x1f8b0800000000000003c455cb76db3610dde72b7cb86e65911429cbabca1463c792523d2c39759c05480c4584244003202bd5475fd6453e29bf50108455d9474dcfe9a64bdeb93373312f7efff3dbf3bbb3338b60ebf2ccfaed616dcfe648acc6e127bccc966b7ff06934b17e6a1842320e1f34cd159b5510c8d5d5c65f5e4c6e331ee164781f89dbe9d3d5eefd24a9974f5faffdedf8ea3ec4ad33e31878eb1c542a52f1ab01dad025009eb19cc43bc5e86a8c2309eac3f37da7e3f56cd7f55dcf751c6d23b46624863b523414db732fdc81ef38b636c2b624ca9930facadeb78d1d43c90491438c3908a19f33b85927f2b62f2807a7866c7ce1f5c49dbc76275e9a08e7a2ba6e65969ce12a961f68c278a13328efa67a8d2409c50844dcc49b2221815386e16c295146e846fb1b56a070c5a2559e1bb44c7782c42857688272012f30576f6cf477bb9daec1e28a73a0ba4c56b85a580add6b6d51b553f53ca54c5b3ea2e24d520d8705224d5a15b7690af05f608b8a32874ecc0aeb9819b08a4abe3b11e381942750f570792a6340e4a920a61bce3f9bec13a659cae84b92432554774748a223ba6a3927b52ecb523673b5d1f5db9655e48f86d1264daa4570efcf9fb83b4e96a3af24eb65e18ad4c32c49e3eb9b69b60ea1173d3c79ee7afe477f90f57a219b7bd35139b91d8f87b3b157afd7fe6cdb5fd90b77007312d1281d89fb4115ceed314e07c1282a368b9f3f978e48bf58a71511d0a3f8fc685ddd058fd6e5e3ff24efd1dabfac3b9295d644e177cb6c560c65abd9d80e152ed1ae002a1becf397767f21a92846510ec7636de0e9bf8d9de261c22196abc5a421a65296e2f2fcfc88772e534433b16355eb21b7efc1ac8bfe4e94b68f4c9244ad5623bad12679d5caa047861fa4504b994728ce84a909f01af88ae7c77cb5429482ec6028582792b12a45cbeb30de2ebe15f35d2999994ab396aacd878f1f9fbbf618b4059e824c5973469ff7075302b068bded03f6a6181afb4f874f3bef0fcb55304ad47f409db4f07066cd89ed75bb7d736253d2fc2c9a936692c1ab6141b56a7f3319c67a8344fa9a015b0914037edbbfbfe7086a336e6f47f08ee5c0116d2f67a7fb6eff17000000ffff03003a3b8e5ae2060000,2018-10-01 12:17:01+00,,expired,3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd,f,
-3qtdXmycQwhWEPs91MExB2,\x1f8b0800000000000003c455cb769b4810dde72b7c5827b21002455e4502f2b0a48c1e96e538cea2a10bd106ba5177238bf8e8cb66319f34bf90a6c18aeca324e7cc6696dcba5575bb5efcfbf73f8fafcece0c828d8b33c3da487c9395e1ec215ef953d13727fe6ed8315e570c2119874f354dac97ae2b97c3b5b3783bbe4c7880a3c12a109793cdb07c3f8eb68bcdfd0767371aae7c5c3b338e81d7ce6ea122657f35401d3a07c0539692b0548cb6c63892a03e6cc7e9b4ecae69598e655b9d8eb611ba6524842b925514d3b6de5a7dc7b11d6d845d4e943361f499bd6737760c3913440e30e620847e8ef9b0bcf70a6bf6ddc3e3e48bdfe38e7f39ef4d2837931b424641af969973868b507ea211e399cea0bcabea559224641e88b08a37414202a70cc3d942a284d0b5f66f58aec2158b1669daa0795c0a12a254a1114a053cc15cbd51eb373bad76038605e740759d0c7f393714bad7e282a254053d254d5b3ea3ec45560dfb1922555e15b7ea0af077b043599e422b649971cc745941252f4fc4b825f90954bd5c9ecae812792a48d38eceaf4de609d33466f429c9a112aabd1e92e888ae7acec956976521abc15aebfaedf22270bc41b08ea362eeae9cd9865ba368e1dd93a49bf84bb21d24511c7ef83849ae7de806b71bdbba9e7deff5936ed767337be2e5e3cbd168301dd9dbeb6b67baeb2dcdb9d587190968107b62d52ffc9939c271dff5826c3d7ff335ef88f89b715a11013d8b8f77c6f0cabd332eeefe277977c6fe69df912cb4260a0f46b35a21e4b5e6c676a8708eca0ca8acb0afdfea0586a8a01805291ccf75034ffe34768a870987502ee7e38a184b998b8bf3f323deb98c114d44c98ada43eede83de97767d4122a5ed33932452bb5589aeb4495ed432e891e13729d456a6010a13d1d404f816f892a7c77cb54294826c61c8582b90a12a45cd6b315e6fbe11f23297ac99ca662d559b0f1fbfbf77f535a80b3c0119b3ea8e3eee0fa608605e7b9b07ec453134f69f2e9f76de1f962b6394a81f81ba69fee1ce3637b6db36cde6c6c6a4fa5b5437ad4906cf86056d55fbabc968ac1f91889f3360278162c02ffbf7738e60db8cdbcb11bc62297044ebd3d96abfdaff000000ffff0300fd61e9cae3060000,2018-10-01 12:24:16+00,,expired,3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd,f,
-BtJGr7kt52QkZe8RdhKz42,\x1f8b0800000000000003c455c172da4810bde72b5c3a6f301208249f168462078cd780c115e21c469a161a4b9a9167465a888b2fcb219f945fc86824b3d8c566abf692a3de7b3dfda6a7bbf5e3dbf7e777676706c1c6c5993194e34bde4fa46dcd923538731c4fbe762de38f4a2124e3f051cb3a62b3f43cb91c6e7a0be77a9cf0004783fb408ca74fc3dd87eba85c3c3d5ef6b693e1bd8feb60c631f03ad82bd449d95f0d501f9d03e05b969270a7146d8d7124417dd83dc76a5996d9711dc771db3dcd115a3212c21dc92a8969779c8edb6ff72d4dc236272a9830fa9a771b1e43ce0491038c3908a1af73152d3ee55bfea9fb784978de21ebf286925537598ef12258737f52dbcc39c345283fd288f14c6750d155f52a4b12b21188b03a6f8a84044e1986b3854409a11b1ddfa83c852b152dd2b441f3782748885285462815f002737547eddf6cb79c7ebf6d9b96dd7061c139505d2ec35fce0d85eeb5c7a0d8a9ba9e72a8991b94bd49ae613f43a44a6fa4880b4168028efbe7a6025b21cb8c63a9c70a2af9eec4216b929f405505e4a9941e91a70e699ec5fa77ca3c41ddc68cbe243994423df308497424576fcf49a9ebb29055836d7401b77911f44683601347c5dcbbefcd9e7867122d468f24e926fe929483248ac3cbab69b2f2a11bac9fecce6af6b5ef26ddaecf66f674945f8f2793c1edc42e57abdeedb6bf34e71d176624a0413c12f76ee1cfcc098e5d6f14649bf9fbcfb925e22fc6694704744f3e3f18c33befc1b878f84df61e8cfdcbdc2359684f14fe369a110b21af3d37dca1c239da654065857dfe520f324405c52848e1b8bf1b78fa9f7da784987008e5727e5d2963297371717e0e5b94e52954ba7319239a881d2bea08b9fd007a70daf52a8994b91b2649a486ac725d9993bca87dd023e21729d478a6010a13d1140578097cc9d363bdf24d29c816868cb50219aa5ad4ba16e3f50a3042becb256bdab2194cf5ce878f5f2fbe7a2dd4159e828c59b5509ff7072a0298d7d1e6017b530c8dfdaf15a883f787e9ca1825ea8fa0969b7f58b8cdb2edb64dbb59b631a97e1bd5726b92c1ab6e41a57aeaaa351af60a89f8b502b6122806fcf6fdfe6924289b7e7bdb83772c058e68bd435bed77fb9f000000ffff030034f07389ec060000,2018-10-01 12:31:12+00,,expired,3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd,f,
-VWB3riH9WuCv9NtSedaGE6,\x1f8b0800000000000003c455c1729b4810bde72b5c9cb3b21012029f222162c792bc9664a494631f0668c404984133032bc5a52fcb219f945fc83060457629deaabdec91f75e4fbfe9e96e7e7efff1f4eeec4cc3a17671a62d574383e12b7b5538a57d231610a24bd7d4de570a2e28834f4a66f0b5e738c21baecd8535b94e981f468395cfafa79be1eee3242a179baf97e6763c5cb9611d4c5908ac0e760a7952f67703d447e700e12d4d71b0938ab6c21812203f7aa6d569753aba615b9665b74dc56152521cc01dce2a89de332cc3eeebb6ae48d8e65806634a5ef056bbe143c829c76210860c3857d7e96fd6b6037d4f1457c10adb9fbd9bfb8531b059d17326cbcbd5106a9b39a36111884f24a22c5319647455bdca92806c043ca8ce9b222e80111ac2d942a00493b58a6f548ec4a58a1469daa079bce33840a944239472788699bca3f2afb75b56bfdfeee99d5ec30505634054b934d79b6b12dd2b8f7eb193753de5503137287b955cc16e8670955e4b11e31c93042cfbc3ba025b01cdb463a9430b22d8eec421f7383f81ca0a8853291d2c4e1dd23c4be7cf947e82ba8d29794e7228857ce61112e8482edf9ee152d56521aa065bab026ef3c23747037f1d47c5dc5999b30d33c6d162f41527ddc4f5703948a238b8bc9a264b17bafefda6672c67dffa76d2edba74d69b8ef2c9f5783cb81df7cae5d2bcddf63d7d6ed830c33ef1e3115fd9853bd3c7616c3b233f5bcffffa927778fca89d768441f5e4d38336bc731eb48b87ffc9de83b67f9e7b240ae589c03f5a336201e4b5e7863b543847bb0c88a8b02f8ff52043549010f9291cf777034fffb5efa430c40c02e1cd2795321622e717e7e7b045599e42a53b17312209dfd1a28e10db8fa006a75daf92489abba1024772c82ad79539c18ada073922de4821c733f55190f0a628c04a601e4b8ff5d23721205a2164b4e58b40d6a2d6b528ab578016b05d2e68d396cd60ca773e7cbcbdf8eab55057780a22a6d5427dda1fa808605e47eb07ec553114f69f56a00ade1fa62ba304cb3f825c6eee61e136cbb6dbd6cd66d9c6b8fa6d54cbad49062fba0595f2a9abd668d82bc4e3970ad80a202184afdfef772341d9f4dbeb1ebca3293044ea1dda6abfdbff020000ffff0300e1a26ae9ec060000,2018-10-01 12:33:11+00,,expired,3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd,f,
-At4CDM5vfewV2WDHEPKRbt,\x1f8b0800000000000003c4554d73a33810bdcfaf4871de758c0db6c9696d20c9c471c61fb15d35933908688c06908824183329ffb23dec4fdabfb092205e27e59daddacb1e79efb5faa9d5ddfcf9fb1f2f1f2e2e0c1c195717c65858ae37b3ab18be6f7a5befd69f4f9781307e510a2e28838f5ad6e7bbb5eb8af56437588deeef521644f1781bf0bbd9f3a4bebe8fabd5f3b79bc17e3ad9fa51134c5904ac09764b7952fea9059aa30b80684e331cd652d1d5184302e4873d18f53b3db33f1c398edd1d3a9ac3a4a23884479c2b8969f74756d71c0d4c4dc2bec0321853f286ef0d5b3e8282722cc651c480737d9db1fde361b901320bf8c4ab83bb38c2dc22d73dd7de06f5eac6228dcd82d1a80cc547125396eb0c325a554f5912907bc04375de0c71018cd0082e5602a598ec747cab72252e55a4ccb2162d929ae31065128d51c6e11566f28ecabf351a76468ee90c7bc3960a4bc680e86a19fe7a6948f4a02d06652dcb7acea0661e50fe2eb786fd1c6195ddc810e31c931446ce6f3b0576429a1ba752979644b0facc219f717106950510e752ba589c3ba47d95de3f53e6196a9e50f29ae4580af9ca1e12e8442e9f9ee14ad76525547fed7401f745190cbc71b04be272e96e078b67d69fc62bef1b4eadd45fe36a9cc64978733b4b373e58c1e767bbbf59fc183aa965f97461cfbce2fe6e3a1dcfa776b5d90ce6fbe1da5cf61d58e0800489c7b74ee92fcc699438ae17e4bbe5af5f8a1e4fbe1ae71d61d02df9f2644c1edd27e3eae97fb2f7641c5ec71e89527b22f0dd68272c84a2f1dc72c70a17a8ce8108857df9dacc31c425895090c1697bb7f0ec5ffb4e0a23cc2014ebe5bd52264214fceaf212f6282f3250ba4b912092f29a964d84d85f839e9b6eb3496269ee810a1ccb1953ae9539c1cac60739217e92424e6716a030e56d518055c0d62c3bd54bdf8480e84490d34e2042598b46d7a1acd90046c8ea42d0b62ddbc194ef7cfcf8f9de6bb64253e1198884aa7dfa72385231c0b289368fd8bb6268ec3f6d401d7c384e574e09963f04b9dbfce3be3deeda41bfddb509567f0db5dbda64f0a65b50259f5ab546cbde229ebc55c05e0089207aff7e7f3712546dbfbdefc1479a0143a459a19dee87c35f000000ffff0300011a2ad8eb060000,2018-10-01 13:51:01+00,,expired,3sgUCCtUBg6S8LJkrbdfAWbsJMqByFLfvSqjG6xKBWEd,f,
### BTCPayServer.Tests/TestData/OldPayments.csv
@@ -1,12 +0,0 @@
-Id,Blob,InvoiceDataId,Accounted,Blob2,Type
-a8be47ca93a1583f60b25fb1279b6c162af731024d169f8d1cd0d29d1d391132-0,\x1f8b0800000000000003748f396ec33010457b9f4260ed82c39d2ead20958b2050a966c425201289824205100c9f2c458e942b447216b8c9af66fe03de603edf3fcebbaa22537021bd05dfa43e904305921b4139a36cbfd13c9731a7a1ac847006c02d78eb3df3149cf13682129e320e513304a59ced98ee40c68e29caa33408963b14ba0b68e84fc89f79be7a9d1692de04345a10d26b0116c0482339a008144da7509a2e4aca95d7511923b534fadb87cee57928c1afca32cde15aba69194baeb3df5e23c7a62637f5032e7d18ca1d16dce8b925751e629a7a2c290ff5666bc901ecbe258fc7fb75bc6a5b720a4fe896758ff8f21a2eff289b65fc3d7a4acf81ec2e5f000000ffff03002eb110c572010000,Q7RqoHLngK9svM4MgRyi9y,t,,
-c703dd8ae34622dfb96d677260631c39af483918d9e63676839be0db1b8a9268-1,\x1f8b0800000000000003748f3d6ec3300c85f79cc2d09c413fb644658c8b4e198ac2a3175aa20ba1b565b8720123c8c93af448bd42e5040dbaf44de47bc0f7c8efcfaff3ae28d84c8ec207f9260cc40e85a84a59951c14df6f695cd214c39872c2345809283adf11b71d28a39526edad00654bc05e59e1b2c58dd446fbcefa5eca529302f49e2b67b8e057b13b79b971bdecace37709835694d0a1e08012786572a3b2d944aba4ef2de81e205f50213907e6c643e7e23226f21999e685aea69bd729c53afaed35766c6af6c77ec275a0313d60c22d3db7ac8e631fe601538863bdd15a76a8a4d8b7ecf9f898e72bb765277a41b7e6bdc7b777bafcc36cd6e9b7f5145e89ed2e3f000000ffff03000f0bf2f373010000,Q7RqoHLngK9svM4MgRyi9y,t,,
-f237a3d75018f4435927f5b1be1a8902045d88ddda39c25254214c3e484bd383-1,\x1f8b080000000000000374904d6ac3301046f73945d03a14fdc6a32ce3925528a564e9cd581a1593da0a8e9c62424ed6458fd42b547669e8a6b39bf7c193e6fbfaf8bc2e964b76a1fedcc48e6d967c35ed3d396a2ee40f4d4b190aa3a5e5609599d38ed27bec8f3b9a32fec0a791731287748a4d973267a0bcd2b50645dac96c30d249653d7a0f603cd75c821558532d829185b15a052dc0705fa05245905ccc62ceeee661f66ac36bedf97d44815668a851704009dc14be26653344aba40f16d601c0d660909c83e2c787cec5a14be4b332f503cdd0f5e329c532fae930b63d94ec0f7ec6b1a52e3d62c229bd56ac8c5d68fa1653aeae9c6c15db88756e6a55b197ed2e6fb3b9624ff7c232cb8565b4a75774635e03be9de9f6cf4387f1f4fb957d7324b6b87d030000ffff0300eef4b353b2010000,Q7RqoHLngK9svM4MgRyi9y,t,,
-aedd36b5c976e56543cd7a5e207ea13dc801764cb3682474ab75a54399f20c27-9,\x1f8b08000000000000037490bf6ec2301087779e02794695ff3b66241513aaaa8a91e5629fab8812a3e050458827ebd047ea2bd44e0bead29b7cdfcffacebeaf8fcfcb6c3e2767ec4f6decc872ce16a5efd1617b46bf6d0f58a052dc68658d9cd20ed37becf76b2c197da0a5f894c4211d63dba5cc0937d4056ead14a08c82c6482e75d508e98ca6cc55c20333c8a94203ce4ba1152aa39d6d94d0de03523b8929b99b87c99b6779c128a3bfc50c582621d0c02b69a571ba623a7068b4e516adb0547b45196f022aea2bf3e303e7e2d025f45999fa0127e8faf198621d7df918596d6bf2073fc378c02e3d4282925e76a48e5d68fb03a4bcbabad87664c9163bf2b25ae75380b713e6eee9bead0cf3b632dae02bb8f176e7facf94ed78bcbd63d3ee91ccaedf000000ffff030012c428b2af010000,Q7RqoHLngK9svM4MgRyi9y,t,,
-3358197dcb30420d3487516e8ec9dcc0f6d03f16b4f41b77cd3ad429b1e529ee-0,\x1f8b0800000000000003748fb14ec3301086f73e45e4b9839db3e3b86383983a209431cbe57c4116248e828314557d32061e8957202914b170d3ddff49dfe9ff7cff38efb24c4c4c1cded8d7a16771c894d18536e024ec371ae734c630a49508e6dcb16955eebc06246fad6a3bdd6a5540e7655790f444aee4828d2a2d68e9750e925aeb95332580fc19f16b9eaf5e50680dc8fcc69545a774993b7285c1429adc90266d491a8980502290b2d2b80ebd85d27efb9028ce4362bf2ad334f335a4691953aca2dfaa89635d893ff1032e3d0fe90e136ef4dc882a0e5d987a4c210ed5666bc441ed1bf178bc5fb70e5f5e79bd4efc84b4dc82cb3fca7a196f4f4fe199c5eef2050000ffff0300b173d7d272010000,Q7RqoHLngK9svM4MgRyi9y,t,,
-03d66d2d633dac96cc45546a0555cb917f5d2f0d37dddfdf67e48f88ae728aa1-5,\x1f8b08000000000000037490bd6ec2301446779e027946951dff33928a095555c598e5625fa38812a3e050458827ebd047ea2bd40e2aead2ebe99e4f3ab6bfefcfafeb6c3e2717eccf6decc872ce1665efd1617b41bf6d8f58a0144652a3f93ded307dc4feb0c692d1275aa69a9238a4536cbb94390166405780c6988042691ff2f15c535f05e975b0cceda4a4528114423a671538ee15afbcf25e514ee524a6e4611e26af50a085a68f611a2c1312ad1396a3715c280f2cd8c0b50dc2535571b6432a0ce74aed8cbefbc0b93874097d56a67ec009ba7e3ca558475f3e4656db9afcc1af301eb14bcf90a0a4d786d4b10b6d7f8494abab8bad214bc9b45a34e46db5cecb246ec8cba3afcc725f196d700f6ecc6b80f733defeb9673b9e7e5fb2690f4866b71f000000ffff03007bb33a2fb1010000,Q7RqoHLngK9svM4MgRyi9y,t,,
-dc130d025a4bd2e7ee83b7707d850e7c1a52872c222a5bc2e05d3357e79aa762-1,\x1f8b08000000000000037490bf6ec2301087779e027946e8fc2f761849c584aaaa6264b9d817145162141caa08f1641dfa487d85daa98abaf426dfefb3beb3efebe3f3369bcfd995fa4b1b3ab69af345ee7b72d45ec9efda13e5506bae1557d64eb4a3f81efae386328325e4121309433c87b68b296785405322196da4d49ec0095d0b1442386bb4e0681c90d5c61ba88d954464bc50b54610e0b9f40ef82406f6300f9317ea74c5c1a3b8c1922b4da553a524eba42a3cf2a66ca4291be5a11092d704ca4a5914b5353f3e742e0c5d249f940dbe5d684a5d3f9e63a882cf3f63eb5dc5fec42f389ea88b4f1831d3db9e55a16bdafe8431edaecaba3d5bc162cf5ed79b748afd40a9797e6c2bd365e65b3aa01b533b4dbeff3364379e7f9fb16d8fc466f76f000000ffff0300f93b039faf010000,Q7RqoHLngK9svM4MgRyi9y,f,,
-afc39884e024cbb3a48ca997b7e878b199d85fe97f90f94471364cc866ba83ad-1,\x1f8b080000000000000374904d6ac3301085f73945d03a14c992f593655cb20aa5942cbd1949a362d258c191534cc8c9bae8917a854a2e0ddd7476ef3de6d3e87d7d7c5e17cb25b9e070ee624fd64bb62a7a4087dd05fdbe3b6231eb9ad5a21246ce698fe93d0e872d968c3ed032d59cc4319d62d7a7ec13f09a5b90d269e1b8544c88600c55014d1dbc36c632a5515b651418ed4058ee6c25906a91258740d90ca6e44e1e672eb5402b47efc3f23e13351a270cc7bc2aa407164ce0ca04e1a9ac38b34885e65c4aabd50f0f9c8b639fd067641a469c4d374ca7149be8cbc7c866df903ff6334c47ecd3232428e9b5254dec43371c21e5ea9a426bc95ae59e562d79d96cb398c12d79baf795bddc57b676f80a6eca32c0db196fffbcb39f4ebf97ecba0392c5ed1b0000ffff030018cc54a1b1010000,Q7RqoHLngK9svM4MgRyi9y,t,,
-6f2b8513ebfdb14b41d4de235f050cd028400cb01fde700d72c6bedc2ad8af1e-5,\x1f8b08000000000000037490bf6ac3301087f73c45d01cc249966425635c3285528a472ffa732a26b5151c39c5843c59873e525fa192434397de22ddef83efa4fbfefcba2e964b72c1e1dc869e6c977495fb012db6177475db610e85908a6d24c04c7b8c1f6138ee313358432e369330c65368fb987242517ba79876d6a0952503578243ea0d80e5c0944b2708e159e1d0714eb931d43b34b4508219e941cc62200ff378f752c719c2a368a937942b445158855e6967b8b05c0a2e9934c0b59585960c0b55d272a3cabb4f5b1bc63ea24b4aafdfcf38a776984e3154c1e59f915d5d913ff18b9e3aece3938e3ad36b43aad0fb76e8744cbbabb2ae215b5835e475b74fb7388c989ae7c7b6325d677ec0376da7d4ce936fff0ca9a7d3ef330eed11c9e2f6030000ffff0300b09cf40daf010000,Q7RqoHLngK9svM4MgRyi9y,f,,
-3a6659e189f83f649c0010305def1b8fb78efdbe8c0ce44d56c8c22fff742b55-61,\x1f8b08000000000000037490bd6ec3201485f73c45c41c5580f973c6b8ca14555595d10be65e222b8d891c9cca8af2641dfa487d8582ab585d7a27ce39f001e7fbf3ebb6582ec915fb4b1b3ab25eb255d63d3a6caf08fbf684d994525121a85653da61fc08fd718b39a34f340f9f9230c47368bb987c22256fb4f09e7bc79d914a000aea8c6bd083c1461bcfd2524241593a5f3a250aef8d2991c952a9c21630812999c9c3c4d55615cad37998b625131eb8e5c080496c941525958c97b2708c838286022ac5b56060f42fcf3a17862e222464ec079c4cd78fe718aa00f96364b3afc81ffbd58e27ece2b38d36a7b79a54a1f36d7fb2315557655a4dd64c30b1aac9db669b84b7ef174cea652e2c99a9b064edf060ddf8d873ffe7a2fd787e3c65d71e912cee3f000000ffff0300a991d8c4b2010000,Q7RqoHLngK9svM4MgRyi9y,t,,
-26c879f3d27a894a62f8730c84205ac9dec38b7bbc0a11ccc0c196d1259b25aa-1,\x1f8b08000000000000036c90cf6ed4301087dfc5e7086c27f19fdccaa2b0b4dbaa452b964ab94cec314d378943e204d26a9f8c038fc42be02eea01099f3c9faddfcc7cbf7ffe7a260b8e53e37b52b0848c68b059d0ee9b0eafa78804cfa9d69aa954c884f418befbf158229282bea109f173187cd3075210009eeb9ae796696198a1c63046a136b256b5492d1a9d03a72aa346a64e099e81d2122c77a9d4467141193d1ff237758e99fddcb6090163fcdc07b4a408e38c0931e33a04bff1364e4176eff61bf2ca6e61edb00fef21407c7aae88f1bd6bc60e425c70f3925291422415196b176f0eda096305d68e384d9154e4f3e5ae94878b61f1eeca680fdf862ffb3be5ecc5aacb9b0f87fce89e9aedfd63d64cf869fbb46c1fe67ab854dd74d5fd58efef4ad61c9c6bacce1eafa1bbc1beac486c70c4f516c2c3b9017d1b3da567bc403b6384715098260c1fedf98770944b8d1a2dcd585427a347ed7269a9a15c73953191096ab25a720e9866b904c6104daa98c9b9b0ff647325b253ac5bfc0a667d5dfaf43f65fb7578311a85ee9a2392d31f000000ffff03004a65a9b61e020000,Q7RqoHLngK9svM4MgRyi9y,t,,
### BTCPayServer.Tests/TestData/Upload.csv
@@ -0,0 +1,2 @@
+id,name
+1,Test upload
### BTCPayServer.Tests/UnitTest1.cs
@@ -2193,171 +2193,6 @@ public async Task CanCheckForNewVersion()
Assert.False(fn.Seen);
}
- [Fact(Timeout = LongRunningTestTimeout)]
- [Trait("Integration", "Integration")]
- public async Task CanMigrateFileIds()
- {
- using var tester = CreateServerTester(newDb: true);
- tester.DeleteStore = false;
- await tester.StartAsync();
-
- var user = tester.NewAccount();
- await user.GrantAccessAsync();
-
- using (var ctx = tester.PayTester.GetService<ApplicationDbContextFactory>().CreateContext())
- {
- var storeConfig = """
- {
- "spread": 0.0,
- "cssFileId": "2a51c49a-9d54-4013-80a2-3f6e69d08523",
- "logoFileId": "8f890691-87f9-4c65-80e5-3b7ffaa3551f",
- "soundFileId": "62bc4757-b92b-4a3b-a8ab-0e9b693d6a29",
- "networkFeeMode": "MultiplePaymentsOnly",
- "defaultCurrency": "USD",
- "showStoreHeader": true,
- "celebratePayment": true,
- "paymentTolerance": 0.0,
- "invoiceExpiration": 15,
- "preferredExchange": "kraken",
- "showRecommendedFee": true,
- "monitoringExpiration": 1440,
- "showPayInWalletButton": true,
- "displayExpirationTimer": 5,
- "excludedPaymentMethods": null,
- "recommendedFeeBlockTarget": 1
- }
- """;
- var serverConfig = """
- {
- "CssUri": null,
- "FirstRun": false,
- "LogoFileId": "ce71d90a-dd90-40a3-b1f0-96d00c9abb52",
- "CustomTheme": true,
- "CustomThemeCssUri": null,
- "CustomThemeFileId": "9b00f4ed-914b-437b-abd2-9a90c1b22c34",
- "CustomThemeExtension": 0
- }
- """;
- await ctx.Database.GetDbConnection().ExecuteAsync("""
- UPDATE "Stores" SET "StoreBlob"=@storeConfig::JSONB WHERE "Id"=@storeId;
- """, new { storeId = user.StoreId, storeConfig });
- await ctx.Database.GetDbConnection().ExecuteAsync("""
- UPDATE "Settings" SET "Value"=@serverConfig::JSONB WHERE "Id"='BTCPayServer.Services.ThemeSettings';
- """, new { serverConfig });
- await ctx.Database.GetDbConnection().ExecuteAsync("""
- INSERT INTO "Files" VALUES (@id, @fileName, @id || '-' || @fileName, NOW(), @userId);
- """,
- new[]
- {
- new { id = "2a51c49a-9d54-4013-80a2-3f6e69d08523", fileName = "store.css", userId = user.UserId },
- new { id = "8f890691-87f9-4c65-80e5-3b7ffaa3551f", fileName = "store.png", userId = user.UserId },
- new { id = "ce71d90a-dd90-40a3-b1f0-96d00c9abb52", fileName = "admin.png", userId = user.UserId },
- new { id = "9b00f4ed-914b-437b-abd2-9a90c1b22c34", fileName = "admin.css", userId = user.UserId },
- new { id = "62bc4757-b92b-4a3b-a8ab-0e9b693d6a29", fileName = "store.mp3", userId = user.UserId },
- });
- await ctx.Database.GetDbConnection().ExecuteAsync("""
- DELETE FROM "__EFMigrationsHistory" WHERE "MigrationId"='20240508015052_fileid'
- """);
- await ctx.Database.MigrateAsync();
- ((MemoryCache)tester.PayTester.GetService<IMemoryCache>()).Clear();
- }
-
- var controller = tester.PayTester.GetController<UIStoresController>(user.UserId, user.StoreId);
- var vm = await controller.GeneralSettings(user.StoreId).AssertViewModelAsync<GeneralSettingsViewModel>();
- Assert.Equal(tester.PayTester.ServerUriWithIP + "LocalStorage/8f890691-87f9-4c65-80e5-3b7ffaa3551f-store.png", vm.LogoUrl);
- Assert.Equal(tester.PayTester.ServerUriWithIP + "LocalStorage/2a51c49a-9d54-4013-80a2-3f6e69d08523-store.css", vm.CssUrl);
-
- var vm2 = await controller.CheckoutAppearance().AssertViewModelAsync<CheckoutAppearanceViewModel>();
- Assert.Equal(tester.PayTester.ServerUriWithIP + "LocalStorage/62bc4757-b92b-4a3b-a8ab-0e9b693d6a29-store.mp3", vm2.PaymentSoundUrl);
-
- var serverController = tester.PayTester.GetController<UIServerController>();
- var branding = await serverController.Branding().AssertViewModelAsync<BrandingViewModel>();
-
- Assert.Equal(tester.PayTester.ServerUriWithIP + "LocalStorage/ce71d90a-dd90-40a3-b1f0-96d00c9abb52-admin.png", branding.LogoUrl);
- Assert.Equal(tester.PayTester.ServerUriWithIP + "LocalStorage/9b00f4ed-914b-437b-abd2-9a90c1b22c34-admin.css", branding.CustomThemeCssUrl);
- }
-
- [Fact(Timeout = LongRunningTestTimeout)]
- [Trait("Integration", "Integration")]
- [Obsolete]
- public async Task CanDoLabelMigrations()
- {
- using var tester = CreateServerTester(newDb: true);
- await tester.StartAsync();
- var dbf = tester.PayTester.GetService<ApplicationDbContextFactory>();
- int walletCount = 1000;
- var wallet = "walletttttttttttttttttttttttttttt";
- using (var db = dbf.CreateContext())
- {
- for (int i = 0; i < walletCount; i++)
- {
- 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();
- }
- uint256 firstTxId = null;
- using (var db = dbf.CreateContext())
- {
- int transactionCount = 10_000;
- for (int i = 0; i < transactionCount; i++)
- {
- var txId = RandomUtils.GetUInt256();
- var wt = new WalletTransactionData()
- {
- WalletDataId = $"S-{wallet}{i % walletCount}-BTC",
- TransactionId = txId.ToString(),
- };
- firstTxId ??= txId;
- if (i != 10)
- wt.Blob = ZipUtils.Zip("{\"Comment\":\"test\"}");
- if (i % 1240 != 0)
- {
- wt.Labels = "[{\"type\":\"raw\", \"text\":\"label1\"}]";
- }
- else if (i == 0)
- {
- wt.Labels = "[{\"type\":\"raw\", \"text\":\"label1\"},{\"type\":\"raw\", \"text\":\"labelo" + i + "\"}, " +
- "{\"type\":\"payout\", \"text\":\"payout\", \"pullPaymentPayouts\":{\"pp1\":[\"p1\",\"p2\"],\"pp2\":[\"p3\"]}}]";
- }
- else
- {
- wt.Labels = "[{\"type\":\"raw\", \"text\":\"label1\"},{\"type\":\"raw\", \"text\":\"labelo" + i + "\"}]";
- }
- db.WalletTransactions.Add(wt);
- }
- await db.SaveChangesAsync();
- }
- await tester.RestartMigration();
- var migrator = tester.PayTester.GetService<IEnumerable<IHostedService>>().OfType<DbMigrationsHostedService>().First();
- await migrator.MigratedTransactionLabels(0);
-
- var walletRepo = tester.PayTester.GetService<WalletRepository>();
- var wi1 = await walletRepo.GetWalletLabels(new WalletId($"{wallet}0", "BTC"));
- Assert.Equal(3, wi1.Length);
- Assert.Contains(wi1, o => o.Label == "label1" && o.Color == "black");
- Assert.Contains(wi1, o => o.Label == "labelo0" && o.Color == "#000");
- Assert.Contains(wi1, o => o.Label == "payout" && o.Color == "green");
-
- var txInfo = await walletRepo.GetWalletTransactionsInfo(new WalletId($"{wallet}0", "BTC"), new[] { firstTxId.ToString() });
- Assert.Equal("test", txInfo.Values.First().Comment);
- // Should have the 2 raw labels, and one legacy label for payouts
- Assert.Equal(3, txInfo.Values.First().LegacyLabels.Count);
- var payoutLabel = txInfo.Values.First().LegacyLabels.Select(l => l.Value).OfType<PayoutLabel>().First();
- Assert.Equal(2, payoutLabel.PullPaymentPayouts.Count);
- Assert.Equal(2, payoutLabel.PullPaymentPayouts["pp1"].Count);
- Assert.Single(payoutLabel.PullPaymentPayouts["pp2"]);
- }
-
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CreateStoreDoesNotTrustCanEditPreferredExchange()
@@ -2713,47 +2548,6 @@ await TestUtils.EventuallyAsync(async () =>
- [Fact(Timeout = LongRunningTestTimeout)]
- [Trait("Integration", "Integration")]
- public async Task CanDoInvoiceMigrations()
- {
- using var tester = CreateServerTester(newDb: true);
- await tester.StartAsync();
-
- var acc = tester.NewAccount();
- await acc.GrantAccessAsync(true);
- await acc.CreateStoreAsync();
- await acc.RegisterDerivationSchemeAsync("BTC");
- var handlers = tester.PayTester.GetService<PaymentMethodHandlerDictionary>();
-
- await acc.ImportOldInvoices();
-
- var dbContext = tester.PayTester.GetService<ApplicationDbContextFactory>().CreateContext();
- var invoiceMigrator = tester.PayTester.GetService<InvoiceBlobMigratorHostedService>();
- invoiceMigrator.BatchSize = 2;
- await invoiceMigrator.ResetMigration();
- await invoiceMigrator.StartAsync(default);
- tester.DeleteStore = false;
- await TestUtils.EventuallyAsync(async () =>
- {
- var invoices = await dbContext.Invoices.AsNoTracking().ToListAsync();
- foreach (var invoice in invoices)
- {
- Assert.NotNull(invoice.Currency);
- Assert.NotNull(invoice.Amount);
- Assert.NotNull(invoice.Blob2);
- }
- Assert.True(await invoiceMigrator.IsComplete());
- });
- var invoiceRepo = tester.PayTester.GetService<InvoiceRepository>();
- var invoice = await invoiceRepo.GetInvoice("Q7RqoHLngK9svM4MgRyi9y");
-#pragma warning disable CS0618 // Type or member is obsolete
- var p = invoice.Payments.First(p => p.Id == "26c879f3d27a894a62f8730c84205ac9dec38b7bbc0a11ccc0c196d1259b25aa-1");
-#pragma warning restore CS0618 // Type or member is obsolete
- var details = p.GetDetails<BitcoinLikePaymentData>(handlers.GetBitcoinHandler("BTC"));
- Assert.Equal("6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d", details.AssetId.ToString());
- }
-
[Fact(Timeout = TestUtils.TestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanViewFiles()
@@ -3022,19 +2816,6 @@ public async Task CanCreateReports()
Assert.Equal(8, itemsCount["green-tea"]);
Assert.Equal(1, itemsCount["black-tea"]);
- await acc.ImportOldInvoices();
- var date2018 = new DateTimeOffset(2018, 1, 1, 0, 0, 0, TimeSpan.Zero);
- report = await GetReport(acc, "Payments", date2018, date2018 + TimeSpan.FromDays(365));
- var invoiceIdIndex = report.GetIndex("InvoiceId");
- var invoiceCurrencyAmountIndex = report.GetIndex("InvoiceCurrencyAmount");
- var rateIndex = report.GetIndex("Rate");
- var oldPaymentsCount = report.Data.Count(d => d[invoiceIdIndex].Value<string>() == "Q7RqoHLngK9svM4MgRyi9y");
- Assert.Equal(9, oldPaymentsCount); // 11 payments, but 2 unaccounted
- Assert.Single(report.Data, d =>
- d[invoiceIdIndex].Value<string>() == "Q7RqoHLngK9svM4MgRyi9y" &&
- GetAmount(rateIndex, d) == 6596.35m &&
- GetAmount(invoiceCurrencyAmountIndex, d) == 1.18m);
-
var addr = await tester.ExplorerNode.GetNewAddressAsync();
// Two invoices get refunded
for (int i = 0; i < 2; i++)
### BTCPayServer/HostedServices/DbMigrationsHostedService.cs
@@ -1,354 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using BTCPayServer.Client.Models;
-using BTCPayServer.Configuration;
-using BTCPayServer.Data;
-using BTCPayServer.Logging;
-using BTCPayServer.Services;
-using BTCPayServer.Services.Invoices;
-using BTCPayServer.Services.Labels;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.Logging;
-using Microsoft.Extensions.Options;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-
-namespace BTCPayServer.HostedServices
-{
- /// <summary>
- /// In charge of all long running db migrations that we can't execute on startup in MigrationStartupTask
- /// </summary>
- public class DbMigrationsHostedService : BaseAsyncService
- {
- private readonly InvoiceRepository _invoiceRepository;
- private readonly SettingsRepository _settingsRepository;
- private readonly ApplicationDbContextFactory _dbContextFactory;
- private readonly IOptions<DataDirectories> _datadirs;
-
- public DbMigrationsHostedService(InvoiceRepository invoiceRepository, SettingsRepository settingsRepository, ApplicationDbContextFactory dbContextFactory, IOptions<DataDirectories> datadirs, Logs logs) : base(logs)
- {
- _invoiceRepository = invoiceRepository;
- _settingsRepository = settingsRepository;
- _dbContextFactory = dbContextFactory;
- _datadirs = datadirs;
- }
-
-
- internal override Task[] InitializeTasks()
- {
- return new Task[] { ProcessMigration() };
- }
-
- protected async Task ProcessMigration()
- {
- var settings = await _settingsRepository.GetSettingAsync<MigrationSettings>();
- if (settings.MigratedInvoiceTextSearchPages != int.MaxValue)
- {
- await MigratedInvoiceTextSearchToDb(settings.MigratedInvoiceTextSearchPages ?? 0);
- }
- if (settings.MigratedTransactionLabels != int.MaxValue)
- {
- await MigratedTransactionLabels(settings.MigratedTransactionLabels ?? 0);
- }
- }
-
-
-#pragma warning disable CS0612 // Type or member is obsolete
- class LegacyWalletTransactionInfo
- {
- public string Comment { get; set; } = string.Empty;
- [JsonIgnore]
- public Dictionary<string, LabelData> Labels { get; set; } = new Dictionary<string, LabelData>();
- }
-
- static LegacyWalletTransactionInfo GetBlobInfo(WalletTransactionData walletTransactionData)
- {
- LegacyWalletTransactionInfo blobInfo;
- if (walletTransactionData.Blob == null || walletTransactionData.Blob.Length == 0)
- blobInfo = new LegacyWalletTransactionInfo();
- else
- blobInfo = JsonConvert.DeserializeObject<LegacyWalletTransactionInfo>(ZipUtils.Unzip(walletTransactionData.Blob));
- if (!string.IsNullOrEmpty(walletTransactionData.Labels))
- {
- if (walletTransactionData.Labels.StartsWith('['))
- {
- foreach (var jtoken in JsonParser.ParseArray(walletTransactionData.Labels))
- {
- var l = jtoken.Type == JTokenType.String ? Label.Parse(jtoken.Value<string>())
- : Label.Parse(jtoken.ToString());
- blobInfo.Labels.TryAdd(l.Text, l);
- }
- }
- else
- {
- // Legacy path
- foreach (var token in walletTransactionData.Labels.Split(',',
- StringSplitOptions.RemoveEmptyEntries))
- {
- var l = Label.Parse(token);
- blobInfo.Labels.TryAdd(l.Text, l);
- }
- }
- }
- return blobInfo;
- }
-
- internal async Task MigratedTransactionLabels(int startFromOffset)
- {
- // Only of 1000, that's what EF does anyway under the hood by default
- int batchCount = 1000;
- int total = 0;
- HashSet<(string WalletId, string LabelId)> existingLabels;
- using (var db = _dbContextFactory.CreateContext())
- {
- total = await db.WalletTransactions.CountAsync();
- existingLabels = (await (
- db.WalletObjects.AsNoTracking()
- .Where(wo => wo.Type == WalletObjectData.Types.Label)
- .Select(wl => new { wl.WalletId, wl.Id })
- .ToListAsync()))
- .Select(o => (o.WalletId, o.Id)).ToHashSet();
- }
-
-
-
-next:
-// var insertedObjectInDBContext
-// Need to keep track of this hack, or then EF has a bug where he crash on the .Add and get internally
-// corrupted.
- var ifuckinghateentityframework = new HashSet<(string WalletId, string Type, string Id)>();
- using (var db = _dbContextFactory.CreateContext())
- {
- Logs.PayServer.LogInformation($"Wallet transaction label importing transactions {startFromOffset}/{total}");
- var txs = await db.WalletTransactions
- .OrderByDescending(wt => wt.WalletDataId).ThenBy(wt => wt.TransactionId)
- .Skip(startFromOffset)
- .Take(batchCount)
- .ToArrayAsync();
-
- foreach (var tx in txs)
- {
- // Same as above
- var ifuckinghateentityframework2 = new HashSet<(string Type, string Id)>();
- var blob = GetBlobInfo(tx);
- db.WalletObjects.Add(new Data.WalletObjectData()
- {
- WalletId = tx.WalletDataId,
- Type = Data.WalletObjectData.Types.Tx,
- Id = tx.TransactionId,
- Data = string.IsNullOrEmpty(blob.Comment) ? null : new JObject() { ["comment"] = blob.Comment }.ToString()
- });
-
- foreach (var label in blob.Labels)
- {
- var labelId = label.Key;
- if (labelId.StartsWith("{", StringComparison.OrdinalIgnoreCase))
- {
- try
- {
- labelId = JsonParser.ParseObject(label.Key)["value"].Value<string>();
- }
- catch
- {
- }
- }
- if (!existingLabels.Contains((tx.WalletDataId, labelId)))
- {
- JObject labelData = new JObject();
- labelData.Add("color", "#000");
- db.WalletObjects.Add(new WalletObjectData()
- {
- WalletId = tx.WalletDataId,
- Type = WalletObjectData.Types.Label,
- Id = labelId,
- Data = labelData.ToString()
- });
- existingLabels.Add((tx.WalletDataId, labelId));
- }
- if (ifuckinghateentityframework2.Add((Data.WalletObjectData.Types.Label, labelId)))
- db.WalletObjectLinks.Add(new WalletObjectLinkData()
- {
- WalletId = tx.WalletDataId,
- BType = Data.WalletObjectData.Types.Tx,
- BId = tx.TransactionId,
- AType = Data.WalletObjectData.Types.Label,
- AId = labelId
- });
-
- if (label.Value is ReferenceLabel reflabel)
- {
- if (IsReferenceLabel(reflabel.Type))
- {
- if (ifuckinghateentityframework.Add((tx.WalletDataId, reflabel.Type, reflabel.Reference ?? String.Empty)))
- db.WalletObjects.Add(new WalletObjectData()
- {
- WalletId = tx.WalletDataId,
- Type = reflabel.Type,
- Id = reflabel.Reference ?? String.Empty
- });
-
- if (ifuckinghateentityframework2.Add((reflabel.Type, reflabel.Reference ?? String.Empty)))
- db.WalletObjectLinks.Add(new WalletObjectLinkData()
- {
- WalletId = tx.WalletDataId,
- BType = Data.WalletObjectData.Types.Tx,
- BId = tx.TransactionId,
- AType = reflabel.Type,
- AId = reflabel.Reference ?? String.Empty
- });
- }
- }
- else if (label.Value is PayoutLabel payoutLabel)
- {
- foreach (var pp in payoutLabel.PullPaymentPayouts)
- {
- foreach (var payout in pp.Value)
- {
- var payoutData = string.IsNullOrEmpty(pp.Key) ? null : new JObject()
- {
- ["pullPaymentId"] = pp.Key
- };
- if (ifuckinghateentityframework.Add((tx.WalletDataId, "payout", payout)))
- db.WalletObjects.Add(new WalletObjectData()
- {
- WalletId = tx.WalletDataId,
- Type = "payout",
- Id = payout,
- Data = payoutData?.ToString()
- });
- if (ifuckinghateentityframework2.Add(("payout", payout)))
- db.WalletObjectLinks.Add(new WalletObjectLinkData()
- {
- WalletId = tx.WalletDataId,
- BType = Data.WalletObjectData.Types.Tx,
- BId = tx.TransactionId,
- AType = "payout",
- AId = payout
- });
- }
- }
- }
- }
- }
- int retry = 0;
-retrySave:
- try
- {
- await db.SaveChangesAsync();
- }
- catch (DbUpdateException ex) when (retry < 10)
- {
- foreach (var entry in ex.Entries)
- {
- if (entry.Entity is WalletObjectData wo && (IsReferenceLabel(wo.Type) || wo.Type == "payout"))
- {
- await entry.ReloadAsync();
- }
- }
- retry++;
- goto retrySave;
- }
- if (txs.Length < batchCount)
- {
- var settings = await _settingsRepository.GetSettingAsync<MigrationSettings>();
- settings.MigratedTransactionLabels = int.MaxValue;
- await _settingsRepository.UpdateSetting(settings);
- Logs.PayServer.LogInformation($"Wallet transaction label successfully migrated");
- return;
- }
- else
- {
- startFromOffset += batchCount;
- var settings = await _settingsRepository.GetSettingAsync<MigrationSettings>();
- settings.MigratedTransactionLabels = startFromOffset;
- await _settingsRepository.UpdateSetting(settings);
- goto next;
- }
- }
- }
-
- private static bool IsReferenceLabel(string type)
- {
- return type == "invoice" ||
- type == "payment-request" ||
- type == "app" ||
- type == "pj-exposed";
- }
-#pragma warning restore CS0612 // Type or member is obsolete
- private async Task MigratedInvoiceTextSearchToDb(int startFromPage)
- {
- // deleting legacy DBriize database if present
- var dbpath = Path.Combine(_datadirs.Value.DataDir, "InvoiceDB");
- if (Directory.Exists(dbpath))
- {
- Directory.Delete(dbpath, true);
- }
-
- var invoiceQuery = new InvoiceQuery { IncludeArchived = true };
- var totalCount = await CountInvoices();
- const int PAGE_SIZE = 1000;
- var totalPages = Math.Ceiling(totalCount * 1.0m / PAGE_SIZE);
- Logs.PayServer.LogInformation($"Importing {totalCount} invoices into the search table in {totalPages - startFromPage} pages");
- for (int i = startFromPage; i < totalPages && !CancellationToken.IsCancellationRequested; i++)
- {
- Logs.PayServer.LogInformation($"Import to search table progress: {i + 1}/{totalPages} pages");
- // migrate data to new table using invoices from database
- using var ctx = _dbContextFactory.CreateContext();
- invoiceQuery.Skip = i * PAGE_SIZE;
- invoiceQuery.Take = PAGE_SIZE;
- var invoices = await _invoiceRepository.GetInvoices(invoiceQuery);
-
- foreach (var invoice in invoices)
- {
- var textSearch = new List<string>();
-
- // recreating different textSearch.Adds that were previously in DBriize
- foreach (var paymentMethod in invoice.GetPaymentPrompts())
- {
- var paymentDestination = paymentMethod.Destination;
- textSearch.Add(paymentDestination);
- textSearch.Add(paymentMethod.Calculate().TotalDue.ToString());
- }
- //
- textSearch.Add(invoice.Id);
- textSearch.Add(invoice.InvoiceTime.ToString(CultureInfo.InvariantCulture));
- textSearch.Add(invoice.Price.ToString(CultureInfo.InvariantCulture));
- textSearch.Add(invoice.Metadata.OrderId);
- textSearch.Add(invoice.StoreId);
- textSearch.Add(invoice.Metadata.BuyerEmail);
- // TODO: Are there more things to cache? PaymentData?
- InvoiceRepository.AddToTextSearch(ctx,
- new Data.InvoiceData { Id = invoice.Id, InvoiceSearchData = new List<InvoiceSearchData>() },
- textSearch.ToArray());
- }
-
- var settings = await _settingsRepository.GetSettingAsync<MigrationSettings>();
- if (i + 1 < totalPages)
- {
- settings.MigratedInvoiceTextSearchPages = i;
- }
- else
- {
- // during final pass we set int.MaxValue so migration doesn't run again
- settings.MigratedInvoiceTextSearchPages = int.MaxValue;
- }
-
- // this call triggers update; we're sure that MigrationSettings is already initialized in db
- // because of logic executed in MigrationStartupTask.cs
- _settingsRepository.UpdateSettingInContext(ctx, settings);
- await ctx.SaveChangesAsync();
- }
- Logs.PayServer.LogInformation($"Full invoice search import successful");
- }
-
- private async Task<int> CountInvoices()
- {
- using var ctx = _dbContextFactory.CreateContext();
- return await ctx.Invoices.CountAsync();
- }
- }
-}
### BTCPayServer/HostedServices/InvoiceBlobMigratorHostedService.cs
@@ -1,83 +0,0 @@
-#nullable enable
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using BTCPayServer.Abstractions.Contracts;
-using BTCPayServer.Data;
-using BTCPayServer.Services.Invoices;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.Logging;
-using Newtonsoft.Json.Linq;
-
-namespace BTCPayServer.HostedServices;
-
-public class InvoiceBlobMigratorHostedService : BlobMigratorHostedService<InvoiceData>
-{
-
- private readonly PaymentMethodHandlerDictionary _handlers;
-
- public InvoiceBlobMigratorHostedService(
- ILogger<InvoiceBlobMigratorHostedService> logs,
- ISettingsRepository settingsRepository,
- ApplicationDbContextFactory applicationDbContextFactory,
- PaymentMethodHandlerDictionary handlers) : base(logs, settingsRepository, applicationDbContextFactory)
- {
- _handlers = handlers;
- }
-
- public override string SettingsKey => "InvoicesMigration";
- protected override IQueryable<InvoiceData> GetQuery(ApplicationDbContext ctx, DateTimeOffset? progress)
- {
- var query = progress is DateTimeOffset last2 ?
- ctx.Invoices.Include(o => o.Payments).Where(i => i.Created < last2 && i.Currency == null) :
- ctx.Invoices.Include(o => o.Payments).Where(i => i.Currency == null);
- return query.OrderByDescending(i => i.Created);
- }
- protected override Task Reindex(ApplicationDbContext ctx, CancellationToken cancellationToken)
- {
- return ctx.Database.ExecuteSqlRawAsync("REINDEX INDEX \"IX_Invoices_Created\";REINDEX INDEX \"PK_Invoices\";", cancellationToken);
- }
- protected override DateTimeOffset ProcessEntities(ApplicationDbContext ctx, List<InvoiceData> invoices)
- {
- // Those clean up the JSON blobs
- foreach (var inv in invoices)
- {
- var blob = inv.GetBlob();
- var prompts = blob.GetPaymentPrompts();
- foreach (var p in prompts)
- {
- if (_handlers.TryGetValue(p.PaymentMethodId, out var handler) && p.Details is not (null or { Type: JTokenType.Null }))
- {
- p.Details = JToken.FromObject(handler.ParsePaymentPromptDetails(p.Details), handler.Serializer);
- }
- }
- blob.SetPaymentPrompts(prompts);
- inv.SetBlob(blob);
- foreach (var pay in inv.Payments)
- {
- var paymentEntity = pay.GetBlob();
- if (_handlers.TryGetValue(paymentEntity.PaymentMethodId, out var handler) && paymentEntity.Details is not (null or { Type: JTokenType.Null }))
- {
- paymentEntity.Details = JToken.FromObject(handler.ParsePaymentDetails(paymentEntity.Details), handler.Serializer);
- }
- pay.SetBlob(paymentEntity);
-
- if (pay.MigratedPaymentMethodId is not null && pay.PaymentMethodId != pay.MigratedPaymentMethodId)
- {
- ctx.Add(pay);
- ctx.Payments.Remove(new PaymentData() { Id = pay.Id, PaymentMethodId = pay.MigratedPaymentMethodId });
- }
- }
- }
- return invoices[^1].Created;
- }
-
- protected override async Task PostMigrationCleanup(ApplicationDbContext ctx, CancellationToken cancellationToken)
- {
- Logs.LogInformation("Post-migration VACUUM (ANALYZE)");
- await ctx.Database.ExecuteSqlRawAsync("VACUUM (ANALYZE) \"Invoices\"", cancellationToken);
- Logs.LogInformation("Post-migration VACUUM (ANALYZE) finished");
- }
-}
### BTCPayServer/Hosting/BTCPayServerServices.cs
@@ -473,7 +473,6 @@ CREATE INDEX IF NOT EXISTS idx_invoices_expired_cleanup
services.AddSingleton<INotificationHandler, InvoiceEventNotification.Handler>();
services.AddSingleton<INotificationHandler, PayoutNotification.Handler>();
services.AddSingleton<INotificationHandler, ExternalPayoutTransactionNotification.Handler>();
- services.AddSingleton<IHostedService, DbMigrationsHostedService>();
services.TryAddSingleton<ExplorerClientProvider>();
services.AddSingleton<IExplorerClientProvider, ExplorerClientProvider>(x =>
@@ -781,9 +780,6 @@ internal static void RegisterRateSources(IServiceCollection services)
services.AddRateProvider<DesiboardRateProvider>();
services.AddRateProvider<CoinDCXRateProvider>();
- services.AddSingleton<InvoiceBlobMigratorHostedService>();
- services.AddSingleton<IHostedService, InvoiceBlobMigratorHostedService>(o => o.GetRequiredService<InvoiceBlobMigratorHostedService>());
-
services.AddSingleton<PaymentRequestsMigratorHostedService>();
services.AddSingleton<IHostedService, PaymentRequestsMigratorHostedService>(o => o.GetRequiredService<PaymentRequestsMigratorHostedService>());
### BTCPayServer/Hosting/MigrationStartupTask.cs
@@ -8,12 +8,10 @@
using BTCPayServer.Data;
using BTCPayServer.Payments;
using BTCPayServer.Payments.Bitcoin;
-using BTCPayServer.Payments.Lightning;
using BTCPayServer.Services;
using BTCPayServer.Services.Invoices;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
-using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Npgsql;
@@ -35,34 +33,12 @@ public async Task ExecuteAsync(CancellationToken cancellationToken = default)
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
- settings = new MigrationSettings() { MigratedInvoiceTextSearchPages = int.MaxValue, MigratedTransactionLabels = int.MaxValue };
- foreach (var prop in settings.GetType().GetProperties().Where(p => p.CanWrite && p.PropertyType == typeof(bool)))
- {
- prop.SetValue(settings, true);
- }
+ // First-run defaults are initialization, not an upgrade migration.
+ settings = new MigrationSettings { MigrateOldDerivationSchemes = true };
await settingsRepository.UpdateSetting(new ThemeSettings());
await settingsRepository.UpdateSetting(settings);
}
- if (!settings.MigrateToStoreConfig)
- {
- await MigrateToStoreConfig();
- settings.MigrateToStoreConfig = true;
- await settingsRepository.UpdateSetting(settings);
- }
- if (!settings.MigrateBlockExplorerLinks)
- {
- await MigrateBlockExplorerLinks();
- settings.MigrateBlockExplorerLinks = true;
- await settingsRepository.UpdateSetting(settings);
- }
- if (!settings.MigrateStoreExcludedPaymentMethods)
- {
- await MigrateStoreExcludedPaymentMethods();
- settings.MigrateStoreExcludedPaymentMethods = true;
- await settingsRepository.UpdateSetting(settings);
- }
if (!settings.MigrateOldDerivationSchemes)
{
await MigrateOldDerivationSchemes();
@@ -107,107 +83,6 @@ private async Task MigrateOldDerivationSchemes()
await ctx.SaveChangesAsync();
}
- private async Task MigrateStoreExcludedPaymentMethods()
- {
- await using var ctx = dbContextFactory.CreateContext();
- var stores = await ctx.Stores.ToArrayAsync();
- foreach (var store in stores)
- {
- if (store.StoreBlob is null)
- continue;
- var blob = JsonParser.ParseObject(store.StoreBlob);
- var array = blob["excludedPaymentMethods"] as JArray;
- if (array is null || array.Count == 0)
- continue;
- var newArray = new JArray(array.Select(a => MigrationExtensions.TryMigratePaymentMethodId(a.Value<string>())).ToArray());
- if (array.ToString() == newArray.ToString())
- continue;
- blob["excludedPaymentMethods"] = newArray;
- store.StoreBlob = blob.ToString();
- }
- await ctx.SaveChangesAsync();
- }
-
- private async Task MigrateBlockExplorerLinks()
- {
- await using var ctx = dbContextFactory.CreateContext();
- var settings = await ctx.Settings.Where(s => s.Id == "BTCPayServer.Services.PoliciesSettings").FirstOrDefaultAsync();
- if (settings is null)
- return;
- var obj = JsonParser.ParseObject(settings.Value);
- var arr = obj["BlockExplorerLinks"] as JArray;
- if (arr is null or { Count: 0 })
- return;
- foreach (var item in arr.OfType<JObject>())
- {
- var cryptoCode = item["CryptoCode"]?.Value<string>();
- if (cryptoCode is null)
- continue;
- item.Remove("CryptoCode");
- item["PaymentMethodId"] = PaymentTypes.CHAIN.GetPaymentMethodId(cryptoCode).ToString();
- }
- settings.Value = obj.ToString();
- await ctx.SaveChangesAsync();
- }
-
- private async Task MigrateToStoreConfig()
- {
- await using var ctx = dbContextFactory.CreateContext();
- var stores = await ctx.Stores.ToArrayAsync();
- foreach (var store in stores)
- {
- if (string.IsNullOrEmpty(store.DerivationStrategies))
- continue;
- var strategies = JsonParser.ParseObject(store.DerivationStrategies);
- foreach (var s in strategies.Properties().ToList())
- {
- var ls = s;
- var pmi = PaymentMethodId.Parse(s.Name);
- MigrationExtensions.RenameProperty(ref ls, pmi.ToString());
- if (ls.Value is JObject conf)
- {
- if (IsLN(pmi))
- {
- conf.RenameProperty("LightningConnectionString", "connectionString");
- conf.Remove("DisableBOLT11PaymentOption"); // Old
- conf.RenameProperty("InternalNodeRef", "internalNodeRef");
- conf.Remove("CryptoCode");
- conf.RemoveIfValue("internalNodeRef", null as string);
- conf.RemoveIfValue("connectionString", null as string);
- }
- else if (IsLNURL(pmi))
- {
- conf.RenameProperty("LUD12Enabled", "lud12Enabled");
- conf.RenameProperty("UseBech32Scheme", "useBech32Scheme");
- conf.RemoveIfValue("lud12Enabled", false);
- conf.RemoveIfValue("useBech32Scheme", false);
- conf.Remove("CryptoCode");
- }
- else if (IsChain(pmi))
- {
- conf.RemoveIfValue("label", null as string);
- conf.RemoveIfValue("isHotWallet", false);
- }
- }
- }
- store.DerivationStrategies = strategies.ToString(Formatting.None);
- }
- await ctx.SaveChangesAsync();
- }
-
- private bool IsLN(PaymentMethodId paymentMethodId)
- {
- 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;
- }
- private bool IsLNURL(PaymentMethodId paymentMethodId)
- {
- return handlers.TryGetValue(paymentMethodId, out var v) && v is LNURLPayPaymentHandler;
- }
-
private async Task Migrate(CancellationToken cancellationToken)
{
TimeSpan cancellationTimeout = TimeSpan.FromDays(1.0);
@@ -226,13 +101,13 @@ private async Task Migrate(CancellationToken cancellationToken)
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";
+ const string baseline = "20240924065254_monitoredinvoices";
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.");
+ "Upgrade to BTCPay Server 2.0.x first, then upgrade to this version.");
}
throw;
}
### BTCPayServer/Services/MigrationSettings.cs
@@ -2,12 +2,6 @@ namespace BTCPayServer.Services
{
public class MigrationSettings
{
- // Done in DbMigrationsHostedService
- public int? MigratedInvoiceTextSearchPages { get; set; }
- public int? MigratedTransactionLabels { get; set; }
- public bool MigrateToStoreConfig { get; set; }
- public bool MigrateBlockExplorerLinks { get; set; }
- public bool MigrateStoreExcludedPaymentMethods { get; set; }
public bool MigrateOldDerivationSchemes { get; set; }
}
}
### docs/maintainers/README.md
@@ -74,32 +74,38 @@ Test both a fresh database and an upgrade from the previous schema when the chan
### Consolidated Migrations
`DBScripts/000.Init.sql` contains the schema and seed data through
-`20231020135844_AddBoltcardsTable` (BTCPay Server 1.12.0). The migration keeps its
+`20240924065254_monitoredinvoices` (BTCPay Server 2.0.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
+Startup data migrations already present in 2.0.0 are also removed; first-run
defaults remain part of initialization rather than migration flags.
+The derivation-scheme repair introduced after 2.0.0 and later payment-request
+migrations remain.
+
`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
+with a `ConfigException` explaining that an intermediate upgrade to 2.0.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`.
+`__EFMigrationsHistory`. Also export the `StoreRoles` and `lang_dictionaries`
+seed rows with `--data-only --column-inserts`. Remove dump comments, session
+settings, psql meta-commands, and `public.` qualifiers before updating `000.Init.sql`.
+Order SQL functions that query tables after those tables and their dependencies.
+Keep table creation first so unsupported databases fail with a duplicate-table
+error before encountering existing functions.
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.
+schemas and all seed data 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 forWhy this scored 34/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.