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

Encrypt master key with a password before storing #28

Merged
merged 4 commits into from
Feb 10, 2024
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- name: Setup node
uses: actions/setup-node@v3
with:
node-version: 18.2.x
node-version: 20.9.x
cache: npm
- name: Cache node modules
id: cache-node-modules
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
- name: Setup node
uses: actions/setup-node@v3
with:
node-version: 18.2.x
node-version: 20.9.x
cache: npm
- name: Cache node modules
id: cache-node-modules
Expand Down
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v20.9.0
22 changes: 16 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"tiny-secp256k1": "^2.2.3"
},
"devDependencies": {
"@types/bip38": "^3.1.2",
"@types/create-hash": "^1.2.3",
"@types/jest": "^29.5.3",
"@types/node": "^20.5.0",
Expand Down
11 changes: 8 additions & 3 deletions src/wallet/db/db.interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Buffer } from 'buffer';
import { Coin } from '../coin.ts';

export type DbInterface = {
Expand All @@ -7,8 +6,14 @@ export type DbInterface = {
getStatus(): string;
getVersion(): Promise<number>;
setVersion(version: number): Promise<void>;
getMasterKey(): Promise<{ privateKey: Buffer; chaincode: Buffer }>;
setMasterKey(privateKey: Buffer, chaincode: Buffer): Promise<void>;
getMasterKey(): Promise<{
encryptedPrivateKey: string;
encryptedChainCode: string;
}>;
setMasterKey(
encryptedPrivateKey: string,
encryptedChainCode: string,
): Promise<void>;
saveAddress(address: string, path: string): Promise<void>;
getAddress(address: string): Promise<string>;
hasAddress(address: string): Promise<boolean>;
Expand Down
25 changes: 10 additions & 15 deletions src/wallet/db/level/db.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Level } from 'level';
import { wdb } from './layout.ts';
import { DbInterface } from '../db.interface.ts';
import { Buffer } from 'buffer';
import { Coin } from '../../coin.ts';

export type LevelDBConfigOptions = {
Expand Down Expand Up @@ -39,24 +38,20 @@ export class WalletDB implements DbInterface {
await this.db.put(wdb.V, version.toString());
}

public async getMasterKey(): Promise<{
privateKey: Buffer;
chaincode: Buffer;
}> {
public async getMasterKey() {
theanmolsharma marked this conversation as resolved.
Show resolved Hide resolved
const masterKey = await this.db.get(wdb.M);
const privateKey = Buffer.from(masterKey.slice(0, 64), 'hex');
const chaincode = Buffer.from(masterKey.slice(64), 'hex');
const [encryptedPrivateKey, encryptedChainCode] = masterKey.split(':');

return { privateKey, chaincode };
return { encryptedPrivateKey, encryptedChainCode };
}

public async setMasterKey(
privateKey: Buffer,
chaincode: Buffer,
encryptedPrivateKey: string,
encryptedChainCode: string,
): Promise<void> {
await this.db.put(
wdb.M,
Buffer.concat([privateKey, chaincode]).toString('hex'),
`${encryptedPrivateKey}:${encryptedChainCode}`,
);
}

Expand All @@ -73,19 +68,19 @@ export class WalletDB implements DbInterface {
}

async getReceiveDepth(): Promise<number> {
return parseInt(await this.db.sublevel(wdb.A).get('receiveDepth'));
return parseInt(await this.db.sublevel(wdb.D).get('receiveDepth'));
}

async setReceiveDepth(depth: number): Promise<void> {
await this.db.sublevel(wdb.A).put('receiveDepth', depth.toString());
await this.db.sublevel(wdb.D).put('receiveDepth', depth.toString());
}

async getChangeDepth(): Promise<number> {
return parseInt(await this.db.sublevel(wdb.A).get('changeDepth'));
return parseInt(await this.db.sublevel(wdb.D).get('changeDepth'));
}

async setChangeDepth(depth: number): Promise<void> {
await this.db.sublevel(wdb.A).put('changeDepth', depth.toString());
await this.db.sublevel(wdb.D).put('changeDepth', depth.toString());
}

async getAllAddresses(): Promise<string[]> {
Expand Down
1 change: 1 addition & 0 deletions src/wallet/db/level/layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export const wdb = {
V: 'V', // Version
M: 'M', // Master key
A: 'A', // Address
D: 'D', // Address depth
C: 'C', // Coins
SP: 'SP', // Silent payment address
};
47 changes: 40 additions & 7 deletions src/wallet/wallet.ts
theanmolsharma marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Coin } from './coin.ts';
import { ECPairFactory } from 'ecpair';
import { createOutputs, encodeSilentPaymentAddress } from '../core';
import { toXOnly } from 'bitcoinjs-lib/src/psbt/bip371';
import { encrypt, decrypt } from 'bip38';

initEccLib(ecc);
const ECPair = ECPairFactory(ecc);
Expand All @@ -21,6 +22,8 @@ export type WalletConfigOptions = {
networkClient: NetworkInterface;
};

const DEFAULT_ENCRYPTION_PASSWORD = '12345678';

export class Wallet {
private readonly db: DbInterface;
private readonly network: NetworkInterface;
Expand All @@ -33,19 +36,29 @@ export class Wallet {
this.network = config.networkClient;
}

async init(mnemonic?: string) {
async init(params?: { mnemonic?: string; password?: string }) {
const { mnemonic, password } = params;
await this.db.open();

if (mnemonic) {
const seed = mnemonicToSeedSync(mnemonic).toString('hex');
this.masterKey = bip32.fromSeed(Buffer.from(seed, 'hex'));
await this.db.setMasterKey(
this.masterKey.privateKey,
this.masterKey.chainCode,
);
this.setPassword(password ?? DEFAULT_ENCRYPTION_PASSWORD);
} else {
const { privateKey, chaincode } = await this.db.getMasterKey();
this.masterKey = bip32.fromPrivateKey(privateKey, chaincode);
const { encryptedPrivateKey, encryptedChainCode } =
await this.db.getMasterKey();
const { privateKey: decryptedPrivateKey } = decrypt(
encryptedPrivateKey,
password ?? DEFAULT_ENCRYPTION_PASSWORD,
);
const { privateKey: decryptedChainCode } = decrypt(
encryptedChainCode,
password ?? DEFAULT_ENCRYPTION_PASSWORD,
);
this.masterKey = bip32.fromPrivateKey(
decryptedPrivateKey,
decryptedChainCode,
);
}
}

Expand All @@ -56,6 +69,26 @@ export class Wallet {
await this.db.close();
}

async setPassword(newPassword: string) {
if (!this.masterKey) {
throw new Error(
'Wallet not initialized. Please call wallet.init()',
);
} else {
const encryptedPrivateKey = encrypt(
this.masterKey.privateKey,
false,
newPassword,
);
const encryptedChainCode = encrypt(
this.masterKey.chainCode,
false,
newPassword,
);
await this.db.setMasterKey(encryptedPrivateKey, encryptedChainCode);
}
}

private async deriveAddress(path: string): Promise<string> {
const child = this.masterKey.derivePath(path);
const { address } = payments.p2wpkh({
Expand Down
10 changes: 10 additions & 0 deletions test/wallet-db.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ describe('Wallet DB', () => {
expect(await walletDB.getVersion()).toBe(1);
});

it('should set and retrieve encryptedPrivateKey and encryptedChainCode', async () => {
const samplePrivateKey = 'samplePrivateKey';
const sampleChainCode = 'sampleChainCode';
await walletDB.setMasterKey(samplePrivateKey, sampleChainCode);
const { encryptedPrivateKey, encryptedChainCode } =
await walletDB.getMasterKey();
expect(encryptedPrivateKey).toStrictEqual(samplePrivateKey);
expect(encryptedChainCode).toStrictEqual(sampleChainCode);
});

afterAll(async () => {
await walletDB.close();
fs.rmSync('./test/wallet-db', { recursive: true, force: true });
Expand Down
14 changes: 11 additions & 3 deletions test/wallet.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,17 @@ describe('Wallet', () => {
});

it('should initialise the wallet', async () => {
await wallet.init(
'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about',
);
await wallet.init({
mnemonic:
'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about',
});
});

it('should set a new password, close and reopen the wallet with the same password', async () => {
const password = 'notSoSecretPassword';
await wallet.setPassword(password);
await wallet.close();
await wallet.init({ password });
});

it('should derive first receive address', async () => {
Expand Down
Loading