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: add qr keyring package #60

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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: 2 additions & 0 deletions packages/keyring-eth-qr/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Changelog

15 changes: 15 additions & 0 deletions packages/keyring-eth-qr/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
ISC License

Copyright (c) 2020 MetaMask

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1 change: 1 addition & 0 deletions packages/keyring-eth-qr/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# QR Keyring
29 changes: 29 additions & 0 deletions packages/keyring-eth-qr/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/

const merge = require('deepmerge');
const path = require('path');

const baseConfig = require('../../jest.config.packages');

const displayName = path.basename(__dirname);

module.exports = merge(baseConfig, {
// The display name when running multiple projects
displayName,

// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: ['./src/tests'],

// An object that configures minimum threshold enforcement for coverage results
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
});
76 changes: 76 additions & 0 deletions packages/keyring-eth-qr/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"name": "@metamask/eth-qr-keyring",
"version": "1.0.0",
"description": "A simple standard interface for a series of Ethereum private keys.",
"keywords": [
"ethereum",
"keyring",
"qr",
"metamask"
],
"homepage": "https://github.com/MetaMask/accounts/packages/keyring-eth-qr#readme",
"bugs": {
"url": "https://github.com/MetaMask/accounts/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/MetaMask/accounts.git"
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist/"
],
"scripts": {
"build": "tsc --build tsconfig.build.json",
"build:clean": "rimraf dist && yarn build",
"build:docs": "typedoc",
"build:force": "tsc --build tsconfig.build.json --force",
"changelog:update": "../../scripts/update-changelog.sh @metamask/eth-simple-keyring",
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/eth-simple-keyring",
"publish:preview": "yarn npm publish --tag preview",
"sample": "ts-node src/sample.ts",
"test": "jest",
"test:clean": "jest --clearCache",
"test:verbose": "jest --verbose",
"test:watch": "jest --watch"
},
"dependencies": {
"@ethereumjs/util": "^9.1.0",
"@keystonehq/bc-ur-registry-eth": "^0.21.0",
"@keystonehq/ur-decoder": "^0.12.2",
"@metamask/utils": "^9.2.1",
"@ngraveio/bc-ur": "^1.1.13",
"hdkey": "^2.1.0"
},
"devDependencies": {
"@lavamoat/allow-scripts": "^3.2.1",
"@metamask/auto-changelog": "^3.4.4",
"@types/hdkey": "^2.0.1",
"@types/jest": "^29.5.12",
"@types/node": "^20.12.12",
"deepmerge": "^4.2.2",
"depcheck": "^1.4.7",
"jest": "^29.5.0",
"ts-jest": "^29.0.5",
"ts-node": "^10.9.2",
"typedoc": "^0.25.13",
"typescript": "~4.8.4"
},
"engines": {
"node": "^18.18 || >=20"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
},
"lavamoat": {
"allowScripts": {
"keccak": true,
"secp256k1": true,
"@lavamoat/preinstall-always-fail": false,
"ethereumjs-tx>ethereumjs-util>ethereum-cryptography>keccak": false,
"ethereumjs-tx>ethereumjs-util>ethereum-cryptography>secp256k1": false
}
}
}
91 changes: 91 additions & 0 deletions packages/keyring-eth-qr/src/account-deriver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { pubToAddress } from '@ethereumjs/util';
import {
CryptoAccount,
type CryptoHDKey,
type CryptoOutput,
} from '@keystonehq/bc-ur-registry-eth';
import { add0x, getChecksumAddress, type Hex } from '@metamask/utils';
import HDKey from 'hdkey';

export type RootAccount = { fingerprint: Hex } & (
| {
type: 'hd';
hdPath: string;
childrenPath: string;
bip32xPub: string;
}
| {
type: 'account';
addressPaths: Record<Hex, string>;
}
);

export class AccountDeriver {
#root?: RootAccount;

init(source: CryptoAccount | CryptoHDKey) {
const fingerprint = this.#getFingerprintFromSource(source);
if (source instanceof CryptoAccount) {
this.#root = {
fingerprint,
type: 'account',
addressPaths: this.#getPathsFromCryptoOutputDescriptors(
source.getOutputDescriptors(),
),
};
} else {
this.#root = {
fingerprint,
type: 'hd',
hdPath: `m/${source.getOrigin().getPath()}`,
childrenPath: source.getChildren().getPath(),
bip32xPub: source.getBip32Key(),
};
}
}

deriveIndex(index: number): Hex {
if (!this.#root) {
throw new Error('AccountDeriver not initialized');
}

if (this.#root.type === 'account') {
const address = Object.keys(this.#root.addressPaths)[index];
if (!address) {
throw new Error(`Address not found for index ${index}`);
}
return add0x(address);
} else {
const hdKey = HDKey.fromExtendedKey(this.#root.bip32xPub);
hdKey.derive(`m/${index}`);
const address = getChecksumAddress(
add0x(Buffer.from(pubToAddress(hdKey.publicKey, true)).toString('hex')),
);
return add0x(address);
}
}

#getFingerprintFromSource(source: CryptoAccount | CryptoHDKey): Hex {
return source instanceof CryptoAccount
? add0x(source.getMasterFingerprint().toString('hex'))
: add0x(source.getOrigin().getSourceFingerprint().toString('hex'));
}

#getPathsFromCryptoOutputDescriptors(
descriptors: CryptoOutput[],
): Record<Hex, string> {
return descriptors.reduce((paths: Record<Hex, string>, current) => {
const hdKey = current.getHDKey();
if (hdKey) {
const path = `M/${hdKey.getOrigin().getPath()}`;
const address = getChecksumAddress(
add0x(
Buffer.from(pubToAddress(hdKey.getKey(), true)).toString('hex'),
),
);
paths[address] = path;
}
return paths;
}, {});
}
}
1 change: 1 addition & 0 deletions packages/keyring-eth-qr/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './qr-keyring';
76 changes: 76 additions & 0 deletions packages/keyring-eth-qr/src/qr-keyring.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { CryptoAccount, CryptoHDKey } from '@keystonehq/bc-ur-registry-eth';
import { URRegistryDecoder } from '@keystonehq/ur-decoder';
import type { Hex, Keyring } from '@metamask/utils';
import { UR } from '@ngraveio/bc-ur';
import { AccountDeriver } from './account-deriver';

export const QR_KEYRING_TYPE = 'QrKeyring' as const;

export const SUPPORTED_UR_TYPE = {
CRYPTO_HDKEY: 'crypto-hdkey',
CRYPTO_ACCOUNT: 'crypto-account',
ETH_SIGNATURE: 'eth-signature',
};

/**
* The state of the QrKeyring
*
* @property accounts - The accounts in the QrKeyring
*/
export type QrKeyringState = {
accounts: Record<number, Hex>;
cbor?: Hex;
};

export class QrKeyring implements Keyring<QrKeyringState> {
type = QR_KEYRING_TYPE;

#accounts: Record<number, Hex> = {};

#deriver: AccountDeriver = new AccountDeriver();

async serialize(): Promise<QrKeyringState> {
return {
accounts: Object.values(this.#accounts),
cbor: '', // TODO: Serialize deriver
};
}

async deserialize(state: QrKeyringState): Promise<void> {
this.#accounts = state.accounts;
if (state.cbor) {
this.submitCBOR(state.cbor);
}
}

async addAccounts(_accountsToAdd: number): Promise<Hex[]> {
// TODO: Implement
}

async getAccounts(): Promise<Hex[]> {
return Object.values(this.#accounts);
}

submitCBOR(cbor: Hex) {
const ur = URRegistryDecoder.decode(cbor);
const bufferedCbor = Buffer.from(cbor, 'hex');
let derivationSource: CryptoHDKey | CryptoAccount;

switch (ur.type) {
case SUPPORTED_UR_TYPE.CRYPTO_HDKEY:
derivationSource = CryptoHDKey.fromCBOR(bufferedCbor);
break;
case SUPPORTED_UR_TYPE.CRYPTO_ACCOUNT:
derivationSource = CryptoAccount.fromCBOR(bufferedCbor);
break;
default:
throw new Error('Unsupported UR type');
}

this.#deriver.init(derivationSource);
}

async setAccountToUnlock(index: number): Promise<void> {
// TODO: Implement
}
}
11 changes: 11 additions & 0 deletions packages/keyring-eth-qr/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.packages.build.json",
"compilerOptions": {
"baseUrl": "./",
"outDir": "dist",
"rootDir": "src",
"target": "es2020"
},
"include": ["./src/**/*.ts"],
"exclude": ["./src/**/*.test.ts", "./src/sample.ts"]
}
8 changes: 8 additions & 0 deletions packages/keyring-eth-qr/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.packages.json",
"compilerOptions": {
"baseUrl": "./"
},
"include": ["./src"],
"exclude": ["./dist/**/*"]
}
6 changes: 6 additions & 0 deletions packages/keyring-eth-qr/typedoc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"entryPoints": ["./src/index.ts"],
"excludePrivate": true,
"hideGenerator": true,
"out": "docs"
}
1 change: 1 addition & 0 deletions tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"references": [
{ "path": "./packages/keyring-api/tsconfig.build.json" },
{ "path": "./packages/keyring-eth-ledger-bridge/tsconfig.build.json" },
{ "path": "./packages/keyring-eth-qr/tsconfig.build.json" },
{ "path": "./packages/keyring-eth-simple/tsconfig.build.json" },
{ "path": "./packages/keyring-eth-trezor/tsconfig.build.json" },
{ "path": "./packages/keyring-snap-bridge/tsconfig.build.json" }
Expand Down
Loading