All files level-private-state-provider.ts

91.15% Statements 433/475
79.33% Branches 192/242
100% Functions 56/56
91.29% Lines 430/471

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347                                                                                            1x         1x         1x                                                                                                         1x                             1x   487x 26x 45x         1x   1x 494x     1x 494x 494x     1x         950x     950x     950x 950x 950x 950x   950x 950x       1x   1x   1x   1x                                             1x   1x 407x   407x 407x       407x 407x 407x 407x 311x 311x               96x 96x       96x 96x     407x   407x 407x   407x       1x         381x 381x 381x   381x 381x 270x 270x 269x   1x 1x 1x     111x 111x 111x 111x     1x 21x 21x 21x 21x     1x   1x         27x   27x 1x           1x       27x 27x   27x   27x 27x   27x 27x       1x         393x 393x   393x 6x           6x                         1x 4x 4x 4x                 1x     27x   27x 27x   26x 26x 26x 26x   26x       26x 26x 26x   26x 63x   37x 2x           35x 19x     35x 23x 23x   4x 4x       19x     31x 31x 31x                     20x 3x     17x       17x 17x 25x 25x 25x                     17x       17x   17x 17x                     17x         1x           175x 175x   175x 175x 175x   174x 42x         132x 132x 132x 1x 1x 1x 1x   131x               131x   131x       131x   2x     2x               1x         28x 28x   28x 28x 28x   28x 66x 28x       38x   38x 38x 38x             38x             38x         38x 38x     28x                                                   1x 1x 1x 1x         1x 15x 2x                 1x 42x 2x   40x 2x             1x 13x 2x           1x   1x 240x 240x             1x 3x 3x                 1x 240x 237x     3x 3x 3x 3x 1x   1x     1x           2x                                           1x                             242x   242x 1x           241x 1x           240x   240x 240x   240x   240x   240x 227x 3x   224x     240x   171x     113x 113x               5x 5x 5x 4x       109x 109x 109x         108x 108x   108x 108x       64x 1x   63x     63x               6x 6x     6x       70x 70x         70x 70x   70x     70x       63x       16x       16x     16x 4x       15x     12x             15x 15x 15x 21x 21x 21x       15x 1x     14x 1x             13x         19x         13x 13x   13x                     26x       26x 26x     26x 1x       25x 2x       23x     23x 11x       20x       10x 10x 10x 10x 10x     4x       16x           2x       14x 1x           13x     13x 1x     12x 1x             11x 8x 8x 11x 11x 3x     8x 2x         9x 9x 9x   9x 12x 12x   12x 3x 2x 2x 1x 1x         10x 10x   9x 8x       8x       14x   14x 4x     13x   10x           13x 1x     12x 1x         11x             11x 11x   11x                     21x 21x   21x 1x     20x 1x     19x   19x 9x     16x     8x 8x 8x 8x 8x   4x     12x           2x     10x 1x         9x   9x 1x     8x 1x         7x 4x 4x 6x 6x 3x     4x 2x       5x 5x 5x   5x 7x 7x   7x 3x 2x 2x 1x 1x       5x   5x 4x       5x               17x 1x     16x 16x   16x 16x           20x     12x           12x                 11x   11x 11x               8x           8x         1x                           1x         14x   14x 14x   14x     14x       14x 14x                   14x 14x                   14x 14x   14x 14x 10x 10x                     14x 6x 6x                       14x 14x   14x   14x 14x                                 1x     9x   9x 2x     7x       7x             7x 7x                               7x 7x                             7x    
/*
 * This file is part of midnight-js.
 * Copyright (C) 2025-2026 Midnight Foundation
 * SPDX-License-Identifier: Apache-2.0
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import type { ContractAddress, SigningKey } from '@midnight-ntwrk/compact-runtime';
import {
  ExportDecryptionError,
  type ExportPrivateStatesOptions,
  type ExportSigningKeysOptions,
  ImportConflictError,
  type ImportPrivateStatesOptions,
  type ImportPrivateStatesResult,
  type ImportSigningKeysOptions,
  type ImportSigningKeysResult,
  InvalidExportFormatError,
  MAX_EXPORT_SIGNING_KEYS,
  MAX_EXPORT_STATES,
  type PrivateStateExport,
  PrivateStateExportError,
  type PrivateStateId,
  type PrivateStateProvider,
  type SigningKeyExport,
  SigningKeyExportError
} from '@midnight-ntwrk/midnight-js-types';
import { type AbstractSublevel } from 'abstract-level';
import { Buffer } from 'buffer';
import { createHash, randomBytes } from 'crypto';
import { Level } from 'level';
import * as superjson from 'superjson';
 
import { decryptValue, getPasswordFromProvider, type PrivateStoragePasswordProvider, StorageEncryption } from './storage-encryption';
 
/**
 * The default name of the indexedDB database for Midnight.
 */
export const MN_LDB_DEFAULT_DB_NAME = 'midnight-level-db';
 
/**
 * The default name of the private state store.
 */
export const MN_LDB_DEFAULT_PRIS_STORE_NAME = 'private-states';
 
/**
 * The default name of the signing key store.
 */
export const MN_LDB_DEFAULT_KEY_STORE_NAME = 'signing-keys';
 
/**
 * Configuration properties for the LevelDB based private state provider.
 */
export interface LevelPrivateStateProviderConfig {
  /**
   * The name of the LevelDB database used to store all Midnight related data.
   */
  readonly midnightDbName: string;
  /**
   * The name of the object store containing private states.
   */
  readonly privateStateStoreName: string;
  /**
   * The name of the object store containing signing keys.
   */
  readonly signingKeyStoreName: string;
  /**
   * Provider function that returns the password used for encrypting private state.
   * The password must be at least 16 characters long.
   *
   * SECURITY: Use a strong, secret password. Never use public key material
   * or other non-secret values as the password source.
   *
   * @example
   * ```typescript
   * {
   *   privateStoragePasswordProvider: async () => await getSecretPassword()
   * }
   * ```
   */
  readonly privateStoragePasswordProvider: PrivateStoragePasswordProvider;
  /**
   * Account identifier used to scope storage. This ensures data isolation
   * between different accounts/wallets using the same database.
   *
   * The accountId is hashed (SHA-256, first 32 chars) before being used
   * in storage paths, so any unique identifier can be used (e.g., wallet address).
   *
   * @example
   * ```typescript
   * {
   *   accountId: walletAddress
   * }
   * ```
   */
  readonly accountId: string;
}
 
/**
 * The default configuration for the level database.
 */
export const DEFAULT_CONFIG = {
  /**
   * The name of the database.
   */
  midnightDbName: MN_LDB_DEFAULT_DB_NAME,
  /**
   * The name of the "level" on which to store private state.
   */
  privateStateStoreName: MN_LDB_DEFAULT_PRIS_STORE_NAME,
  /**
   * The name of the "level" on which to store signing keys.
   */
  signingKeyStoreName: MN_LDB_DEFAULT_KEY_STORE_NAME
};
 
superjson.registerCustom<Buffer, string>(
  {
    isApplicable: (v): v is Buffer => v instanceof Buffer,
    serialize: (v) => v.toString('hex'),
    deserialize: (v) => Buffer.from(v, 'hex')
  },
  'buffer'
);
 
const ACCOUNT_ID_HASH_LENGTH = 32;
 
const hashAccountId = (accountId: string): string => {
  return createHash('sha256').update(accountId).digest('hex').substring(0, ACCOUNT_ID_HASH_LENGTH);
};
 
const getScopedLevelName = (baseLevelName: string, accountId: string): string => {
  const hashedAccountId = hashAccountId(accountId);
  return `${baseLevelName}:${hashedAccountId}`;
};
 
const withSubLevel = async <K, V, A>(
  dbName: string,
  levelName: string,
  thunk: (subLevel: AbstractSublevel<Level, string | Uint8Array | Buffer, K, V>) => Promise<A>
): Promise<A> => {
  const level = new Level(dbName, {
    createIfMissing: true
  });
  const subLevel = level.sublevel<K, V>(levelName, {
    valueEncoding: 'utf-8'
  });
  try {
    await level.open();
    await subLevel.open();
    return await thunk(subLevel);
  } finally {
    await subLevel.close();
    await level.close();
  }
};
 
const METADATA_KEY = '__midnight_encryption_metadata__';
 
const DEFAULT_MAX_ROTATION_ENTRIES = 10000;
 
const encryptionInitPromises = new Map<string, Promise<Buffer>>();
 
const passwordRotationLocks = new Map<string, Promise<void>>();
 
export interface PasswordRotationResult {
  readonly entriesMigrated: number;
}
 
export interface PasswordRotationOptions {
  readonly maxEntries?: number;
}
 
interface EncryptionCacheEntry {
  readonly encryption: StorageEncryption;
  readonly saltHex: string;
}
 
/**
 * Module-level cache for StorageEncryption instances, keyed by `${dbName}:${levelName}`.
 * This cache avoids repeated PBKDF2 key derivation (600,000 iterations) on each operation.
 *
 * Note: This cache has no size limit. For typical usage with a small number of
 * database/level combinations, this is acceptable. If using dynamic db/level names,
 * call `invalidateEncryptionCache()` to prevent unbounded growth.
 */
const encryptionCache = new Map<string, EncryptionCacheEntry>();
 
const getOrCreateSalt = async (dbName: string, levelName: string): Promise<Buffer> => {
  const lockKey = `${dbName}:${levelName}`;
 
  const existingPromise = encryptionInitPromises.get(lockKey);
  Iif (existingPromise) {
    return existingPromise;
  }
 
  const initPromise = withSubLevel<string, string, Buffer>(dbName, levelName, async (subLevel) => {
    try {
      const metadataJson = await subLevel.get(METADATA_KEY);
      if (metadataJson) {
        const metadata = JSON.parse(metadataJson);
        return Buffer.from(metadata.salt, 'hex');
      }
    } catch (error: unknown) {
      if (!(error && typeof error === 'object' && 'code' in error && error.code === 'LEVEL_NOT_FOUND')) {
        throw error;
      }
    }
 
    const salt = randomBytes(32);
    const metadata = {
      salt: salt.toString('hex'),
      version: 1
    };
    await subLevel.put(METADATA_KEY, JSON.stringify(metadata));
    return salt;
  });
 
  encryptionInitPromises.set(lockKey, initPromise);
 
  try {
    return await initPromise;
  } finally {
    encryptionInitPromises.delete(lockKey);
  }
};
 
const getOrCreateEncryption = async (
  dbName: string,
  levelName: string,
  passwordProvider: PrivateStoragePasswordProvider
): Promise<StorageEncryption> => {
  const cacheKey = `${dbName}:${levelName}`;
  const salt = await getOrCreateSalt(dbName, levelName);
  const saltHex = salt.toString('hex');
 
  const cached = encryptionCache.get(cacheKey);
  if (cached && cached.saltHex === saltHex) {
    const password = await getPasswordFromProvider(passwordProvider);
    if (cached.encryption.verifyPassword(password)) {
      return cached.encryption;
    }
    const encryption = new StorageEncryption(password, salt);
    encryptionCache.set(cacheKey, { encryption, saltHex });
    return encryption;
  }
 
  const password = await getPasswordFromProvider(passwordProvider);
  const encryption = new StorageEncryption(password, salt);
  encryptionCache.set(cacheKey, { encryption, saltHex });
  return encryption;
};
 
const invalidateEncryptionCacheForDb = (dbName: string, privateStateStoreName: string, signingKeyStoreName: string): void => {
  const privateStateKey = `${dbName}:${privateStateStoreName}`;
  const signingKeyKey = `${dbName}:${signingKeyStoreName}`;
  encryptionCache.delete(privateStateKey);
  encryptionCache.delete(signingKeyKey);
};
 
const DEFAULT_LOCK_TIMEOUT_MS = 300000; // 5 minutes
 
const withPasswordRotationLock = async <T>(
  lockKey: string,
  operation: () => Promise<T>,
  timeoutMs: number = DEFAULT_LOCK_TIMEOUT_MS
): Promise<T> => {
  const startWait = Date.now();
 
  while (passwordRotationLocks.has(lockKey)) {
    Iif (Date.now() - startWait > timeoutMs) {
      throw new Error(
        `Timed out waiting for password rotation lock on "${lockKey}". ` +
          `Another rotation may be stuck or taking longer than ${timeoutMs}ms.`
      );
    }
    await passwordRotationLocks.get(lockKey);
  }
 
  let resolve!: () => void;
  const lockPromise = new Promise<void>((r) => {
    resolve = r;
  });
  passwordRotationLocks.set(lockKey, lockPromise);
 
  try {
    return await operation();
  } finally {
    passwordRotationLocks.delete(lockKey);
    resolve();
  }
};
 
const waitForRotationLock = async (
  dbName: string,
  levelName: string,
  timeoutMs: number = DEFAULT_LOCK_TIMEOUT_MS
): Promise<void> => {
  const lockKey = `${dbName}:${levelName}`;
  const startWait = Date.now();
 
  while (passwordRotationLocks.has(lockKey)) {
    Iif (Date.now() - startWait > timeoutMs) {
      throw new Error(
        `Timed out waiting for password rotation to complete on "${lockKey}". ` +
          `The rotation may be stuck or taking longer than ${timeoutMs}ms.`
      );
    }
    await passwordRotationLocks.get(lockKey);
  }
};
 
interface RotateStorePasswordParams {
  readonly dbName: string;
  readonly storeName: string;
  readonly oldPasswordProvider: PrivateStoragePasswordProvider;
  readonly newPasswordProvider: PrivateStoragePasswordProvider;
  readonly maxEntries: number;
  readonly shouldProceed?: (key: string) => boolean;
}
 
const isDecryptionError = (error: unknown): boolean => {
  Iif (!(error instanceof Error)) return false;
  const message = error.message.toLowerCase();
  return (
    message.includes('unsupported state') ||
    message.includes('salt mismatch') ||
    message.includes('invalid encrypted data') ||
    message.includes('bad decrypt') ||
    message.includes('unable to authenticate')
  );
};
 
const rotateStorePassword = async (
  params: RotateStorePasswordParams
): Promise<PasswordRotationResult> => {
  const { dbName, storeName, oldPasswordProvider, newPasswordProvider, maxEntries, shouldProceed } = params;
 
  const oldPassword = await getPasswordFromProvider(oldPasswordProvider);
  const newPassword = await getPasswordFromProvider(newPasswordProvider);
 
  const salt = await getOrCreateSalt(dbName, storeName);
  const oldEncryption = new StorageEncryption(oldPassword, salt);
  const newEncryption = new StorageEncryption(newPassword);
  const newSalt = newEncryption.getSalt();
 
  return withSubLevel<string, string, PasswordRotationResult>(
    dbName,
    storeName,
    async (subLevel) => {
      const entriesToMigrate: { key: string; decryptedValue: string }[] = [];
      let hasMatchingData = false;
      let firstEntryValidated = false;
 
      for await (const [key, encryptedValue] of subLevel.iterator()) {
        if (key === METADATA_KEY) continue;
 
        if (entriesToMigrate.length >= maxEntries) {
          throw new Error(
            `Entry count exceeds maximum allowed (${maxEntries}). ` +
            `Use the maxEntries option to increase the limit if needed.`
          );
        }
 
        if (shouldProceed && shouldProceed(key)) {
          hasMatchingData = true;
        }
 
        if (!firstEntryValidated) {
          try {
            decryptValue(encryptedValue, oldEncryption, oldPassword);
          } catch (error: unknown) {
            Eif (isDecryptionError(error)) {
              throw new Error('Old password is incorrect: failed to decrypt existing data', { cause: error });
            }
            throw error;
          }
          firstEntryValidated = true;
        }
 
        try {
          const decryptedValue = decryptValue(encryptedValue, oldEncryption, oldPassword);
          entriesToMigrate.push({ key, decryptedValue });
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : 'Unknown error';
          throw new Error(
            `Failed to decrypt entry "${key}": ${errorMessage}. ` +
            `Successfully processed ${entriesToMigrate.length} entries before failure.`,
            { cause: error }
          );
        }
      }
 
      if (entriesToMigrate.length === 0) {
        return { entriesMigrated: 0 };
      }
 
      Iif (shouldProceed && !hasMatchingData) {
        return { entriesMigrated: 0 };
      }
 
      const operations: { type: 'put'; key: string; value: string }[] = [];
      for (const { key, decryptedValue } of entriesToMigrate) {
        try {
          const encryptedValue = newEncryption.encrypt(decryptedValue);
          operations.push({ type: 'put', key, value: encryptedValue });
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : 'Unknown error';
          throw new Error(
            `Failed to re-encrypt entry "${key}": ${errorMessage}. ` +
            `Original data is still encrypted with old password.`,
            { cause: error }
          );
        }
      }
 
      const metadata = {
        salt: newSalt.toString('hex'),
        version: 1
      };
      operations.push({ type: 'put', key: METADATA_KEY, value: JSON.stringify(metadata) });
 
      try {
        await subLevel.batch(operations);
      } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        throw new Error(
          `Failed to write re-encrypted data: ${errorMessage}. ` +
          `Your data may be in an inconsistent state. ` +
          `Keep both old and new passwords until you can verify data integrity.`,
          { cause: error }
        );
      }
 
      return { entriesMigrated: entriesToMigrate.length };
    }
  );
};
 
const subLevelMaybeGet = async <K, V>(
  dbName: string,
  levelName: string,
  key: K,
  passwordProvider: PrivateStoragePasswordProvider
): Promise<V | null> => {
  await waitForRotationLock(dbName, levelName);
  const encryption = await getOrCreateEncryption(dbName, levelName, passwordProvider);
 
  return withSubLevel<K, string, V | null>(dbName, levelName, async (subLevel) => {
    try {
      const encryptedValue = await subLevel.get(key);
 
      if (encryptedValue === undefined) {
        return null;
      }
 
      let decryptedValue: string;
 
      if (StorageEncryption.isEncrypted(encryptedValue)) {
        const version = StorageEncryption.getVersion(encryptedValue);
        if (version === 1) {
          const password = await getPasswordFromProvider(passwordProvider);
          decryptedValue = encryption.decryptWithPassword(encryptedValue, password);
          const reEncrypted = encryption.encrypt(decryptedValue);
          await subLevel.put(key, reEncrypted);
        } else {
          decryptedValue = encryption.decrypt(encryptedValue);
        }
      } else E{
        decryptedValue = encryptedValue;
        const reEncrypted = encryption.encrypt(encryptedValue);
        await subLevel.put(key, reEncrypted);
      }
 
      const value = superjson.parse<V>(decryptedValue);
 
      Iif (value === undefined) {
        return null;
      }
 
      return value;
    } catch (error: unknown) {
      Iif (error && typeof error === 'object' && 'code' in error && error.code === 'LEVEL_NOT_FOUND') {
        return null;
      }
      throw error;
    }
  });
};
 
/**
 * Iterate all key-value pairs in a sublevel, excluding metadata keys.
 */
const getAllEntries = async <K extends string, V>(
  dbName: string,
  levelName: string,
  passwordProvider: PrivateStoragePasswordProvider
): Promise<Map<K, V>> => {
  await waitForRotationLock(dbName, levelName);
  const encryption = await getOrCreateEncryption(dbName, levelName, passwordProvider);
 
  return withSubLevel<K, string, Map<K, V>>(dbName, levelName, async (subLevel) => {
    const entries = new Map<K, V>();
    let password: string | null = null;
 
    for await (const [key, encryptedValue] of subLevel.iterator()) {
      if (key === METADATA_KEY) {
        continue;
      }
 
      let decryptedValue: string;
      let needsReEncryption = false;
 
      if (StorageEncryption.isEncrypted(encryptedValue)) {
        const version = StorageEncryption.getVersion(encryptedValue);
        Iif (version === 1) {
          if (password === null) {
            password = await getPasswordFromProvider(passwordProvider);
          }
          decryptedValue = encryption.decryptWithPassword(encryptedValue, password);
          needsReEncryption = true;
        } else {
          decryptedValue = encryption.decrypt(encryptedValue);
        }
      } else E{
        decryptedValue = encryptedValue;
        needsReEncryption = true;
      }
 
      Iif (needsReEncryption) {
        const reEncrypted = encryption.encrypt(decryptedValue);
        await subLevel.put(key, reEncrypted);
      }
 
      const value = superjson.parse<V>(decryptedValue);
      entries.set(key as K, value);
    }
 
    return entries;
  });
};
 
/**
 * Internal structure of the decrypted export payload.
 * Includes metadata to ensure it's authenticated by the encryption.
 */
interface PrivateStatePayload<PSI extends PrivateStateId = PrivateStateId> {
  readonly version: number;
  readonly exportedAt: string;
  readonly stateCount: number;
  readonly states: Record<PSI, string>;
}
 
/**
 * Internal structure of the decrypted signing key export payload.
 * Includes metadata to ensure it's authenticated by the encryption.
 */
interface SigningKeyPayload {
  readonly version: number;
  readonly exportedAt: string;
  readonly keyCount: number;
  readonly keys: Record<ContractAddress, SigningKey>;
}
 
const CURRENT_EXPORT_VERSION = 1;
const SUPPORTED_EXPORT_VERSIONS = [1];
const EXPECTED_SALT_LENGTH = 64; // 32 bytes as hex
const MIN_PASSWORD_LENGTH = 16;
 
/**
 * Validates a custom password meets minimum requirements.
 */
const validateExportPassword = (password: string): void => {
  if (password.length < MIN_PASSWORD_LENGTH) {
    throw new PrivateStateExportError(
      `Password must be at least ${MIN_PASSWORD_LENGTH} characters`
    );
  }
};
 
/**
 * Validates the salt format and length.
 */
const validateSalt = (salt: string): void => {
  if (salt.length !== EXPECTED_SALT_LENGTH) {
    throw new InvalidExportFormatError('Invalid salt length');
  }
  if (!/^[0-9a-fA-F]+$/.test(salt)) {
    throw new InvalidExportFormatError('Invalid salt format');
  }
};
 
/**
 * Validates a custom signing key export password meets minimum requirements.
 */
const validateSigningKeyExportPassword = (password: string): void => {
  if (password.length < MIN_PASSWORD_LENGTH) {
    throw new SigningKeyExportError(
      `Password must be at least ${MIN_PASSWORD_LENGTH} characters`
    );
  }
};
 
const BROWSER_WARNING_KEY = '__midnight_browser_warning_shown__';
 
const isBrowserEnvironment = (): boolean => {
  const global = globalThis as Record<string, unknown>;
  return typeof globalThis !== 'undefined' &&
    'window' in globalThis &&
    global.window !== undefined &&
    'document' in globalThis &&
    global.document !== undefined;
};
 
const getSessionStorage = (): Storage | undefined => {
  Eif (typeof globalThis !== 'undefined' && 'sessionStorage' in globalThis) {
    return (globalThis as Record<string, unknown>).sessionStorage as Storage | undefined;
  }
  return undefined;
};
 
/**
 * Shows a warning about browser storage risks.
 * Only shows once per session using sessionStorage.
 */
const showBrowserWarning = (): void => {
  if (!isBrowserEnvironment()) {
    return;
  }
 
  try {
    const storage = getSessionStorage();
    Eif (storage) {
      if (storage.getItem(BROWSER_WARNING_KEY)) {
        return;
      }
      storage.setItem(BROWSER_WARNING_KEY, 'true');
    }
  } catch (error: unknown) {
    console.debug(
      'MIDNIGHT: Could not access sessionStorage for warning deduplication:',
      error instanceof Error ? error.message : 'Unknown error'
    );
  }
 
  console.warn(
    `⚠️ MIDNIGHT: Private state and signing keys are stored in browser storage.\n` +
    `Clearing browser cache or storage will permanently destroy this data.\n` +
    `For assets with real-world value, this may result in irreversible financial loss.\n` +
    `Use exportPrivateStates() and exportSigningKeys() to create backups.`
  );
};
 
/* eslint-disable @typescript-eslint/no-explicit-any */
 
/**
 * Constructs an instance of {@link PrivateStateProvider} based on {@link Level} database.
 *
 * ⚠️ WARNING
 *
 * RISK: This provider lacks a recovery mechanism.
 * Clearing browser cache or deleting local files permanently destroys the private state (contract state/keys).
 * For assets with real-world value, this may result in irreversible financial loss.
 * DO NOT use for production applications requiring data persistence.
 *
 * @param config Database configuration options.
 */
export const levelPrivateStateProvider = <PSI extends PrivateStateId, PS = any>(
  config: Partial<LevelPrivateStateProviderConfig> & Pick<LevelPrivateStateProviderConfig, 'privateStoragePasswordProvider' | 'accountId'>
): PrivateStateProvider<PSI, PS> & {
  invalidateEncryptionCache(): void;
  changePassword(
    oldPasswordProvider: PrivateStoragePasswordProvider,
    newPasswordProvider: PrivateStoragePasswordProvider,
    options?: PasswordRotationOptions
  ): Promise<PasswordRotationResult>;
  changeSigningKeysPassword(
    oldPasswordProvider: PrivateStoragePasswordProvider,
    newPasswordProvider: PrivateStoragePasswordProvider,
    options?: PasswordRotationOptions
  ): Promise<PasswordRotationResult>;
} => {
  const fullConfig = { ...DEFAULT_CONFIG, ...config };
 
  if (!config.privateStoragePasswordProvider) {
    throw new Error(
      'privateStoragePasswordProvider is required.\n' +
      'Provide a function that returns a strong, secret password (minimum 16 characters).'
    );
  }
 
  if (!config.accountId || config.accountId.trim().length === 0) {
    throw new Error(
      'accountId is required.\n' +
      'Provide an account identifier (e.g., wallet address) to scope storage and prevent cross-account data access.'
    );
  }
 
  const passwordProvider: PrivateStoragePasswordProvider = config.privateStoragePasswordProvider;
 
  const scopedPrivateStateLevelName = getScopedLevelName(fullConfig.privateStateStoreName, config.accountId);
  const scopedSigningKeyLevelName = getScopedLevelName(fullConfig.signingKeyStoreName, config.accountId);
 
  showBrowserWarning();
 
  let contractAddress: ContractAddress | null = null;
 
  const getScopedKey = (privateStateId: PSI): string => {
    if (contractAddress === null) {
      throw new Error('Contract address not set. Call setContractAddress() before accessing private state.');
    }
    return `${contractAddress}:${privateStateId}`;
  };
 
  return {
    setContractAddress(address: ContractAddress): void {
      contractAddress = address;
    },
    async get(privateStateId: PSI): Promise<PS | null> {
      const scopedKey = getScopedKey(privateStateId);
      return subLevelMaybeGet<string, PS>(
        fullConfig.midnightDbName,
        scopedPrivateStateLevelName,
        scopedKey,
        passwordProvider
      );
    },
    async remove(privateStateId: PSI): Promise<void> {
      await waitForRotationLock(fullConfig.midnightDbName, scopedPrivateStateLevelName);
      const scopedKey = getScopedKey(privateStateId);
      return withSubLevel<string, string, void>(fullConfig.midnightDbName, scopedPrivateStateLevelName, (subLevel) =>
        subLevel.del(scopedKey)
      );
    },
    async set(privateStateId: PSI, state: PS): Promise<void> {
      await waitForRotationLock(fullConfig.midnightDbName, scopedPrivateStateLevelName);
      const scopedKey = getScopedKey(privateStateId);
      const encryption = await getOrCreateEncryption(
        fullConfig.midnightDbName,
        scopedPrivateStateLevelName,
        passwordProvider
      );
      const serialized = superjson.stringify(state);
      const encrypted = encryption.encrypt(serialized);
 
      return withSubLevel<string, string, void>(fullConfig.midnightDbName, scopedPrivateStateLevelName, (subLevel) =>
        subLevel.put(scopedKey, encrypted)
      );
    },
    async clear(): Promise<void> {
      if (contractAddress === null) {
        throw new Error('Contract address not set. Call setContractAddress() before accessing private state.');
      }
      return withSubLevel(fullConfig.midnightDbName, scopedPrivateStateLevelName, (subLevel) => subLevel.clear());
    },
    getSigningKey(address: ContractAddress): Promise<SigningKey | null> {
      return subLevelMaybeGet<ContractAddress, SigningKey>(
        fullConfig.midnightDbName,
        scopedSigningKeyLevelName,
        address,
        passwordProvider
      );
    },
    async removeSigningKey(address: ContractAddress): Promise<void> {
      await waitForRotationLock(fullConfig.midnightDbName, scopedSigningKeyLevelName);
      return withSubLevel<ContractAddress, string, void>(
        fullConfig.midnightDbName,
        scopedSigningKeyLevelName,
        (subLevel) => subLevel.del(address)
      );
    },
    async setSigningKey(address: ContractAddress, signingKey: SigningKey): Promise<void> {
      await waitForRotationLock(fullConfig.midnightDbName, scopedSigningKeyLevelName);
      const encryption = await getOrCreateEncryption(
        fullConfig.midnightDbName,
        scopedSigningKeyLevelName,
        passwordProvider
      );
      const serialized = superjson.stringify(signingKey);
      const encrypted = encryption.encrypt(serialized);
 
      return withSubLevel<ContractAddress, string, void>(
        fullConfig.midnightDbName,
        scopedSigningKeyLevelName,
        (subLevel) => subLevel.put(address, encrypted)
      );
    },
    clearSigningKeys(): Promise<void> {
      return withSubLevel(fullConfig.midnightDbName, scopedSigningKeyLevelName, (subLevel) => subLevel.clear());
    },
 
    async exportPrivateStates(options?: ExportPrivateStatesOptions): Promise<PrivateStateExport> {
      Iif (contractAddress === null) {
        throw new Error('Contract address not set. Call setContractAddress() before exporting private states.');
      }
 
      const maxStates = options?.maxStates ?? MAX_EXPORT_STATES;
 
      // Validate custom password if provided
      if (options?.password !== undefined) {
        validateExportPassword(options.password);
      }
 
      // Determine export password - use provided password or storage password
      const exportPassword = options?.password ?? await getPasswordFromProvider(passwordProvider);
 
      // Get all private states (not signing keys)
      const allStates = await getAllEntries<string, PS>(
        fullConfig.midnightDbName,
        scopedPrivateStateLevelName,
        passwordProvider
      );
 
      // Filter and extract only states for the current contract address
      const prefix = `${contractAddress}:`;
      const states = new Map<PSI, PS>();
      for (const [scopedKey, value] of allStates.entries()) {
        Eif (scopedKey.startsWith(prefix)) {
          const rawStateId = scopedKey.slice(prefix.length) as PSI;
          states.set(rawStateId, value);
        }
      }
 
      if (states.size === 0) {
        throw new PrivateStateExportError('No private states to export');
      }
 
      if (states.size > maxStates) {
        throw new PrivateStateExportError(
          `Too many states to export (${states.size}). Maximum allowed: ${maxStates}`
        );
      }
 
      // Serialize states using superjson (to preserve types like BigInt, Buffer, etc.)
      // Include metadata in the encrypted payload to ensure it's authenticated
      const payload: PrivateStatePayload<PSI> = {
        version: CURRENT_EXPORT_VERSION,
        exportedAt: new Date().toISOString(),
        stateCount: states.size,
        states: Object.fromEntries(
          Array.from(states.entries()).map(([key, value]) => [key, superjson.stringify(value)])
        ) as Record<PSI, string>
      };
 
      // Create new encryption instance for export (different salt from storage)
      const exportEncryption = new StorageEncryption(exportPassword);
      const encryptedPayload = exportEncryption.encrypt(JSON.stringify(payload));
 
      return {
        format: 'midnight-private-state-export',
        encryptedPayload,
        salt: exportEncryption.getSalt().toString('hex')
      };
    },
 
    async importPrivateStates(
      exportData: PrivateStateExport,
      options?: ImportPrivateStatesOptions
    ): Promise<ImportPrivateStatesResult> {
      Iif (contractAddress === null) {
        throw new Error('Contract address not set. Call setContractAddress() before importing private states.');
      }
 
      const conflictStrategy = options?.conflictStrategy ?? 'error';
      const maxStates = options?.maxStates ?? MAX_EXPORT_STATES;
 
      // Validate format identifier
      if (exportData.format !== 'midnight-private-state-export') {
        throw new InvalidExportFormatError('Unrecognized export format');
      }
 
      // Validate structure
      if (!exportData.encryptedPayload || !exportData.salt) {
        throw new InvalidExportFormatError('Missing required fields');
      }
 
      // Validate salt format
      validateSalt(exportData.salt);
 
      // Validate custom password if provided
      if (options?.password !== undefined) {
        validateExportPassword(options.password);
      }
 
      // Determine import password - use provided password or storage password
      const importPassword = options?.password ?? await getPasswordFromProvider(passwordProvider);
 
      // Decrypt the payload - use single generic error to prevent oracle attacks
      let payload: PrivateStatePayload<PSI>;
      try {
        const salt = Buffer.from(exportData.salt, 'hex');
        const importEncryption = new StorageEncryption(importPassword, salt);
        const decryptedJson = importEncryption.decrypt(exportData.encryptedPayload);
        payload = JSON.parse(decryptedJson);
      } catch {
        // Single generic error - don't reveal whether password was wrong or data was corrupted
        throw new ExportDecryptionError();
      }
 
      // Validate payload structure (metadata is now inside encrypted payload)
      if (
        !payload.states ||
        typeof payload.states !== 'object' ||
        typeof payload.version !== 'number' ||
        typeof payload.stateCount !== 'number'
      ) {
        throw new ExportDecryptionError();
      }
 
      // Validate version from authenticated payload
      if (!SUPPORTED_EXPORT_VERSIONS.includes(payload.version)) {
        throw new InvalidExportFormatError(
          `Export version ${payload.version} is not supported. Supported versions: ${SUPPORTED_EXPORT_VERSIONS.join(', ')}`
        );
      }
 
      // stateIds are raw state IDs (not scoped with contract address)
      const stateIds = Object.keys(payload.states) as PSI[];
 
      // Validate state count matches and is within limits
      if (stateIds.length !== payload.stateCount) {
        throw new ExportDecryptionError();
      }
 
      if (stateIds.length > maxStates) {
        throw new InvalidExportFormatError(
          `Too many states in export (${stateIds.length}). Maximum allowed: ${maxStates}`
        );
      }
 
      // Check for conflicts if strategy is 'error'
      // Use this.get() which properly scopes the state IDs
      if (conflictStrategy === 'error') {
        let conflictCount = 0;
        for (const stateId of stateIds) {
          const existing = await this.get(stateId);
          if (existing !== null) {
            conflictCount++;
          }
        }
        if (conflictCount > 0) {
          throw new ImportConflictError(conflictCount);
        }
      }
 
      // Import states
      let imported = 0;
      let skipped = 0;
      let overwritten = 0;
 
      for (const stateId of stateIds) {
        const serializedState = payload.states[stateId];
        const existingState = await this.get(stateId);
 
        if (existingState !== null) {
          if (conflictStrategy === 'skip') {
            skipped++;
            continue;
          } else if (EconflictStrategy === 'overwrite') {
            overwritten++;
          }
        }
 
        // Deserialize and store the state
        const state = superjson.parse<PS>(serializedState);
        await this.set(stateId, state);
 
        if (existingState === null) {
          imported++;
        }
      }
 
      return { imported, skipped, overwritten };
    },
 
    async exportSigningKeys(options?: ExportSigningKeysOptions): Promise<SigningKeyExport> {
      const maxKeys = options?.maxKeys ?? MAX_EXPORT_SIGNING_KEYS;
 
      if (options?.password !== undefined) {
        validateSigningKeyExportPassword(options.password);
      }
 
      const exportPassword = options?.password ?? await getPasswordFromProvider(passwordProvider);
 
      const allKeys = await getAllEntries<ContractAddress, SigningKey>(
        fullConfig.midnightDbName,
        scopedSigningKeyLevelName,
        passwordProvider
      );
 
      if (allKeys.size === 0) {
        throw new SigningKeyExportError('No signing keys to export');
      }
 
      if (allKeys.size > maxKeys) {
        throw new SigningKeyExportError(
          `Too many keys to export (${allKeys.size}). Maximum allowed: ${maxKeys}`
        );
      }
 
      const payload: SigningKeyPayload = {
        version: CURRENT_EXPORT_VERSION,
        exportedAt: new Date().toISOString(),
        keyCount: allKeys.size,
        keys: Object.fromEntries(allKeys.entries()) as Record<ContractAddress, SigningKey>
      };
 
      const exportEncryption = new StorageEncryption(exportPassword);
      const encryptedPayload = exportEncryption.encrypt(JSON.stringify(payload));
 
      return {
        format: 'midnight-signing-key-export',
        encryptedPayload,
        salt: exportEncryption.getSalt().toString('hex')
      };
    },
 
    async importSigningKeys(
      exportData: SigningKeyExport,
      options?: ImportSigningKeysOptions
    ): Promise<ImportSigningKeysResult> {
      const conflictStrategy = options?.conflictStrategy ?? 'error';
      const maxKeys = options?.maxKeys ?? MAX_EXPORT_SIGNING_KEYS;
 
      if (exportData.format !== 'midnight-signing-key-export') {
        throw new InvalidExportFormatError('Unrecognized export format');
      }
 
      if (!exportData.encryptedPayload || !exportData.salt) {
        throw new InvalidExportFormatError('Missing required fields');
      }
 
      validateSalt(exportData.salt);
 
      if (options?.password !== undefined) {
        validateSigningKeyExportPassword(options.password);
      }
 
      const importPassword = options?.password ?? await getPasswordFromProvider(passwordProvider);
 
      let payload: SigningKeyPayload;
      try {
        const salt = Buffer.from(exportData.salt, 'hex');
        const importEncryption = new StorageEncryption(importPassword, salt);
        const decryptedJson = importEncryption.decrypt(exportData.encryptedPayload);
        payload = JSON.parse(decryptedJson);
      } catch {
        throw new ExportDecryptionError();
      }
 
      if (
        !payload.keys ||
        typeof payload.keys !== 'object' ||
        typeof payload.version !== 'number' ||
        typeof payload.keyCount !== 'number'
      ) {
        throw new ExportDecryptionError();
      }
 
      if (!SUPPORTED_EXPORT_VERSIONS.includes(payload.version)) {
        throw new InvalidExportFormatError(
          `Export version ${payload.version} is not supported. Supported versions: ${SUPPORTED_EXPORT_VERSIONS.join(', ')}`
        );
      }
 
      const addresses = Object.keys(payload.keys) as ContractAddress[];
 
      if (addresses.length !== payload.keyCount) {
        throw new ExportDecryptionError();
      }
 
      if (addresses.length > maxKeys) {
        throw new InvalidExportFormatError(
          `Too many keys in export (${addresses.length}). Maximum allowed: ${maxKeys}`
        );
      }
 
      if (conflictStrategy === 'error') {
        let conflictCount = 0;
        for (const address of addresses) {
          const existing = await this.getSigningKey(address);
          if (existing !== null) {
            conflictCount++;
          }
        }
        if (conflictCount > 0) {
          throw new ImportConflictError(conflictCount, 'signing key');
        }
      }
 
      let imported = 0;
      let skipped = 0;
      let overwritten = 0;
 
      for (const address of addresses) {
        const signingKey = payload.keys[address];
        const existingKey = await this.getSigningKey(address);
 
        if (existingKey !== null) {
          if (conflictStrategy === 'skip') {
            skipped++;
            continue;
          } else if (EconflictStrategy === 'overwrite') {
            overwritten++;
          }
        }
 
        await this.setSigningKey(address, signingKey);
 
        if (existingKey === null) {
          imported++;
        }
      }
 
      return { imported, skipped, overwritten };
    },
 
    async changePassword(
      oldPasswordProvider: PrivateStoragePasswordProvider,
      newPasswordProvider: PrivateStoragePasswordProvider,
      options?: PasswordRotationOptions
    ): Promise<PasswordRotationResult> {
      if (contractAddress === null) {
        throw new Error('Contract address not set. Call setContractAddress() before changing password.');
      }
 
      const lockKey = `${fullConfig.midnightDbName}:${scopedPrivateStateLevelName}`;
      const prefix = `${contractAddress}:`;
 
      return withPasswordRotationLock(lockKey, async () => {
        const result = await rotateStorePassword({
          dbName: fullConfig.midnightDbName,
          storeName: scopedPrivateStateLevelName,
          oldPasswordProvider,
          newPasswordProvider,
          maxEntries: options?.maxEntries ?? DEFAULT_MAX_ROTATION_ENTRIES,
          shouldProceed: (key) => key.startsWith(prefix)
        });
 
        invalidateEncryptionCacheForDb(
          fullConfig.midnightDbName,
          scopedPrivateStateLevelName,
          scopedSigningKeyLevelName
        );
 
        return result;
      });
    },
 
    async changeSigningKeysPassword(
      oldPasswordProvider: PrivateStoragePasswordProvider,
      newPasswordProvider: PrivateStoragePasswordProvider,
      options?: PasswordRotationOptions
    ): Promise<PasswordRotationResult> {
      const lockKey = `${fullConfig.midnightDbName}:${scopedSigningKeyLevelName}`;
 
      return withPasswordRotationLock(lockKey, async () => {
        const result = await rotateStorePassword({
          dbName: fullConfig.midnightDbName,
          storeName: scopedSigningKeyLevelName,
          oldPasswordProvider,
          newPasswordProvider,
          maxEntries: options?.maxEntries ?? DEFAULT_MAX_ROTATION_ENTRIES
        });
 
        invalidateEncryptionCacheForDb(
          fullConfig.midnightDbName,
          scopedPrivateStateLevelName,
          scopedSigningKeyLevelName
        );
 
        return result;
      });
    },
 
    invalidateEncryptionCache(): void {
      invalidateEncryptionCacheForDb(
        fullConfig.midnightDbName,
        scopedPrivateStateLevelName,
        scopedSigningKeyLevelName
      );
    }
  };
};
 
export interface MigrationResult {
  readonly privateStatesMigrated: number;
  readonly signingKeysMigrated: number;
}
 
const migrateSublevel = async (
  dbName: string,
  oldLevelName: string,
  newLevelName: string
): Promise<number> => {
  const level = new Level(dbName, { createIfMissing: true });
 
  try {
    await level.open();
 
    const oldSubLevel = level.sublevel<string, string>(oldLevelName, {
      valueEncoding: 'utf-8'
    });
    const newSubLevel = level.sublevel<string, string>(newLevelName, {
      valueEncoding: 'utf-8'
    });
 
    try {
      await oldSubLevel.open();
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      throw new Error(
        `Failed to open source sublevel "${oldLevelName}": ${errorMessage}. ` +
        `Ensure no other process is accessing the database.`,
        { cause: error }
      );
    }
 
    try {
      await newSubLevel.open();
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      throw new Error(
        `Failed to open target sublevel "${newLevelName}": ${errorMessage}. ` +
        `Ensure no other process is accessing the database.`,
        { cause: error }
      );
    }
 
    let count = 0;
    const operations: { type: 'put'; key: string; value: string }[] = [];
 
    try {
      for await (const [key, value] of oldSubLevel.iterator()) {
        operations.push({ type: 'put', key, value });
        count++;
      }
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      throw new Error(
        `Failed to read data from source sublevel "${oldLevelName}" after ${count} entries: ${errorMessage}. ` +
        `Migration incomplete. Source data is unchanged.`,
        { cause: error }
      );
    }
 
    if (operations.length > 0) {
      try {
        await newSubLevel.batch(operations);
      } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        throw new Error(
          `Failed to write ${operations.length} entries to target sublevel "${newLevelName}": ${errorMessage}. ` +
          `Migration incomplete. Target sublevel may contain partial data. ` +
          `Source data at "${oldLevelName}" is unchanged.`,
          { cause: error }
        );
      }
    }
 
    await newSubLevel.close();
    await oldSubLevel.close();
 
    return count;
  } finally {
    try {
      await level.close();
    } catch {
      // Don't mask the original error - just ignore the close failure
    }
  }
};
 
/**
 * Migrates existing unscoped private state and signing key data to account-scoped sublevels.
 *
 * This function copies data from the legacy unscoped locations to the new account-scoped
 * locations. The original data is preserved (not deleted) to allow for safe rollback if needed.
 * To remove old data after successful migration, manually clear the unscoped sublevels.
 *
 * Note: Running this function multiple times is safe but will re-copy all data, overwriting
 * any changes made in the scoped location since the last migration.
 */
export const migrateToAccountScoped = async (
  config: Partial<LevelPrivateStateProviderConfig> & Pick<LevelPrivateStateProviderConfig, 'accountId'>
): Promise<MigrationResult> => {
  const fullConfig = { ...DEFAULT_CONFIG, ...config };
 
  if (!config.accountId || config.accountId.trim().length === 0) {
    throw new Error('accountId is required for migration');
  }
 
  const scopedPrivateStateLevelName = getScopedLevelName(
    fullConfig.privateStateStoreName,
    config.accountId
  );
  const scopedSigningKeyLevelName = getScopedLevelName(
    fullConfig.signingKeyStoreName,
    config.accountId
  );
 
  let privateStatesMigrated: number;
 
  try {
    privateStatesMigrated = await migrateSublevel(
      fullConfig.midnightDbName,
      fullConfig.privateStateStoreName,
      scopedPrivateStateLevelName
    );
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    throw new Error(
      `Migration failed during private states copy: ${errorMessage}. ` +
      `No data has been migrated. Source data is unchanged.`,
      { cause: error }
    );
  }
 
  let signingKeysMigrated: number;
 
  try {
    signingKeysMigrated = await migrateSublevel(
      fullConfig.midnightDbName,
      fullConfig.signingKeyStoreName,
      scopedSigningKeyLevelName
    );
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    throw new Error(
      `Migration failed during signing keys copy: ${errorMessage}. ` +
      `WARNING: ${privateStatesMigrated} private states were already migrated to scoped location. ` +
      `Signing keys remain at original location. Manual intervention may be required.`,
      { cause: error }
    );
  }
 
  return { privateStatesMigrated, signingKeysMigrated };
};