Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: database per wallet exporter #2

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
exporterTenant.json
sharedTenantExportedWallet.json
DB_per_wallet_exportedWallet.json
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ pnpm cli --strategy export \
--tenant-id <tenant-id>
```

### Export Database Per Wallet

Export a tenant wallet from DB per wallet to a JSON file:
```bash
pnpm cli --strategy export \
--wallet-id <wallet-id> \
--wallet-key <wallet-key> \
--storage-type <sqlite|postgres> \
[--postgres-host <host>] \
[--postgres-username <username>] \
[--postgres-password <password>] \
--tenant-id <tenant-id>
```

### Convert Single Wallet to Multi-Wallet

Convert profiles in a sub-wallet to individual wallets:
Expand Down
145 changes: 145 additions & 0 deletions src/db-pw-exporter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { KeyDerivationMethod, WalletConfig, FileSystem } from "@credo-ts/core"
import { Store } from "@hyperledger/aries-askar-nodejs"
import {
keyDerivationMethodToStoreKeyMethod,
uriFromWalletConfig,
} from "@credo-ts/askar/build/utils"
import { writeFileSync } from "fs"
import { join } from "path"

interface WalletRecord {
name: string;
value: string;
tags: Record<string, string>;
category: string;
}

/**
* Class responsible for exporting wallet data.
*/
class DBPerWalletExporter {
private walletConfig: WalletConfig
private fileSystem: FileSystem
private tenantId: string

/**
* Constructor for the Exporter class.
* @param walletConfig - Configuration for the wallet.
* @param fileSystem - File system instance.
* @param tenantId - Tenant ID for the profile.
*/
constructor({
walletConfig,
fileSystem,
tenantId,
}: {
walletConfig: WalletConfig
fileSystem: FileSystem
tenantId: string
}) {
this.walletConfig = walletConfig
this.fileSystem = fileSystem
this.tenantId = tenantId
}

/**
* Export the wallet data to a JSON file.
*/
public async exportDBPerWalletData(): Promise<void> {
try {
console.log("🚀 ~ Exporter ~ exportWalletData ~ this.walletConfig:", this.walletConfig);
const askarWalletConfig = await this.getAskarWalletConfig(this.walletConfig);
const store = await Store.open({
uri: askarWalletConfig.walletURI.uri,
keyMethod: askarWalletConfig.keyMethod,
passKey: askarWalletConfig.passKey,
});
console.log("🚀 Store opened:", store);
await this.processStoreData(store, askarWalletConfig);
} catch (error) {
console.error("🚀 ~ Exporter ~ exportWalletData ~ error:", error);
}
}

private async processStoreData(store: any, askarWalletConfig): Promise<void> {
const data = await this.fetchDataFromStore(store);
const tenantRecord = this.findTenantRecord(data, this.tenantId);

if (!tenantRecord) {
throw new Error('Tenant not found in the base wallet');
}

const { walletId, walletKey } = this.extractWalletConfig(tenantRecord);
console.log(`Wallet ID: ${walletId}`);
console.log(`Wallet Key: ${walletKey}`);

const baseUri = askarWalletConfig.walletURI.uri.split('/').slice(0, -1).join('/');
const tenantUri = `${baseUri}/${walletId}`;

const tenantStore = await Store.open({
uri: tenantUri,
keyMethod: keyDerivationMethodToStoreKeyMethod(KeyDerivationMethod.Raw),
passKey: walletKey,
});

const tenantData = await this.scanStore(tenantStore);
this.processTenantData(tenantData);
}

private async fetchDataFromStore(store: any): Promise<WalletRecord[]> {
try {
const scan = store.scan({});
const records: WalletRecord[] = await scan.fetchAll();
return records;
} catch (error) {
console.error("Error fetching data from store:", error);
throw new Error("Failed to fetch data from store");
}
}

private findTenantRecord(data: WalletRecord[], tenantId: string): WalletRecord | undefined {
return data.find(record => record.category === 'TenantRecord' && record.name === tenantId);
}

private extractWalletConfig(record: WalletRecord): { walletId: string, walletKey: string } {
const value = JSON.parse(record.value);
return {
walletId: value.config.walletConfig.id,
walletKey: value.config.walletConfig.key,
};
}

private async scanStore(store: any): Promise<WalletRecord[]> {
const scan = store.scan({});
return await scan.fetchAll();
}

private processTenantData(data: WalletRecord[]): void {
const filteredData: Record<string, WalletRecord[]> = {};

for (const entry of data) {
if (!filteredData[entry.category]) {
filteredData[entry.category] = [];
}
filteredData[entry.category].push(entry);
}

const outputPath = join(__dirname, "../DB_per_wallet_exportedWallet.json")
writeFileSync(outputPath, JSON.stringify(filteredData, null, 2))
console.log(`Filtered data written to ${outputPath}`)
}
/**
* Get the Askar wallet configuration.
* @param walletConfig - The wallet configuration.
* @returns The Askar wallet configuration.
*/
private async getAskarWalletConfig(walletConfig: WalletConfig) {
return {
walletURI: uriFromWalletConfig(walletConfig, this.fileSystem.dataPath),
keyMethod: keyDerivationMethodToStoreKeyMethod(walletConfig.keyDerivationMethod ?? KeyDerivationMethod.Argon2IMod),
passKey: walletConfig.key,
}
}
}

export default DBPerWalletExporter;
2 changes: 1 addition & 1 deletion src/exporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export class Exporter {
}

// Write filtered data to a JSON file
const outputPath = join(__dirname, "../exportedTenantWallet.json")
const outputPath = join(__dirname, "../sharedTenantExportedWallet.json")
writeFileSync(outputPath, JSON.stringify(filteredData, null, 2))
console.log(`Filtered data written to ${outputPath}`)
}
Expand Down
38 changes: 32 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Command } from "commander"
import { MultiWalletConverter } from "./multiWalletConverter"
import { AskarWalletSqliteStorageConfig } from "@credo-ts/askar/build/wallet"
import { Exporter } from "./exporter"
import DBPerWalletExporter from "./db-pw-exporter"

const program = new Command("askar-tools-javascript")

Expand All @@ -13,7 +14,7 @@ program
"--strategy <strategy>",
"Specify strategy to be used. Choose from 'mt-convert-to-mw', or 'import-tenant'.",
(value) => {
if (!["mt-convert-to-mw", "import-tenant","export"].includes(value)) {
if (!["mt-convert-to-mw", "import-tenant","export","db-pw-export"].includes(value)) {
throw new Error(
"Invalid strategy. Choose from 'mt-convert-to-mw', or 'import-tenant'."
)
Expand Down Expand Up @@ -57,13 +58,10 @@ const main = async () => {

let method
let exporterMethod
let storageType:| AskarWalletPostgresStorageConfig| AskarWalletSqliteStorageConfig

switch (options.strategy) {
case "export":
let storageType:
| AskarWalletPostgresStorageConfig
| AskarWalletSqliteStorageConfig

if (options.storageType === "postgres") {
storageType = {
type: "postgres",
Expand Down Expand Up @@ -92,7 +90,35 @@ const main = async () => {
})
await exporterMethod.export()
break

case "db-pw-export":
if (options.storageType === "postgres") {
storageType = {
type: "postgres",
config: {
host: options.postgresHost,
},
credentials: {
account: options.postgresUsername,
password: options.postgresPassword,
},
}
} else {
storageType = {
type: "sqlite",
}
}

exporterMethod = new DBPerWalletExporter({
fileSystem: new agentDependencies.FileSystem(),
walletConfig: {
id: options.walletId,
key: options.walletKey,
storage: storageType,
},
tenantId: options.tenantId,
})
await exporterMethod.exportDBPerWalletData()
break
case "mt-convert-to-mw":
let storage:
| AskarWalletPostgresStorageConfig
Expand Down