Skip to content
Closed
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
7 changes: 7 additions & 0 deletions packages/common-types/src/baseTypes/aggregateTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,8 @@ export type LocalTransitionData = [...IAuthMetadatas, ...ShareStores, ...IMessag
export type LocalMetadataTransitions = [LocalTransitionShares, LocalTransitionData];

export interface ITKeyApi {
setModuleState<T>(data: T, moduleName: string);
getModuleState<T>(moduleName: string): T;
getMetadata(): IMetadata;
getStorageLayer(): IStorageLayer;
initialize(params: { input?: ShareStore; importKey?: BN; neverInitializeNewKey?: boolean }): Promise<KeyDetails>;
Expand All @@ -256,6 +258,7 @@ export interface ITKeyApi {
middleware: (generalStore: unknown, oldShareStores: ShareStoreMap, newShareStores: ShareStoreMap) => unknown
): void;
_addReconstructKeyMiddleware(moduleName: string, middleware: () => Promise<Array<BN>>): void;
_addReconstructKeyMiddlewareV2(moduleName: string, middleware: (tkey: ITKeyApi, moduleName: string) => Promise<Array<BN>>): void;
_addShareSerializationMiddleware(
serialize: (share: BN, type: string) => Promise<unknown>,
deserialize: (serializedShare: unknown, type: string) => Promise<BN>
Expand Down Expand Up @@ -310,3 +313,7 @@ export interface ITKey extends ITKeyApi, ISerializable {

getKeyDetails(): KeyDetails;
}

export type ReconstructKeyMiddlewareMapV2 = {
[moduleName: string]: (tkey: ITKeyApi, moduleName: string) => Promise<BN[]>;
};
36 changes: 36 additions & 0 deletions packages/core/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
prettyPrintError,
ReconstructedKeyResult,
ReconstructKeyMiddlewareMap,
ReconstructKeyMiddlewareMapV2,
RefreshMiddlewareMap,
RefreshSharesResult,
Share,
Expand Down Expand Up @@ -81,12 +82,16 @@ class ThresholdKey implements ITKey {

_shareSerializationMiddleware: ShareSerializationMiddleware;

_reconstructKeyMiddlewareV2: ReconstructKeyMiddlewareMapV2;

storeDeviceShare: (deviceShareStore: ShareStore, customDeviceInfo?: StringifiedType) => Promise<void>;

haveWriteMetadataLock: string;

serverTimeOffset?: number = 0;

moduleState: Record<string, any> = {};

constructor(args?: TKeyArgs) {
const { enableLogging = false, modules = {}, serviceProvider, storageLayer, manualSync = false, serverTimeOffset } = args || {};
this.enableLogging = enableLogging;
Expand All @@ -98,6 +103,7 @@ class ThresholdKey implements ITKey {
this.manualSync = manualSync;
this._refreshMiddleware = {};
this._reconstructKeyMiddleware = {};
this._reconstructKeyMiddlewareV2 = {};
this._shareSerializationMiddleware = undefined;
this.storeDeviceShare = undefined;
this._localMetadataTransitions = [[], []];
Expand Down Expand Up @@ -193,6 +199,14 @@ class ThresholdKey implements ITKey {
return tb;
}

getModuleState<T>(moduleName: string): T {
return this.moduleState[moduleName] as T;
}

setModuleState<T>(data: T, moduleName: string) {
this.moduleState[moduleName] = data;
}

getStorageLayer(): IStorageLayer {
return this.storageLayer;
}
Expand Down Expand Up @@ -439,6 +453,21 @@ class ThresholdKey implements ITKey {
})
);
}

// duplicate for testing purpose only
if (_reconstructKeyMiddleware && Object.keys(this._reconstructKeyMiddlewareV2).length > 0) {
// retireve/reconstruct extra keys that live on metadata
await Promise.all(
Object.keys(this._reconstructKeyMiddlewareV2).map(async (x) => {
if (Object.prototype.hasOwnProperty.call(this._reconstructKeyMiddlewareV2, x)) {
const extraKeys = await this._reconstructKeyMiddlewareV2[x](this, x);
returnObject[x] = extraKeys;
returnObject.allKeys.push(...extraKeys);
}
})
);
}

return returnObject;
}

Expand Down Expand Up @@ -1071,6 +1100,10 @@ class ThresholdKey implements ITKey {
this._reconstructKeyMiddleware[moduleName] = middleware;
}

_addReconstructKeyMiddlewareV2(moduleName: string, middleware: (tkey: ITKeyApi, moduleName: string) => Promise<BN[]>): void {
this._reconstructKeyMiddlewareV2[moduleName] = middleware;
}

_addShareSerializationMiddleware(
serialize: (share: BN, type: string) => Promise<unknown>,
deserialize: (serializedShare: unknown, type: string) => Promise<BN>
Expand Down Expand Up @@ -1290,13 +1323,16 @@ class ThresholdKey implements ITKey {

getApi(): ITKeyApi {
return {
getModuleState: this.getModuleState.bind(this),
setModuleState: this.setModuleState.bind(this),
getMetadata: this.getMetadata.bind(this),
getStorageLayer: this.getStorageLayer.bind(this),
initialize: this.initialize.bind(this),
catchupToLatestShare: this.catchupToLatestShare.bind(this),
_syncShareMetadata: this._syncShareMetadata.bind(this),
_addRefreshMiddleware: this._addRefreshMiddleware.bind(this),
_addReconstructKeyMiddleware: this._addReconstructKeyMiddleware.bind(this),
_addReconstructKeyMiddlewareV2: this._addReconstructKeyMiddlewareV2.bind(this),
_addShareSerializationMiddleware: this._addShareSerializationMiddleware.bind(this),
addShareDescription: this.addShareDescription.bind(this),
generateNewShare: this.generateNewShare.bind(this),
Expand Down
1 change: 1 addition & 0 deletions packages/default/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"devDependencies": {
"@tkey/private-keys": "^7.4.0",
"@tkey/seed-phrase": "^7.4.0",
"@tkey/seed-phrase-v2": "^7.4.0",
"@toruslabs/eccrypto": "^2.1.1",
"@toruslabs/http-helpers": "^3.3.0",
"web3-utils": "^1.9.0"
Expand Down
71 changes: 70 additions & 1 deletion packages/default/test/shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
import { ecCurve, getPubKeyPoint, KEY_NOT_FOUND, SHARE_DELETED } from "@tkey/common-types";
import PrivateKeyModule, { ED25519Format, SECP256K1Format } from "@tkey/private-keys";
import SecurityQuestionsModule from "@tkey/security-questions";
import SeedPhraseModule, { MetamaskSeedPhraseFormat } from "@tkey/seed-phrase";
import SeedPhraseModule, { MetamaskSeedPhraseFormat, SEED_PHRASE_MODULE_NAME } from "@tkey/seed-phrase";
import SeedPhraseModuleV2 from "@tkey/seed-phrase-v2";
import TorusServiceProvider from "@tkey/service-provider-torus";
import ShareTransferModule from "@tkey/share-transfer";
import TorusStorageLayer from "@tkey/storage-layer-torus";
Expand Down Expand Up @@ -1052,6 +1053,74 @@ export const sharedTestCases = (mode, torusSP, storageLayer) => {
tb2.inputShareStore(resp1.deviceShare);
const reconstructedKey = await tb2.reconstructKey();

compareReconstructedKeys(reconstructedKey, {
privKey: resp1.privKey,
seedPhraseModule: [
new BN("70dc3117300011918e26b02176945cc15c3d548cf49fd8418d97f93af699e46", "hex"),
new BN("4d62a55af3496a7b290a12dd5fd5ef3e051d787dbc005fb74536136949602f9e", "hex"),
],
privateKeyModule: [
new BN("4bd0041b7654a9b16a7268a5de7982f2422b15635c4fd170c140dc4897624390", "hex"),
new BN("1ea6edde61c750ec02896e9ac7fe9ac0b48a3630594fdf52ad5305470a2635c0", "hex"),
],
allKeys: [
resp1.privKey,
new BN("70dc3117300011918e26b02176945cc15c3d548cf49fd8418d97f93af699e46", "hex"),
new BN("4d62a55af3496a7b290a12dd5fd5ef3e051d787dbc005fb74536136949602f9e", "hex"),
new BN("4bd0041b7654a9b16a7268a5de7982f2422b15635c4fd170c140dc4897624390", "hex"),
new BN("1ea6edde61c750ec02896e9ac7fe9ac0b48a3630594fdf52ad5305470a2635c0", "hex"),
],
});

const reconstructedKey2 = await tb2.reconstructKey(false);
compareReconstructedKeys(reconstructedKey2, {
privKey: resp1.privKey,
allKeys: [resp1.privKey],
});
});

it.only(`#should be able to get/set private keys and seed phrase v2, manualSync=${mode}`, async function () {
const resp1 = await tb._initializeNewKey({ initializeModules: true });

await tb.modules.seedPhrase.setSeedPhrase("HD Key Tree", "seed sock milk update focus rotate barely fade car face mechanic mercy");
await tb.modules.seedPhrase.setSeedPhrase("HD Key Tree", "chapter gas cost saddle annual mouse chef unknown edit pen stairs claw");

const actualPrivateKeys = [
new BN("4bd0041b7654a9b16a7268a5de7982f2422b15635c4fd170c140dc4897624390", "hex"),
new BN("1ea6edde61c750ec02896e9ac7fe9ac0b48a3630594fdf52ad5305470a2635c0", "hex"),
];
await tb.modules.privateKeyModule.setPrivateKey("secp256k1n", actualPrivateKeys[0]);
await tb.modules.privateKeyModule.setPrivateKey("secp256k1n", actualPrivateKeys[1]);
await tb.syncLocalMetadataTransitions();

const metamaskSeedPhraseFormat2 = new MetamaskSeedPhraseFormat("https://mainnet.infura.io/v3/bca735fdbba0408bb09471e86463ae68");
const tb2 = new ThresholdKey({
serviceProvider: customSP,
manualSync: mode,
storageLayer: customSL,
modules: {
// seedPhrase: new SeedPhraseModule([metamaskSeedPhraseFormat2]),
privateKeyModule: new PrivateKeyModule([secp256k1Format]),
},
});
await tb2.initialize();
tb2.inputShareStore(resp1.deviceShare);

const mdata = {
moduleName: SEED_PHRASE_MODULE_NAME,
seedPhraseFormats: [metamaskSeedPhraseFormat2],
};
SeedPhraseModuleV2.setModuleReferences(tb2, mdata);

const reconstructedKey = await tb2.reconstructKey();

// Example SeedPhrase Module api call
const key = await SeedPhraseModuleV2.getAccounts(tb2);
console.log(key);
const keyAccounts = await SeedPhraseModuleV2.getSeedPhrasesWithAccounts(tb2);
console.log(keyAccounts)


compareReconstructedKeys(reconstructedKey, {
privKey: resp1.privKey,
seedPhraseModule: [
Expand Down
21 changes: 21 additions & 0 deletions packages/seed-phrase-v2/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 tKey

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
80 changes: 80 additions & 0 deletions packages/seed-phrase-v2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# tKey Seed Phrase Module

[![npm version](https://img.shields.io/npm/v/@tkey/seed-phrase?label=%22%22)](https://www.npmjs.com/package/@tkey/seed-phrase/v/latest) [![minzip](https://img.shields.io/bundlephobia/minzip/@tkey/seed-phrase?label=%22%22)](https://bundlephobia.com/result?p=@tkey/seed-phrase@latest)

The tKey Seed Phrase Module helps you add or remove the and password as a share for tkey. This module is the part of the [tKey SDK](https://github.com/tkey/tkey/).


## Installation

```shell
npm install --save @tkey/seed-phrase
```

## Initialization

#### Import the `SeedPhraseModule` class from `@tkey/seed-phrase`

```javascript
import SeedPhraseModule from "@tkey/seed-phrase";
```

#### Assign the `SeedPhraseModule` class to a variable

```javascript
const seedPhraseModule = new SeedPhraseModule();
```

### Returns

The `SeedPhraseModule` class returns an object with the following properties:

```ts
declare class SeedPhraseModule implements IModule {
moduleName: string;
tbSDK: ITKeyApi;
seedPhraseFormats: ISeedPhraseFormat[];
constructor(formats: ISeedPhraseFormat[]);
setModuleReferences(tbSDK: ITKeyApi): void;
initialize(): Promise<void>;
setSeedPhrase(seedPhraseType: string, seedPhrase?: string): Promise<void>;
setSeedPhraseStoreItem(partialStore: ISeedPhraseStore): Promise<void>;
CRITICAL_changeSeedPhrase(oldSeedPhrase: string, newSeedPhrase: string): Promise<void>;
getSeedPhrases(): Promise<ISeedPhraseStore[]>;
getSeedPhrasesWithAccounts(): Promise<ISeedPhraseStoreWithKeys[]>;
getAccounts(): Promise<BN[]>;
}
```

## Usage

With the `SeedPhraseModule`, you've access to the following functions:

### Set Seed Phrase

#### `setSeedPhrase(seedPhraseType: string, seedPhrase?: string)`

- `seedPhraseType`: The type of seed phrase to set.
- `seedPhrase`: The seed phrase to set.

### Set Seed Phrase Store Item

#### `setSeedPhraseStoreItem(partialStore: ISeedPhraseStore)`

- `partialStore`: The partial store to set.

### Get Seed Phrase

#### `getSeedPhrases()`

#### Return

- `Promise<ISeedPhraseStore[]>`: A list of seed phrases.

### Get Seed Phrase With Accounts

#### `getSeedPhrasesWithAccounts()`

#### Return

- `Promise<ISeedPhraseStoreWithKeys[]>`: A list of seed phrases with accounts.
62 changes: 62 additions & 0 deletions packages/seed-phrase-v2/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"name": "@tkey/seed-phrase-v2",
"version": "7.4.0",
"description": "TKey Seed Phrase Module",
"author": "Torus Labs",
"homepage": "https://github.com/tkey/tkey#readme",
"license": "MIT",
"main": "dist/seedPhrase.cjs.js",
"module": "dist/seedPhrase.esm.js",
"unpkg": "dist/seedPhrase.umd.min.js",
"jsdelivr": "dist/seedPhrase.umd.min.js",
"types": "dist/types/index.d.ts",
"files": [
"dist",
"src"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tkey/tkey.git"
},
"scripts": {
"test": "cross-env MOCKED=true mocha --config ../../.mocharc.json ",
"coverage": "nyc yarn test",
"coverage-production": "nyc yarn test-production",
"test-development": "cross-env MOCKED=false METADATA=http://localhost:5051 mocha --config ../../.mocharc.json ",
"test-production": "cross-env MOCKED=false METADATA=https://metadata.tor.us mocha --config ../../.mocharc.json ",
"test-debugger": "mocha --config ../../.mocharc.json --inspect-brk",
"dev": "rimraf dist/ && cross-env NODE_ENV=development torus-scripts build",
"build": "rimraf dist/ && cross-env NODE_ENV=production torus-scripts build",
"lint": "eslint --fix 'src/**/*.ts'",
"prepack": "yarn run build",
"pre-commit": "lint-staged"
},
"bugs": {
"url": "https://github.com/tkey/tkey/issues"
},
"peerDependencies": {
"@babel/runtime": "7.x"
},
"dependencies": {
"@tkey/common-types": "^7.4.0",
"bip39": "^3.1.0",
"bn.js": "^5.2.1",
"hdkey": "^2.1.0",
"web3-core": "^1.9.0",
"web3-eth": "^1.9.0",
"web3-utils": "^1.9.0"
},
"devDependencies": {
"@types/bn.js": "^5.1.1"
},
"lint-staged": {
"!(*d).ts": [
"yarn run lint --",
"prettier --write 'src/**/*.ts'"
]
},
"gitHead": "9967ce9f795f495f28ef0da1fc50acde31dcc258"
}
Loading