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 | 1x 1x 1x 1x 1x 155x 11x 24x 1x 150x 150x 150x 150x 150x 150x 150x 150x 1x 1x 72x 72x 72x 72x 72x 5x 67x 67x 67x 5x 5x 5x 5x 1x 43x 43x 43x 43x 41x 9x 32x 32x 32x 32x 32x 2x 2x 1x 42x 42x 1x 41x 1x 40x 2x 42x 30x 1x 1x 21x 21x 21x 21x 21x 1x 13x 2x 2x 8x 8x 8x 8x 8x 2x | /*
* This file is part of midnight-js.
* Copyright (C) 2025 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 type { PrivateStateId, PrivateStateProvider, WalletProvider } from '@midnight-ntwrk/midnight-js-types';
import { type AbstractSublevel } from 'abstract-level';
import { Buffer } from 'buffer';
import { Level } from 'level';
import _ from 'lodash';
import * as superjson from 'superjson';
import { 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';
/**
* Optional properties for the indexedDB based private state provider configuration.
*/
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;
/**
* Wallet provider used to get the encryption public key for password derivation.
* If privateStoragePasswordProvider is not provided, the wallet's encryption public key
* will be used as the password.
*/
readonly walletProvider?: WalletProvider;
/**
* Provider function that returns the password used for encrypting private state.
* The password must be at least 16 characters long.
*
* If not provided, defaults to using walletProvider.getEncryptionPublicKey().
*
* @example
* ```typescript
* // Using default (wallet's encryption public key)
* { walletProvider: wallet }
*
* // Using custom password provider
* {
* walletProvider: wallet,
* privateStoragePasswordProvider: async () => await getUserPassword()
* }
* ```
*/
readonly privateStoragePasswordProvider?: PrivateStoragePasswordProvider;
}
/**
* 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 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 getOrCreateEncryption = async (
dbName: string,
levelName: string,
passwordProvider: PrivateStoragePasswordProvider
): Promise<StorageEncryption> => {
const password = await getPasswordFromProvider(passwordProvider);
return withSubLevel<string, string, StorageEncryption>(dbName, levelName, async (subLevel) => {
try {
const metadataJson = await subLevel.get(METADATA_KEY);
if (!metadataJson) {
throw new Error('Metadata not found');
}
const metadata = JSON.parse(metadataJson);
const salt = Buffer.from(metadata.salt, 'hex');
return new StorageEncryption(password, salt);
} catch {
const encryption = new StorageEncryption(password);
const metadata = {
salt: encryption.getSalt().toString('hex'),
version: 1
};
await subLevel.put(METADATA_KEY, JSON.stringify(metadata));
return encryption;
}
});
};
const subLevelMaybeGet = async <K, V>(
dbName: string,
levelName: string,
key: K,
passwordProvider: PrivateStoragePasswordProvider
): Promise<V | null> => {
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)) {
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;
}
});
};
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Constructs an instance of {@link PrivateStateProvider} based on {@link Level} database.
*
* @param config Database configuration options.
*/
export const levelPrivateStateProvider = <PSI extends PrivateStateId, PS = any>(
config: Partial<LevelPrivateStateProviderConfig>
): PrivateStateProvider<PSI, PS> => {
const fullConfig = _.defaults(config, DEFAULT_CONFIG);
if (config.privateStoragePasswordProvider && config.walletProvider) {
throw new Error(
'Cannot provide both privateStoragePasswordProvider and walletProvider.\n' +
'Provide only one: walletProvider for default behavior, or privateStoragePasswordProvider for custom password.'
);
}
if (!config.privateStoragePasswordProvider && !config.walletProvider) {
throw new Error(
'Either privateStoragePasswordProvider or walletProvider must be provided.\n' +
'Provide walletProvider to use wallet encryption key, or privateStoragePasswordProvider for custom password.'
);
}
const passwordProvider: PrivateStoragePasswordProvider = config.privateStoragePasswordProvider ||
(() => config.walletProvider!.getEncryptionPublicKey());
return {
get(privateStateId: PSI): Promise<PS | null> {
return subLevelMaybeGet<PSI, PS>(
fullConfig.midnightDbName,
fullConfig.privateStateStoreName,
privateStateId,
passwordProvider
);
},
remove(privateStateId: PSI): Promise<void> {
return withSubLevel<PSI, string, void>(fullConfig.midnightDbName, fullConfig.privateStateStoreName, (subLevel) =>
subLevel.del(privateStateId)
);
},
async set(privateStateId: PSI, state: PS): Promise<void> {
const encryption = await getOrCreateEncryption(
fullConfig.midnightDbName,
fullConfig.privateStateStoreName,
passwordProvider
);
const serialized = superjson.stringify(state);
const encrypted = encryption.encrypt(serialized);
return withSubLevel<PSI, string, void>(fullConfig.midnightDbName, fullConfig.privateStateStoreName, (subLevel) =>
subLevel.put(privateStateId, encrypted)
);
},
clear(): Promise<void> {
return withSubLevel(fullConfig.midnightDbName, fullConfig.privateStateStoreName, (subLevel) => subLevel.clear());
},
getSigningKey(address: ContractAddress): Promise<SigningKey | null> {
return subLevelMaybeGet<ContractAddress, SigningKey>(
fullConfig.midnightDbName,
fullConfig.signingKeyStoreName,
address,
passwordProvider
);
},
removeSigningKey(address: ContractAddress): Promise<void> {
return withSubLevel<ContractAddress, string, void>(
fullConfig.midnightDbName,
fullConfig.signingKeyStoreName,
(subLevel) => subLevel.del(address)
);
},
async setSigningKey(address: ContractAddress, signingKey: SigningKey): Promise<void> {
const encryption = await getOrCreateEncryption(
fullConfig.midnightDbName,
fullConfig.signingKeyStoreName,
passwordProvider
);
const serialized = superjson.stringify(signingKey);
const encrypted = encryption.encrypt(serialized);
return withSubLevel<ContractAddress, string, void>(
fullConfig.midnightDbName,
fullConfig.signingKeyStoreName,
(subLevel) => subLevel.put(address, encrypted)
);
},
clearSigningKeys(): Promise<void> {
return withSubLevel(fullConfig.midnightDbName, fullConfig.signingKeyStoreName, (subLevel) => subLevel.clear());
}
};
};
|