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 4 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
88 changes: 84 additions & 4 deletions src/exporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from "@credo-ts/askar/build/utils"
import { writeFileSync } from "fs"
import { join } from "path"
import { databaseScheme } from "."

/**
* Class responsible for exporting wallet data.
Expand All @@ -14,6 +15,8 @@ export class Exporter {
private walletConfig: WalletConfig
private fileSystem: FileSystem
private profileId: string
private tenantId: string
private databaseScheme: string

/**
* Constructor for the Exporter class.
Expand All @@ -25,20 +28,24 @@ export class Exporter {
walletConfig,
fileSystem,
tenantId,
databaseScheme
}: {
walletConfig: WalletConfig
fileSystem: FileSystem
tenantId: string
databaseScheme: string
}) {
this.walletConfig = walletConfig
this.fileSystem = fileSystem
this.profileId = `tenant-${tenantId}`
this.tenantId = tenantId
this.databaseScheme = databaseScheme
}

/**
* Export the wallet data to a JSON file.
*/
public async export(): Promise<void> {
public async export(strategy:string): Promise<void> {
try {
const askarWalletConfig = await this.getAskarWalletConfig(this.walletConfig)
const store = await Store.open({
Expand All @@ -47,12 +54,17 @@ export class Exporter {
passKey: askarWalletConfig.passKey,
})
console.log("🚀 Store opened:", store)
await this.getDecodedItemsAndTags(store)
if (this.databaseScheme === databaseScheme.PROFILE_PER_WALLET) {
await this.getDecodedItemsAndTags(store);
} else if (this.databaseScheme === databaseScheme.DATABASE_PER_WALLET) {
await this.processStoreData(store, askarWalletConfig);
} else {
console.warn(`Unknown strategy`);
}
} catch (error) {
console.error("🚀 ~ Exporter ~ export ~ error:", error)
}
}

/**
* Get decoded items and tags from the store and write them to a JSON file.
* @param store - The store instance.
Expand All @@ -78,11 +90,79 @@ 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}`)
}

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.uri.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){
try {
const scan = store.scan({});
const records = 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, tenantId: string) {
return data.find(record => record.category === 'TenantRecord' && record.name === tenantId);
}

private extractWalletConfig(record): { 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) {
const scan = store.scan({});
return await scan.fetchAll();
}

private processTenantData(data): void {
const filteredData = {};

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.
Expand Down
27 changes: 21 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@ import { Exporter } from "./exporter"

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

export enum databaseScheme {
PROFILE_PER_WALLET = 'ProfilePerWallet',
DATABASE_PER_WALLET = 'DatabasePerWallet'
}

program
.requiredOption(
"--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"].includes(value)) {
throw new Error(
"Invalid strategy. Choose from 'mt-convert-to-mw', or 'import-tenant'."
)
Expand Down Expand Up @@ -49,6 +54,19 @@ program
"Specify password for postgres storage."
)
.option("--tenant-id <id>", "Specify tenant-id to be migrated.")
.option(
"--database-scheme <scheme>",
"Specify database scheme to be migrated. Choose from 'DatabasePerWallet' or 'ProfilePerWallet'.",
(value) => {
if (!["DatabasePerWallet", "ProfilePerWallet"].includes(value)) {
throw new Error(
"Invalid database scheme. Choose from 'DatabasePerWallet' or 'ProfilePerWallet'."
)
}
return value
},
"ProfilePerWallet"
)

const main = async () => {
const options = program.opts()
Expand All @@ -57,13 +75,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 All @@ -89,10 +104,10 @@ const main = async () => {
storage: storageType,
},
tenantId: options.tenantId,
databaseScheme: options.databaseScheme,
})
await exporterMethod.export()
break

case "mt-convert-to-mw":
let storage:
| AskarWalletPostgresStorageConfig
Expand Down