add trust-graph-js project (#4)

This commit is contained in:
Dima 2021-02-17 18:10:57 +03:00 committed by GitHub
parent 2dc5df28cc
commit 87332f0f4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 7820 additions and 0 deletions

23
js/.eslintrc.js Normal file
View File

@ -0,0 +1,23 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12,
sourceType: 'module', // Allows for the use of imports
},
env: {
browser: true,
es2021: true,
},
extends: [
'airbnb-base',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
// Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
'plugin:prettier/recommended',
],
plugins: ['@typescript-eslint', 'prettier'],
rules: {},
settings: {
'import/extensions': ['.js', '.ts'],
},
};

17
js/.gitignore vendored Normal file
View File

@ -0,0 +1,17 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.idea
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
bundle/
# Dependency directories
node_modules/
jspm_packages/
/dist/

12
js/.npmignore Normal file
View File

@ -0,0 +1,12 @@
.idea
.gitignore
node_modules
types
src/
tsconfig.json
webpack.config.js
bundle
pkg

8
js/.prettierrc.js Normal file
View File

@ -0,0 +1,8 @@
module.exports = {
semi: true,
trailingComma: "all",
singleQuote: true,
printWidth: 120,
tabWidth: 4,
useTabs: false
};

4
js/jest.config.js Normal file
View File

@ -0,0 +1,4 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};

7295
js/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

35
js/package.json Normal file
View File

@ -0,0 +1,35 @@
{
"name": "@fluencelabs/trust-graph",
"version": "0.1.0",
"description": "Trust graph implementation",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"scripts": {
"test": "jest --watch",
"test:all": "jest",
"build": "tsc"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"bs58": "4.0.1",
"libp2p-crypto": "0.19.0",
"loglevel": "1.7.0",
"peer-id": "0.13.12"
},
"devDependencies": {
"@types/base64-js": "1.2.5",
"@types/bs58": "4.0.1",
"assert": "2.0.0",
"libp2p-ts": "https://github.com/ChainSafe/libp2p-ts.git#fca072c9764436ef71f974a211bb1befae432575",
"@types/node": "14.14.28",
"mocha-loader": "^5.1.5",
"ts-loader": "7.0.5",
"ts-mocha": "8.0.0",
"typescript": "^3.9.5",
"jest": "^26.6.3",
"@types/jest": "^26.0.20",
"ts-jest": "^26.5.0"
}
}

View File

@ -0,0 +1,63 @@
import {certificateFromString, certificateToString} from "../certificate";
describe('Typescript usage suite', () => {
it('should serialize and deserialize certificate correctly', async function () {
let cert = `11
1111
5566Dn4ZXXbBK5LJdUsE7L3pG9qdAzdPY47adjzkhEx9
3HNXpW2cLdqXzf4jz5EhsGEBFkWzuVdBCyxzJUZu2WPVU7kpzPjatcqvdJMjTtcycVAdaV5qh2fCGphSmw8UMBkr
158981172690500
1589974723504
2EvoZAZaGjKWFVdr36F1jphQ5cW7eK3yM16mqEHwQyr7
4UAJQWzB3nTchBtwARHAhsn7wjdYtqUHojps9xV6JkuLENV8KRiWM3BhQByx5KijumkaNjr7MhHjouLawmiN1A4d
1590061123504
1589974723504`;
let deser = await certificateFromString(cert);
let ser = certificateToString(deser);
expect(ser).toEqual(cert);
});
})
// TODO implement this test when `trust-graph-js - fluence-js - fluence node` chain will be available
// export async function testCerts() {
// const key1 = await generatePeerId();
// const key2 = await generatePeerId();
//
// // connect to two different nodes
// const cl1 = new FluenceClientImpl(key1);
// const cl2 = new FluenceClientImpl(key2);
//
// await cl1.connect('/dns4/134.209.186.43/tcp/9003/ws/p2p/12D3KooWBUJifCTgaxAUrcM9JysqCcS4CS8tiYH5hExbdWCAoNwb');
// await cl2.connect('/ip4/134.209.186.43/tcp/9002/ws/p2p/12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er');
//
// let trustGraph1 = new TrustGraph(/* cl1 */);
// let trustGraph2 = new TrustGraph(/* cl2 */);
//
// let issuedAt = new Date();
// let expiresAt = new Date();
// // certificate expires after one day
// expiresAt.setDate(new Date().getDate() + 1);
//
// // create root certificate for key1 and extend it with key2
// let rootCert = await nodeRootCert(key1);
// let extended = await issue(key1, key2, rootCert, expiresAt.getTime(), issuedAt.getTime());
//
// // publish certificates to Fluence network
// await trustGraph1.publishCertificates(key2.toB58String(), [extended]);
//
// // get certificates from network
// let certs = await trustGraph2.getCertificates(key2.toB58String());
//
// // root certificate could be different because nodes save trusts with bigger `expiresAt` date and less `issuedAt` date
// expect(certs[0].chain[1].issuedFor.toB58String()).to.be.equal(extended.chain[1].issuedFor.toB58String());
// expect(certs[0].chain[1].signature).to.be.equal(extended.chain[1].signature);
// expect(certs[0].chain[1].expiresAt).to.be.equal(extended.chain[1].expiresAt);
// expect(certs[0].chain[1].issuedAt).to.be.equal(extended.chain[1].issuedAt);
//
// await cl1.disconnect();
// await cl2.disconnect();
// }

107
js/src/certificate.ts Normal file
View File

@ -0,0 +1,107 @@
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { createTrust, Trust, trustFromString, trustToString } from './trust';
import * as PeerId from 'peer-id';
const FORMAT = '11';
const VERSION = '1111';
// TODO verify certificate
// Chain of trusts started from self-signed root trust.
export interface Certificate {
chain: Trust[];
}
export function certificateToString(cert: Certificate): string {
let certStr = cert.chain.map((t) => trustToString(t)).join('\n');
return `${FORMAT}\n${VERSION}\n${certStr}`;
}
export async function certificateFromString(str: string): Promise<Certificate> {
let lines = str.split('\n');
// last line could be empty
if (!lines[lines.length - 1]) {
lines.pop();
}
// TODO do match different formats and versions
let _format = lines[0];
let _version = lines[1];
// every trust is 4 lines, certificate lines number without format and version should be divided by 4
if ((lines.length - 2) % 4 !== 0) {
throw Error('Incorrect format of the certificate:\n' + str);
}
let chain: Trust[] = [];
let i;
for (i = 2; i < lines.length; i = i + 4) {
chain.push(await trustFromString(lines[i], lines[i + 1], lines[i + 2], lines[i + 3]));
}
return { chain };
}
// Creates new certificate with root trust (self-signed public key) from a key pair.
export async function issueRoot(
issuedBy: PeerId,
forPk: PeerId,
expiresAt: number,
issuedAt: number,
): Promise<Certificate> {
if (expiresAt < issuedAt) {
throw Error('Expiration time should be greater then issued time.');
}
let maxDate = new Date(158981172690500).getTime();
let rootTrust = await createTrust(issuedBy, issuedBy, maxDate, issuedAt);
let trust = await createTrust(forPk, issuedBy, expiresAt, issuedAt);
let chain = [rootTrust, trust];
return {
chain: chain,
};
}
// Adds a new trust into chain of trust in certificate.
export async function issue(
issuedBy: PeerId,
forPk: PeerId,
extendCert: Certificate,
expiresAt: number,
issuedAt: number,
): Promise<Certificate> {
if (expiresAt < issuedAt) {
throw Error('Expiration time should be greater then issued time.');
}
let lastTrust = extendCert.chain[extendCert.chain.length - 1];
if (lastTrust.issuedFor !== issuedBy) {
throw Error('`issuedFor` should be equal to `issuedBy` in the last trust of the chain.');
}
let trust = await createTrust(forPk, issuedBy, expiresAt, issuedAt);
let chain = [...extendCert.chain];
chain.push(trust);
return {
chain: chain,
};
}

20
js/src/index.ts Normal file
View File

@ -0,0 +1,20 @@
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export * from './certificate'
export * from './trust'
export * from './trust_graph'
export * from './misc'

36
js/src/misc.ts Normal file
View File

@ -0,0 +1,36 @@
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as PeerId from 'peer-id';
import { keys } from 'libp2p-crypto';
import { Certificate, issueRoot } from './certificate';
/**
* Generate root certificate with one of the Fluence trusted key for one day.
*/
export async function nodeRootCert(issuedFor: PeerId): Promise<Certificate> {
// prettier-ignore
let seed = [46, 188, 245, 171, 145, 73, 40, 24, 52, 233, 215, 163, 54, 26, 31, 221, 159, 179, 126, 106, 27, 199, 189, 194, 80, 133, 235, 42, 42, 247, 80, 201];
let privateK = await keys.generateKeyPairFromSeed('Ed25519', Uint8Array.from(seed), 256);
let peerId = await PeerId.createFromPrivKey(Buffer.from(privateK.bytes));
let issuedAt = new Date();
let expiresAt = new Date();
expiresAt.setDate(new Date().getDate() + 1);
return await issueRoot(peerId, issuedFor, expiresAt.getTime(), issuedAt.getTime());
}

90
js/src/trust.ts Normal file
View File

@ -0,0 +1,90 @@
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as PeerId from 'peer-id';
import { decode, encode } from 'bs58';
import crypto from 'libp2p-crypto';
const ed25519 = crypto.keys.supportedKeys.ed25519;
// One element in chain of trust in a certificate.
export interface Trust {
issuedFor: PeerId;
expiresAt: number;
signature: string;
issuedAt: number;
}
export function trustToString(trust: Trust): string {
return `${encode(trust.issuedFor.pubKey.marshal())}\n${trust.signature}\n${trust.expiresAt}\n${trust.issuedAt}`;
}
export async function trustFromString(
issuedFor: string,
signature: string,
expiresAt: string,
issuedAt: string,
): Promise<Trust> {
let pubKey = ed25519.unmarshalEd25519PublicKey(decode(issuedFor));
let peerId = await PeerId.createFromPubKey(Buffer.from(pubKey.bytes));
return {
issuedFor: peerId,
signature: signature,
expiresAt: parseInt(expiresAt),
issuedAt: parseInt(issuedAt),
};
}
export async function createTrust(
forPk: PeerId,
issuedBy: PeerId,
expiresAt: number,
issuedAt: number,
): Promise<Trust> {
let bytes = toSignMessage(forPk, expiresAt, issuedAt);
let signature = await issuedBy.privKey.sign(Buffer.from(bytes));
let signatureStr = encode(signature);
return {
issuedFor: forPk,
expiresAt: expiresAt,
signature: signatureStr,
issuedAt: issuedAt,
};
}
function toSignMessage(pk: PeerId, expiresAt: number, issuedAt: number): Uint8Array {
let bytes = new Uint8Array(48);
let pkEncoded = pk.pubKey.marshal();
bytes.set(pkEncoded, 0);
bytes.set(numToArray(expiresAt), 32);
bytes.set(numToArray(issuedAt), 40);
return bytes;
}
function numToArray(n: number): number[] {
let byteArray = [0, 0, 0, 0, 0, 0, 0, 0];
for (let index = 0; index < byteArray.length; index++) {
let byte = n & 0xff;
byteArray[index] = byte;
n = (n - byte) / 256;
}
return byteArray;
}

75
js/src/trust_graph.ts Normal file
View File

@ -0,0 +1,75 @@
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Certificate, certificateFromString, certificateToString } from './certificate';
import * as log from 'loglevel';
// TODO inherit this with FluenceClient in fluence-js
// The client to interact with the Fluence trust graph API
export class TrustGraph {
//client: FluenceClient;
constructor() {}
// Publish certificate to Fluence network. It will be published in Kademlia neighbourhood by `peerId` key.
async publishCertificates(peerId: string, certs: Certificate[]) {
let certsStr = [];
for (let cert of certs) {
certsStr.push(await certificateToString(cert));
}
// TODO inherit this with FluenceClient in fluence-js
throw new Error("unimplemented")
/*let response = await this.client.callPeer("add_certificates", {
certificates: certsStr,
peer_id: peerId
});*/
let response: any = {};
if (response.reason) {
throw Error(response.reason);
} else if (response.status) {
return response.status;
} else {
throw Error(
`Unexpected response: ${response}. Should be 'status' field for a success response or 'reason' field for an error.`,
);
}
}
// Get certificates that stores in Kademlia neighbourhood by `peerId` key.
async getCertificates(peerId: string): Promise<Certificate[]> {
let resp: any = {};
// TODO inherit this with FluenceClient in fluence-js
throw new Error("unimplemented")
/*let resp = await this.client.callPeer("certificates", {
peer_id: peerId
});*/
let certificatesRaw = resp.certificates;
if (!(certificatesRaw && Array.isArray(certificatesRaw))) {
log.error(Array.isArray(certificatesRaw));
throw Error('Unexpected. Certificates should be presented in the response as an array.');
}
let certs = [];
for (let cert of certificatesRaw) {
certs.push(await certificateFromString(cert));
}
return certs;
}
}

35
js/tsconfig.json Normal file
View File

@ -0,0 +1,35 @@
{
"compilerOptions": {
"typeRoots": [
"./node_modules/@types",
"./node_modules/libp2p-ts/types",
"./types"
],
"outDir": "./dist/",
"baseUrl": ".",
"sourceMap": true,
"inlineSources": true,
"strictFunctionTypes": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"pretty": true,
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"declaration": true,
"esModuleInterop": true,
"declarationMap": true,
"strict": true,
"noImplicitAny": false,
"alwaysStrict": true,
"noImplicitThis": true,
"strictNullChecks": false
},
"exclude": [
"node_modules",
"dist",
"bundle",
"src/__test__"
],
"include": ["src/**/*"]
}