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: keystore decoding #703

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions packages/hdwallet-native-vault/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { registerKeystoreTransformers } from "./keystore";
import { createMnemonic, crypto, entropyToMnemonic, GENERATE_MNEMONIC } from "./util";
import { Vault } from "./vault";

export type { ISealableVaultFactory, IVault, IVaultFactory } from "./types";
export { GENERATE_MNEMONIC } from "./util";
export { Vault } from "./vault";
export { type XChainKeystore, decryptFromKeystore } from "./keystore";

Vault.registerValueTransformer("#mnemonic", async (x: unknown) => {
if (x !== GENERATE_MNEMONIC) return x;
Expand All @@ -16,4 +18,6 @@ Vault.registerValueWrapper("#mnemonic", async (x: unknown, addRevoker: (revoke:
addRevoker(() => out.revoke?.());
return out;
});

registerKeystoreTransformers();
Vault.extensionRegistrationComplete();
115 changes: 115 additions & 0 deletions packages/hdwallet-native-vault/src/keystore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { blake2bFinal, blake2bInit, blake2bUpdate } from "blakejs";

import { crypto, encoder } from "./util";
import { Vault } from "./vault";

// https://github.com/thorswap/SwapKit/blob/349a9212d8357cc35a8bab771728bbc8d6900ebc/packages/wallets/keystore/src/helpers.ts#L6
export interface XChainKeystore {
crypto: {
cipher: string;
ciphertext: string;
cipherparams: {
iv: string;
};
kdf: string;
kdfparams: {
prf: string;
dklen: number;
salt: string;
c: number;
};
mac: string;
};
version: number;
meta: string;
}

// https://github.com/thorswap/SwapKit/blob/349a9212d8357cc35a8bab771728bbc8d6900ebc/packages/wallets/keystore/src/helpers.ts#L29-L42
function blake256(data: Uint8Array): string {
const context = blake2bInit(32);
blake2bUpdate(context, data);
return Buffer.from(blake2bFinal(context)).toString("hex");
}

// https://github.com/thorswap/SwapKit/blob/349a9212d8357cc35a8bab771728bbc8d6900ebc/packages/wallets/keystore/src/helpers.ts#L102
export async function decryptFromKeystore(keystore: XChainKeystore, password: string): Promise<string> {
if (keystore.version !== 1 || keystore.meta !== "xchain-keystore") {
throw new Error("Invalid keystore format");
}

const { kdfparams } = keystore.crypto;

// Derive key using PBKDF2 similar to SwapKit's `pbkdf2Async` call
const passwordKey = await (
await crypto
).subtle.importKey("raw", encoder.encode(password), "PBKDF2", false, ["deriveBits"]);

const derivedKey = new Uint8Array(
await (
await crypto
).subtle.deriveBits(
{
name: "PBKDF2",
salt: Buffer.from(kdfparams.salt, "hex"),
iterations: kdfparams.c,
hash: "SHA-256",
},
passwordKey,
kdfparams.dklen * 8
)
);

const ciphertext = Buffer.from(keystore.crypto.ciphertext, "hex");
const mac = blake256(Buffer.concat([Buffer.from(derivedKey.subarray(16, 32)), ciphertext]));

if (mac !== keystore.crypto.mac) {
throw new Error("Invalid password");
}

const aesKey = await (
await crypto
).subtle.importKey(
"raw",
derivedKey.subarray(0, 16),
{
name: "AES-CTR",
length: 128,
},
false,
["decrypt"]
);

const iv = Buffer.from(keystore.crypto.cipherparams.iv, "hex");
const counter = new Uint8Array(16);
counter.set(iv);

const decrypted = await (
await crypto
).subtle.decrypt(
{
name: "AES-CTR",
counter,
length: 128,
},
aesKey,
ciphertext
);

return new TextDecoder().decode(decrypted);
}

export const registerKeystoreTransformers = () => {
Vault.registerValueTransformer("#keystore", async (value: unknown) => {
if (!value || typeof value !== "string") return value;

try {
const keystore = JSON.parse(value) as XChainKeystore;
if (keystore.version !== 1 || keystore.meta !== "xchain-keystore") {
throw new Error("Invalid keystore format");
}
return keystore;
} catch {
return value;
}
});
};
8 changes: 8 additions & 0 deletions packages/hdwallet-native-vault/src/vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as core from "@shapeshiftoss/hdwallet-core";
import * as jose from "jose";
import * as ta from "type-assertions";

import { decryptFromKeystore } from "./keystore";
import { MapVault } from "./mapVault";
import { RawVault } from "./rawVault";
import { ISealableVaultFactory, IVault, VaultPrepareParams } from "./types";
Expand Down Expand Up @@ -179,6 +180,13 @@ export class Vault extends MapVault implements IVault {
return this;
}

async loadFromKeystore(stringifiedKeystore: string, password: string) {
const keystore = JSON.parse(stringifiedKeystore);
const mnemonic = await decryptFromKeystore(keystore, password);
this.set("#mnemonic", mnemonic);
return this;
}

async save() {
const unwrappedRevoker = new (Revocable(class {}))();
const unwrapped = this.#unwrap((x) => unwrappedRevoker.addRevoker(x));
Expand Down