feat: Update Libp2p to latest version. Add standalone bundled JS Client (#239)

This commit is contained in:
Pavel 2023-02-06 15:18:04 +03:00 committed by GitHub
parent 267ebb687f
commit a1265f4d7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
158 changed files with 3854 additions and 5236 deletions

2
.npmrc
View File

@ -1,2 +1,2 @@
auto-install-peers=true
save-exact=true
save-exact=true

6
package-lock.json generated
View File

@ -1,6 +0,0 @@
{
"name": "fluence-js",
"lockfileVersion": 2,
"requires": true,
"packages": {}
}

19
package.json Normal file
View File

@ -0,0 +1,19 @@
{
"name": "common-dev-deps",
"version": "0.1.0",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"type": "module",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"scripts": {},
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {},
"devDependencies": {
"ts-node": "10.9.1",
"typescript": "4.7"
}
}

View File

@ -1,17 +1,7 @@
{
"extends": "../../../../tsconfig.json",
"compilerOptions": {
"lib": ["es2015", "dom"],
"outDir": "./dist/",
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": false,
"sourceMap": true
"outDir": "./dist"
},
"exclude": ["node_modules", "dist"],
"include": ["src"]
"exclude": ["node_modules", "dist"]
}

View File

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

View File

@ -1,23 +1,7 @@
{
"extends": "../../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist/",
"allowJs": true,
"baseUrl": ".",
"sourceMap": false,
"inlineSources": false,
"pretty": true,
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"declaration": false,
"esModuleInterop": true,
"declarationMap": false,
"strict": true,
"noImplicitAny": false,
"alwaysStrict": true,
"noImplicitThis": true,
"strictNullChecks": false
"outDir": "./dist"
},
"exclude": ["node_modules", "dist"],
"include": ["src", "test"]
"exclude": ["node_modules", "dist"]
}

View File

@ -1,26 +1,7 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist"
},
"exclude": ["node_modules", "dist"]
}

View File

@ -17,8 +17,7 @@
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/fluence": "workspace:*",
"@fluencelabs/js-client.node": "workspace:*",
"ts-node": "10.9.1"
"@fluencelabs/js-client.node": "workspace:*"
},
"devDependencies": {
"@types/node": "16.11.59",

View File

@ -1,12 +1,7 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist/",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"declaration": true,
"skipDefaultLibCheck": true
},
"exclude": ["node_modules", "dist"],
"include": ["src/**/*"]
"outDir": "./dist"
},
"exclude": ["node_modules", "dist"]
}

View File

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

View File

@ -15,14 +15,12 @@
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/js-peer": "workspace:0.1.0"
"@fluencelabs/js-peer": "workspace:*"
},
"devDependencies": {
"@types/node": "16.11.59",
"@types/jest": "28.1.0",
"jest": "28.1.0",
"ts-jest": "28.0.2",
"ts-node": "10.9.1",
"typescript": "4.6.4"
"ts-jest": "28.0.2"
}
}

View File

@ -1,21 +1,7 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist/",
"baseUrl": ".",
"downlevelIteration": true,
"sourceMap": true,
"inlineSources": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"declaration": true,
"esModuleInterop": true,
"declarationMap": true,
"strict": true,
"skipLibCheck": true
"outDir": "./dist"
},
"exclude": ["node_modules", "dist", "bundle"],
"include": ["src/**/*"]
"exclude": ["node_modules", "dist"]
}

View File

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

View File

@ -1,17 +0,0 @@
# Fluence JS
[![npm](https://img.shields.io/npm/v/@fluencelabs/fluence)](https://www.npmjs.com/package/@fluencelabs/fluence)
Official TypeScript implementation of the Fluence Peer.
## Getting started
To start developing applications with Fluence JS refer to the official [documentation](https://fluence.dev/docs/build/fluence-js/)
## Contributing
While the project is still in the early stages of development, you are welcome to track progress and contribute. As the project is undergoing rapid changes, interested contributors should contact the team before embarking on larger pieces of work. All contributors should consult with and agree to our [basic contributing rules](CONTRIBUTING.md).
## License
[Apache 2.0](LICENSE)

View File

@ -1,6 +0,0 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testTimeout: 10000,
testPathIgnorePatterns: ['dist'],
};

View File

@ -1,32 +0,0 @@
{
"name": "@fluencelabs/fluence",
"version": "0.28.0",
"description": "TypeScript implementation of Fluence Peer",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"scripts": {
"build": "tsc"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"loglevel": "1.8.1",
"@fluencelabs/keypair": "workspace:0.2.0",
"@fluencelabs/avm": "0.32.1",
"@fluencelabs/marine-js": "0.3.38",
"@fluencelabs/js-peer": "workspace:0.1.0"
},
"devDependencies": {
"@types/node": "16.11.59",
"@types/jest": "28.1.0",
"jest": "28.1.0",
"ts-jest": "28.0.2",
"ts-node": "10.9.1",
"typescript": "4.6.4"
}
}

View File

@ -1,92 +0,0 @@
/*
* 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 log, { LogLevelDesc } from 'loglevel';
export { KeyPair } from '@fluencelabs/keypair';
import { FluencePeer, PeerConfig } from '@fluencelabs/js-peer/dist/FluencePeer';
export { PeerStatus } from '@fluencelabs/js-peer/dist/FluencePeer';
export { FluencePeer, PeerConfig } from '@fluencelabs/js-peer/dist/FluencePeer';
export { PeerIdB58, CallParams } from '@fluencelabs/js-peer/dist/commonTypes';
export const setLogLevel = (level: LogLevelDesc) => {
log.setLevel(level);
};
log.setDefaultLevel('WARN');
// @ts-ignore
const defaultPeer = globalThis.defaultPeer;
/**
* Public interface to Fluence JS
*/
export const Fluence = {
/**
* Initializes the default peer: starts the Aqua VM, initializes the default call service handlers
* and (optionally) connect to the Fluence network
* @param config - object specifying peer configuration
*/
start: (config?: PeerConfig): Promise<void> => {
return defaultPeer.start(config);
},
/**
* Un-initializes the default peer: stops all the underlying workflows, stops the Aqua VM
* and disconnects from the Fluence network
*/
stop: (): Promise<void> => {
return defaultPeer.stop();
},
/**
* Get the default peer's status
* @returns Default peer's status
*/
getStatus: () => {
return defaultPeer.getStatus();
},
/**
* Get the default peer instance
* @returns the default peer instance
*/
getPeer: (): FluencePeer => {
return defaultPeer;
},
/**
* Registers marine service within the default Fluence peer from wasm file.
* Following helper functions can be used to load wasm files:
* * loadWasmFromFileSystem
* * loadWasmFromNpmPackage
* * loadWasmFromServer
* @param wasm - buffer with the wasm file for service
* @param serviceId - the service id by which the service can be accessed in aqua
*/
registerMarineService: (wasm: SharedArrayBuffer | Buffer, serviceId: string): Promise<void> => {
return defaultPeer.registerMarineService(wasm, serviceId);
},
/**
* Removes the specified marine service from the default Fluence peer
* @param serviceId - the service id to remove
*/
removeMarineService: (serviceId: string): void => {
defaultPeer.removeMarineService(serviceId);
},
};

View File

@ -1,2 +0,0 @@
export * from '@fluencelabs/js-peer/dist/builtins/Sig';
export { registerSig } from '@fluencelabs/js-peer/dist/_aqua/services';

View File

@ -1,21 +0,0 @@
{
"compilerOptions": {
"outDir": "./dist/",
"baseUrl": ".",
"downlevelIteration": true,
"sourceMap": true,
"inlineSources": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"declaration": true,
"esModuleInterop": true,
"declarationMap": true,
"strict": true,
"skipLibCheck": true
},
"exclude": ["node_modules", "dist", "bundle"],
"include": ["src/**/*"]
}

View File

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

View File

@ -15,16 +15,12 @@
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/js-peer": "workspace:0.1.0",
"@fluencelabs/marine.deps-loader.node": "workspace:0.1.0",
"@fluencelabs/marine.background-runner": "workspace:0.1.0"
"@fluencelabs/js-peer": "workspace:*"
},
"devDependencies": {
"@types/node": "16.11.59",
"@types/jest": "28.1.0",
"jest": "28.1.0",
"ts-jest": "28.0.2",
"ts-node": "10.9.1",
"typescript": "4.6.4"
}
}

View File

@ -1,21 +1,7 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist/",
"baseUrl": ".",
"downlevelIteration": true,
"sourceMap": true,
"inlineSources": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"declaration": true,
"esModuleInterop": true,
"declarationMap": true,
"strict": true,
"skipLibCheck": true
"outDir": "./dist"
},
"exclude": ["node_modules", "dist", "bundle"],
"include": ["src/**/*"]
"exclude": ["node_modules", "dist"]
}

View File

@ -9,6 +9,7 @@ lerna-debug.log*
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
bundle/
tmp/
dist
esm

View File

@ -1,4 +1,4 @@
# FluenceJS Keypair
# JS Client web
This package is a part of FluenceJS, the official implementation of the Fluence Peer in typescript. See the [FluenceJS repo](https://github.com/fluencelabs/fluence-js) for more info

View File

@ -0,0 +1,126 @@
import * as fs from 'fs';
import * as path from 'path';
import { fromUint8Array } from 'js-base64';
import { build } from 'vite';
import { createRequire } from 'module';
import type { InlineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import * as inject from '@rollup/plugin-inject';
import { replaceCodePlugin } from 'vite-plugin-replace';
const require = createRequire(import.meta.url);
const getWorkerScriptPathOrDie = () => {
const scriptPath = path.resolve('../../core/dist/marine/worker-script/index.js');
if (!fs.existsSync(scriptPath)) {
console.error();
process.exit(1);
}
return scriptPath;
};
const commonConfig = (opts: {
outDir: string;
name: string;
entry: string;
}): InlineConfig & Required<Pick<InlineConfig, 'build'>> => {
return {
mode: 'production',
build: {
minify: 'esbuild',
lib: {
entry: opts.entry,
name: opts.name,
fileName: opts.name,
},
outDir: opts.outDir,
},
base: '',
plugins: [tsconfigPaths()],
optimizeDeps: {
esbuildOptions: {
define: {
global: 'globalThis',
},
},
},
};
};
const readAsBase64 = async (filePath: string): Promise<string> => {
const scriptRaw = await fs.promises.readFile(filePath);
const b64 = fromUint8Array(scriptRaw);
return b64;
};
const readWasmFromNpmAsBase64 = (pkg: string, wasmFileName: string): Promise<string> => {
const pkgPath = require.resolve(pkg);
const wasmFilePath = path.join(path.dirname(pkgPath), wasmFileName);
return readAsBase64(wasmFilePath);
};
const buildClient = async () => {
await fs.promises.mkdir('tmp', { recursive: true });
// build worker script
const workerConfig = commonConfig({
outDir: './tmp',
entry: getWorkerScriptPathOrDie(),
name: 'worker-script',
});
workerConfig.build!.rollupOptions = {
plugins: [
inject.default({
Buffer: ['buffer', 'Buffer'],
process: 'process',
}),
],
};
await build(workerConfig);
// build js-client
const jsClientConfig = commonConfig({
outDir: './dist',
entry: './src/index.ts',
name: 'js-client',
});
const workerScriptB64 = await readAsBase64('./tmp/worker-script.umd.cjs');
const avmBase64 = await readWasmFromNpmAsBase64('@fluencelabs/avm', 'avm.wasm');
const marineBase64 = await readWasmFromNpmAsBase64('@fluencelabs/marine-js', 'marine-js.wasm');
jsClientConfig.plugins!.push(
replaceCodePlugin({
replacements: [
{
from: '___worker___',
to: workerScriptB64,
},
{
from: '___avm___',
to: avmBase64,
},
{
from: '___marine___',
to: marineBase64,
},
],
}),
);
await build(jsClientConfig);
// We should exclude the script with type=module because
// - it might be confusing (i.e won't work in browsers that do not support ESM, or if you miss the `type` attribute)
// - there is a problem when using `self.crypto` in web workers
await fs.promises.rm('./dist/js-client.js');
// browsers don't understand `.cjs` extensions, just use `.js`
await fs.promises.rename('./dist/js-client.umd.cjs', './dist/js-client.min.js');
};
buildClient()
.then(() => console.log('Built successfully'))
.catch((err) => console.error('failed', err));

View File

@ -0,0 +1,39 @@
{
"name": "@fluencelabs/js-client.web.standalone",
"version": "0.1.0",
"description": "TypeScript implementation of Fluence Peer",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"type": "module",
"scripts": {
"build": "node --loader ts-node/esm ./build.ts"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/js-peer": "workspace:*",
"buffer": "6.0.3",
"process": "0.11.10"
},
"devDependencies": {
"@fluencelabs/avm": "0.35.3",
"@fluencelabs/marine-js": "0.3.42",
"@types/node": "16.11.59",
"@types/jest": "28.1.0",
"jest": "28.1.0",
"ts-jest": "28.0.2",
"js-base64": "3.7.2",
"@rollup/plugin-inject": "5.0.3",
"vite-plugin-replace": "0.1.1",
"vite": "4.0.4",
"vite-tsconfig-paths": "4.0.3"
},
"peerDependencies": {
"esbuild": "0.16.7"
}
}

View File

@ -0,0 +1,35 @@
import { FluencePeer } from '@fluencelabs/js-peer/dist/js-peer/FluencePeer';
import { MarineBasedAvmRunner } from '@fluencelabs/js-peer/dist/js-peer/avm';
import { MarineBackgroundRunner } from '@fluencelabs/js-peer/dist/marine/worker';
import { checkConnection, marineLogFunction } from '@fluencelabs/js-peer/dist/js-peer/utils';
import { InlinedWorkerLoader, InlinedWasmLoader } from '@fluencelabs/js-peer/dist/marine/deps-loader/common';
export const makeDefaultPeer = () => {
const workerLoader = new InlinedWorkerLoader('___worker___');
const controlModuleLoader = new InlinedWasmLoader('___marine___');
const avmModuleLoader = new InlinedWasmLoader('___avm___');
const marine = new MarineBackgroundRunner(workerLoader, controlModuleLoader, marineLogFunction);
const avm = new MarineBasedAvmRunner(marine, avmModuleLoader, undefined);
return new FluencePeer(marine, avm);
};
// @ts-ignore
globalThis.defaultPeer = makeDefaultPeer();
// TODO! remove after implementing smoke test (DXJ-253)
// @ts-ignore
window.demo = async () => {
// @ts-ignore
const peer: FluencePeer = globalThis.defaultPeer;
await peer.start({
connectTo: {
multiaddr: '/ip4/127.0.0.1/tcp/4310/ws/p2p/12D3KooWKEprYXUXqoV5xSBeyqrWLpQLLH4PXfvVkDJtmcqmh5V3',
peerId: '12D3KooWKEprYXUXqoV5xSBeyqrWLpQLLH4PXfvVkDJtmcqmh5V3',
},
});
const res = await checkConnection(peer);
console.log('Check connection res', res);
};

View File

@ -0,0 +1,8 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"moduleResolution": "node"
},
"exclude": ["node_modules", "dist"]
}

View File

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

View File

@ -15,16 +15,12 @@
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/js-peer": "workspace:0.1.0",
"@fluencelabs/marine.deps-loader.web": "workspace:0.1.0",
"@fluencelabs/marine.background-runner": "workspace:0.1.0"
"@fluencelabs/js-peer": "workspace:*"
},
"devDependencies": {
"@types/node": "16.11.59",
"@types/jest": "28.1.0",
"jest": "28.1.0",
"ts-jest": "28.0.2",
"ts-node": "10.9.1",
"typescript": "4.6.4"
"ts-jest": "28.0.2"
}
}

View File

@ -1,21 +1,7 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist/",
"baseUrl": ".",
"downlevelIteration": true,
"sourceMap": true,
"inlineSources": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"declaration": true,
"esModuleInterop": true,
"declarationMap": true,
"strict": true,
"skipLibCheck": true
"outDir": "./dist"
},
"exclude": ["node_modules", "dist", "bundle"],
"include": ["src/**/*"]
"exclude": ["node_modules", "dist"]
}

View File

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

View File

@ -19,7 +19,6 @@
},
"dependencies": {},
"devDependencies": {
"@types/node": "16.11.59",
"typescript": "4.6.4"
"@types/node": "16.11.59"
}
}

View File

@ -1,7 +1,7 @@
#! /usr/bin/env node
import fs from 'fs';
import path from 'path';
import * as fs from 'fs';
import * as path from 'path';
const firstArgument = process.argv[2];

View File

@ -1,21 +1,7 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist/",
"baseUrl": ".",
"downlevelIteration": true,
"sourceMap": true,
"inlineSources": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"declaration": true,
"esModuleInterop": true,
"declarationMap": true,
"strict": true,
"skipLibCheck": true
"outDir": "./dist"
},
"exclude": ["node_modules", "dist", "bundle"],
"include": ["src/**/*"]
"exclude": ["node_modules", "dist"]
}

View File

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

View File

@ -1,13 +0,0 @@
## Contribute Code
You are welcome to contribute to Fluence.
Things you need to know:
1. You need to **agree to the Contributors License Agreement**. This is a common practice in all major Open Source projects. At the current moment we are unable to accept contributions made on behalf of a company. Only individual contributions will be accepted.
2. **Not all proposed contributions can be accepted**. Some features may e.g. just fit a third-party add-on better. The contribution must fit the overall direction of Fluence and really improve it. The more effort you invest, the better you should clarify in advance whether the contribution fits: the best way would be to just open an issue to discuss the contribution you plan to make.
### Contributor License Agreement
When you contribute, you have to be aware that your contribution is covered by **Apache License 2.0**, but might relicensed under few other software licenses mentioned in the **Contributor License Agreement**.
In particular you need to agree to the [Contributor License Agreement](https://gist.github.com/fluencelabs-org/3f4cbb3cc14c1c0fb9ad99d8f7316ed7). If you agree to its content, you simply have to click on the link posted by the CLA assistant as a comment to the pull request. Click it to check the CLA, then accept it on the following screen if you agree to it. CLA assistant will save this decision for upcoming contributions and will notify you if there is any change to the CLA in the meantime.

View File

@ -1,11 +0,0 @@
# FluenceJS connection
This package is a part of FluenceJS, the official implementation of the Fluence Peer in typescript. See the [FluenceJS repo](https://github.com/fluencelabs/fluence-js) for more info
## Contributing
While the project is still in the early stages of development, you are welcome to track progress and contribute. As the project is undergoing rapid changes, interested contributors should contact the team before embarking on larger pieces of work. All contributors should consult with and agree to our [basic contributing rules](CONTRIBUTING.md).
## License
[Apache 2.0](LICENSE)

View File

@ -1,35 +0,0 @@
{
"name": "@fluencelabs/connection",
"version": "0.2.0",
"description": "Fluence connection",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"scripts": {
"build": "tsc"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/interfaces": "workspace:0.2.0",
"peer-id": "0.16.0",
"it-length-prefixed": "5.0.3",
"it-pipe": "1.1.0",
"@chainsafe/libp2p-noise": "4.1.1",
"libp2p": "0.36.2",
"libp2p-interfaces": "4.0.6",
"libp2p-mplex": "0.10.7",
"libp2p-websockets": "0.16.2",
"loglevel": "1.8.1",
"multiaddr": "10.0.1",
"browser-or-node": "2.0.0",
"buffer": "6.0.3"
},
"devDependencies": {
"typescript": "4.6.4"
}
}

View File

@ -1,20 +0,0 @@
/*
* Copyright 2022 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 { isBrowser } from 'browser-or-node';
import { Buffer as BufferPolyfill } from 'buffer';
export default isBrowser ? BufferPolyfill : Buffer;

View File

@ -1,14 +0,0 @@
{
"compilerOptions": {
"outDir": "./dist/",
"lib": ["ES2015"],
"target": "ES5",
"module": "commonjs",
"skipLibCheck": true,
"sourceMap": true,
"declaration": true,
"esModuleInterop": true,
},
"exclude": ["node_modules", "dist"],
"include": ["src/**/*"]
}

View File

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

View File

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

View File

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

View File

@ -1,13 +0,0 @@
## Contribute Code
You are welcome to contribute to Fluence.
Things you need to know:
1. You need to **agree to the Contributors License Agreement**. This is a common practice in all major Open Source projects. At the current moment we are unable to accept contributions made on behalf of a company. Only individual contributions will be accepted.
2. **Not all proposed contributions can be accepted**. Some features may e.g. just fit a third-party add-on better. The contribution must fit the overall direction of Fluence and really improve it. The more effort you invest, the better you should clarify in advance whether the contribution fits: the best way would be to just open an issue to discuss the contribution you plan to make.
### Contributor License Agreement
When you contribute, you have to be aware that your contribution is covered by **Apache License 2.0**, but might relicensed under few other software licenses mentioned in the **Contributor License Agreement**.
In particular you need to agree to the [Contributor License Agreement](https://gist.github.com/fluencelabs-org/3f4cbb3cc14c1c0fb9ad99d8f7316ed7). If you agree to its content, you simply have to click on the link posted by the CLA assistant as a comment to the pull request. Click it to check the CLA, then accept it on the following screen if you agree to it. CLA assistant will save this decision for upcoming contributions and will notify you if there is any change to the CLA in the meantime.

View File

@ -1,11 +0,0 @@
# FluenceJS interfaces
This package is a part of FluenceJS, the official implementation of the Fluence Peer in typescript. See the [FluenceJS repo](https://github.com/fluencelabs/fluence-js) for more info
## Contributing
While the project is still in the early stages of development, you are welcome to track progress and contribute. As the project is undergoing rapid changes, interested contributors should contact the team before embarking on larger pieces of work. All contributors should consult with and agree to our [basic contributing rules](CONTRIBUTING.md).
## License
[Apache 2.0](LICENSE)

View File

@ -1,25 +0,0 @@
{
"name": "@fluencelabs/interfaces",
"version": "0.2.0",
"description": "Fluence interfaces",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"scripts": {
"build": "tsc"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {},
"devDependencies": {
"typescript": "4.6.4",
"@fluencelabs/avm": "0.31.10",
"@fluencelabs/marine-js": "0.3.38",
"@types/node": "16.11.59",
"threads": "^1.7.0"
}
}

View File

@ -1,14 +0,0 @@
{
"compilerOptions": {
"outDir": "./dist/",
"lib": ["ES2017"],
"target": "ES5",
"module": "commonjs",
"skipLibCheck": true,
"sourceMap": true,
"declaration": true,
"esModuleInterop": true
},
"exclude": ["node_modules", "dist"],
"include": ["src/**/*"]
}

View File

@ -0,0 +1,16 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
testPathIgnorePatterns: ['dist'],
transform: {
'^.+\\.tsx?$': [
'ts-jest',
{
useESM: true,
},
],
},
};

View File

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

View File

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

View File

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

View File

@ -1,13 +0,0 @@
## Contribute Code
You are welcome to contribute to Fluence.
Things you need to know:
1. You need to **agree to the Contributors License Agreement**. This is a common practice in all major Open Source projects. At the current moment we are unable to accept contributions made on behalf of a company. Only individual contributions will be accepted.
2. **Not all proposed contributions can be accepted**. Some features may e.g. just fit a third-party add-on better. The contribution must fit the overall direction of Fluence and really improve it. The more effort you invest, the better you should clarify in advance whether the contribution fits: the best way would be to just open an issue to discuss the contribution you plan to make.
### Contributor License Agreement
When you contribute, you have to be aware that your contribution is covered by **Apache License 2.0**, but might relicensed under few other software licenses mentioned in the **Contributor License Agreement**.
In particular you need to agree to the [Contributor License Agreement](https://gist.github.com/fluencelabs-org/3f4cbb3cc14c1c0fb9ad99d8f7316ed7). If you agree to its content, you simply have to click on the link posted by the CLA assistant as a comment to the pull request. Click it to check the CLA, then accept it on the following screen if you agree to it. CLA assistant will save this decision for upcoming contributions and will notify you if there is any change to the CLA in the meantime.

View File

@ -1,6 +0,0 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testTimeout: 10000,
testPathIgnorePatterns: ['dist'],
};

View File

@ -1,59 +0,0 @@
{
"name": "@fluencelabs/js-peer",
"version": "0.1.0",
"description": "TypeScript implementation of Fluence Peer",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"scripts": {
"build": "tsc",
"compile-aqua": "aqua -i ./aqua/ -o ./src/internal/_aqua",
"test": "jest",
"test:unit": "jest --testPathPattern=src/__test__/unit",
"test:integration": "jest --testPathPattern=src/__test__/integration"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/avm": "0.32.1",
"@fluencelabs/connection": "workspace:0.2.0",
"@fluencelabs/interfaces": "workspace:0.2.0",
"@fluencelabs/keypair": "workspace:0.2.0",
"@fluencelabs/marine-js": "0.3.38",
"@fluencelabs/marine.background-runner": "workspace:0.1.0",
"async": "3.2.4",
"base64-js": "^1.5.1",
"bs58": "5.0.0",
"buffer": "6.0.3",
"cids": "1.1.9",
"loglevel": "1.8.1",
"multiformats": "9.9.0",
"peer-id": "0.16.0",
"platform": "1.3.6",
"rxjs": "7.5.5",
"ts-pattern": "3.3.3",
"uuid": "8.3.2"
},
"devDependencies": {
"@fluencelabs/marine.deps-loader.node": "workspace:0.1.0",
"@fluencelabs/aqua": "0.7.7-362",
"@fluencelabs/aqua-api": "0.9.1-373",
"@fluencelabs/aqua-lib": "0.6.0",
"@fluencelabs/fluence-network-environment": "1.0.13",
"@types/bs58": "4.0.1",
"@types/jest": "28.1.0",
"@types/platform": "1.3.4",
"@types/uuid": "8.3.2",
"jest": "28.1.0",
"jest-each": "28.1.3",
"js-base64": "3.7.2",
"multiaddr": "10.0.1",
"ts-jest": "28.0.2",
"ts-node": "10.9.1",
"typescript": "4.6.4"
}
}

View File

@ -1,42 +0,0 @@
import * as bs58 from 'bs58';
import { KeyPair } from '@fluencelabs/keypair';
describe('KeyPair tests', () => {
it('generate keypair from seed', async function () {
// arrange
const random = await KeyPair.randomEd25519();
const privateKey = random.toEd25519PrivateKey();
// act
const keyPair = await KeyPair.fromEd25519SK(privateKey);
const privateKey2 = keyPair.toEd25519PrivateKey();
// assert
expect(privateKey).toStrictEqual(privateKey2);
});
it('create keypair from ed25519 private key', async function () {
// arrange
const rustSK = 'jDaxLJzYtzgwTMrELJCAqavtmx85ktQNfB2rLcK7MhH';
const sk = bs58.decode(rustSK);
// act
const keyPair = await KeyPair.fromEd25519SK(sk);
// assert
const expectedPeerId = '12D3KooWH1W3VznVZ87JH4FwABK4mkntcspTVWJDta6c2xg9Pzbp';
expect(keyPair.Libp2pPeerId.toB58String()).toStrictEqual(expectedPeerId);
});
it('create keypair from a seed phrase', async function () {
// arrange
const seedArray = new Uint8Array(32).fill(1);
// act
const keyPair = await KeyPair.fromEd25519SK(seedArray);
// assert
const expectedPeerId = '12D3KooWK99VoVxNE7XzyBwXEzW7xhK7Gpv85r9F3V3fyKSUKPH5';
expect(keyPair.Libp2pPeerId.toB58String()).toStrictEqual(expectedPeerId);
});
});

View File

@ -1,335 +0,0 @@
import { CallParams, CallServiceData } from '../../commonTypes';
import each from 'jest-each';
import { builtInServices } from '../../builtins/common';
import { KeyPair } from '@fluencelabs/keypair';
import { Sig, defaultSigGuard } from '../../builtins/Sig';
import { toUint8Array } from 'js-base64';
import { allowServiceFn } from '../../builtins/securityGuard';
const a10b20 = `{
"a": 10,
"b": 20
}`;
const oneTwoThreeFour = `[
1,
2,
3,
4
]`;
describe('Tests for default handler', () => {
// prettier-ignore
each`
serviceId | fnName | args | retCode | result
${'op'} | ${'identity'} | ${[]} | ${0} | ${{}}
${'op'} | ${'identity'} | ${[1]} | ${0} | ${1}
${'op'} | ${'identity'} | ${[1, 2]} | ${1} | ${'identity accepts up to 1 arguments, received 2 arguments'}
${'op'} | ${'noop'} | ${[1, 2]} | ${0} | ${{}}
${'op'} | ${'array'} | ${[1, 2, 3]} | ${0} | ${[1, 2, 3]}
${'op'} | ${'array_length'} | ${[[1, 2, 3]]} | ${0} | ${3}
${'op'} | ${'array_length'} | ${[]} | ${1} | ${'array_length accepts exactly one argument, found: 0'}
${'op'} | ${'concat'} | ${[[1, 2], [3, 4], [5, 6]]} | ${0} | ${[1, 2, 3, 4, 5, 6]}
${'op'} | ${'concat'} | ${[[1, 2]]} | ${0} | ${[1, 2]}
${'op'} | ${'concat'} | ${[]} | ${0} | ${[]}
${'op'} | ${'concat'} | ${[1, [1, 2], 1]} | ${1} | ${"All arguments of 'concat' must be arrays: arguments 0, 2 are not"}
${'op'} | ${'string_to_b58'} | ${["test"]} | ${0} | ${"3yZe7d"}
${'op'} | ${'string_to_b58'} | ${["test", 1]} | ${1} | ${"string_to_b58 accepts only one string argument"}
${'op'} | ${'string_from_b58'} | ${["3yZe7d"]} | ${0} | ${"test"}
${'op'} | ${'string_from_b58'} | ${["3yZe7d", 1]} | ${1} | ${"string_from_b58 accepts only one string argument"}
${'op'} | ${'bytes_to_b58'} | ${[[116, 101, 115, 116]]} | ${0} | ${"3yZe7d"}
${'op'} | ${'bytes_to_b58'} | ${[[116, 101, 115, 116], 1]} | ${1} | ${"bytes_to_b58 accepts only single argument: array of numbers"}
${'op'} | ${'bytes_from_b58'} | ${["3yZe7d"]} | ${0} | ${[116, 101, 115, 116]}
${'op'} | ${'bytes_from_b58'} | ${["3yZe7d", 1]} | ${1} | ${"bytes_from_b58 accepts only one string argument"}
${'op'} | ${'sha256_string'} | ${["hello, world!"]} | ${0} | ${"QmVQ8pg6L1tpoWYeq6dpoWqnzZoSLCh7E96fCFXKvfKD3u"}
${'op'} | ${'sha256_string'} | ${["hello, world!", true]} | ${0} | ${"84V7ZxLW7qKsx1Qvbd63BdGaHxUc3TfT2MBPqAXM7Wyu"}
${'op'} | ${'sha256_string'} | ${[]} | ${1} | ${"sha256_string accepts 1-3 arguments, found: 0"}
${'op'} | ${'concat_strings'} | ${[]} | ${0} | ${""}
${'op'} | ${'concat_strings'} | ${["a", "b", "c"]} | ${0} | ${"abc"}
${'peer'} | ${'timeout'} | ${[200, []]} | ${0} | ${[]}}
${'peer'} | ${'timeout'} | ${[200, ['test']]} | ${0} | ${['test']}}
${'peer'} | ${'timeout'} | ${[]} | ${1} | ${'timeout accepts exactly two arguments: timeout duration in ms and a message string'}}
${'peer'} | ${'timeout'} | ${[200, 'test', 1]} | ${1} | ${'timeout accepts exactly two arguments: timeout duration in ms and a message string'}}
${'debug'} | ${'stringify'} | ${[]} | ${0} | ${'"<empty argument list>"'}}
${'debug'} | ${'stringify'} | ${[{a: 10, b: 20}]} | ${0} | ${a10b20}}
${'debug'} | ${'stringify'} | ${[1, 2, 3, 4]} | ${0} | ${oneTwoThreeFour}}
${'math'} | ${'add'}" | ${[2, 2]} | ${0} | ${4}
${'math'} | ${'add'}" | ${[2]} | ${1} | ${"Expected 2 argument(s). Got 1"}
${'math'} | ${'sub'}" | ${[2, 2]} | ${0} | ${0}
${'math'} | ${'sub'}" | ${[2, 3]} | ${0} | ${-1}
${'math'} | ${'mul'}" | ${[2, 2]} | ${0} | ${4}
${'math'} | ${'mul'}" | ${[2, 0]} | ${0} | ${0}
${'math'} | ${'mul'}" | ${[2, -1]} | ${0} | ${-2}
${'math'} | ${'fmul'}" | ${[10, 0.66]} | ${0} | ${6}
${'math'} | ${'fmul'}" | ${[0.5, 0.5]} | ${0} | ${0}
${'math'} | ${'fmul'}" | ${[100.5, 0.5]} | ${0} | ${50}
${'math'} | ${'div'}" | ${[2, 2]} | ${0} | ${1}
${'math'} | ${'div'}" | ${[2, 3]} | ${0} | ${0}
${'math'} | ${'div'}" | ${[10, 5]} | ${0} | ${2}
${'math'} | ${'rem'}" | ${[10, 3]} | ${0} | ${1}
${'math'} | ${'pow'}" | ${[2, 2]} | ${0} | ${4}
${'math'} | ${'pow'}" | ${[2, 0]} | ${0} | ${1}
${'math'} | ${'log'}" | ${[2, 2]} | ${0} | ${1}
${'math'} | ${'log'}" | ${[2, 4]} | ${0} | ${2}
${'cmp'} | ${'gt'}" | ${[2, 4]} | ${0} | ${false}
${'cmp'} | ${'gte'}" | ${[2, 4]} | ${0} | ${false}
${'cmp'} | ${'gte'}" | ${[4, 2]} | ${0} | ${true}
${'cmp'} | ${'gte'}" | ${[2, 2]} | ${0} | ${true}
${'cmp'} | ${'lt'}" | ${[2, 4]} | ${0} | ${true}
${'cmp'} | ${'lte'}" | ${[2, 4]} | ${0} | ${true}
${'cmp'} | ${'lte'}" | ${[4, 2]} | ${0} | ${false}
${'cmp'} | ${'lte'}" | ${[2, 2]} | ${0} | ${true}
${'cmp'} | ${'cmp'}" | ${[2, 4]} | ${0} | ${-1}
${'cmp'} | ${'cmp'}" | ${[2, -4]} | ${0} | ${1}
${'cmp'} | ${'cmp'}" | ${[2, 2]} | ${0} | ${0}
${'array'} | ${'sum'}" | ${[[1, 2, 3]]} | ${0} | ${6}
${'array'} | ${'dedup'}" | ${[["a", "a", "b", "c", "a", "b", "c"]]} | ${0} | ${["a", "b", "c"]}
${'array'} | ${'intersect'}" | ${[["a", "b", "c"], ["c", "b", "d"]]} | ${0} | ${["b", "c"]}
${'array'} | ${'diff'}" | ${[["a", "b", "c"], ["c", "b", "d"]]} | ${0} | ${["a"]}
${'array'} | ${'sdiff'}" | ${[["a", "b", "c"], ["c", "b", "d"]]} | ${0} | ${["a", "d"]}
${'json'} | ${'obj'}" | ${["a", 10, "b", "string", "c", null]} | ${0} | ${{a: 10, b: "string", c: null}}
${'json'} | ${'obj'}" | ${["a", 10, "b", "string", "c"]} | ${1} | ${"Expected even number of argument(s). Got 5"}
${'json'} | ${'obj'}" | ${[]} | ${0} | ${{}}
${'json'} | ${'put'}" | ${[{}, "a", 10]} | ${0} | ${{a: 10}}
${'json'} | ${'put'}" | ${[{b: 11}, "a", 10]} | ${0} | ${{a: 10, b: 11}}
${'json'} | ${'put'}" | ${["a", "a", 11]} | ${1} | ${"Argument 0 expected to be of type object, Got string"}
${'json'} | ${'put'}" | ${[{}, "a", 10, "b", 20]} | ${1} | ${"Expected 3 argument(s). Got 5"}
${'json'} | ${'put'}" | ${[{}]} | ${1} | ${"Expected 3 argument(s). Got 1"}
${'json'} | ${'puts'}" | ${[{}, "a", 10]} | ${0} | ${{a: 10}}
${'json'} | ${'puts'}" | ${[{b: 11}, "a", 10]} | ${0} | ${{a: 10, b: 11}}
${'json'} | ${'puts'}" | ${[{}, "a", 10, "b", "string", "c", null]} | ${0} | ${{a: 10, b: "string", c: null}}
${'json'} | ${'puts'}" | ${[{x: "text"}, "a", 10, "b", "string"]} | ${0} | ${{a: 10, b: "string", x: "text"}}
${'json'} | ${'puts'}" | ${[{}]} | ${1} | ${"Expected more than 3 argument(s). Got 1"}
${'json'} | ${'puts'}" | ${["a", "a", 11]} | ${1} | ${"Argument 0 expected to be of type object, Got string"}
${'json'} | ${'stringify'}" | ${[{a: 10, b: "string", c: null}]} | ${0} | ${"{\"a\":10,\"b\":\"string\",\"c\":null}"}
${'json'} | ${'stringify'}" | ${[1]} | ${1} | ${"Argument 0 expected to be of type object, Got number"}
${'json'} | ${'parse'}" | ${["{\"a\":10,\"b\":\"string\",\"c\":null}"]} | ${0} | ${{a: 10, b: "string", c: null}}
${'json'} | ${'parse'}" | ${["incorrect"]} | ${1} | ${"Unexpected token i in JSON at position 0"}
${'json'} | ${'parse'}" | ${[10]} | ${1} | ${"Argument 0 expected to be of type string, Got number"}
`.test(
//
'$fnName with $args expected retcode: $retCode and result: $result',
async ({ serviceId, fnName, args, retCode, result }) => {
// arrange
const req: CallServiceData = {
serviceId: serviceId,
fnName: fnName,
args: args,
tetraplets: [],
particleContext: {
particleId: 'some',
initPeerId: 'init peer id',
timestamp: 595951200,
ttl: 595961200,
signature: 'sig',
},
};
// act
const fn = builtInServices[req.serviceId][req.fnName];
const res = await fn(req);
// assert
expect(res).toMatchObject({
retCode: retCode,
result: result,
});
},
);
it('should return correct error message for identiy service', async () => {
// arrange
const req: CallServiceData = {
serviceId: 'peer',
fnName: 'identify',
args: [],
tetraplets: [],
particleContext: {
particleId: 'some',
initPeerId: 'init peer id',
timestamp: 595951200,
ttl: 595961200,
signature: 'sig',
},
};
// act
const fn = builtInServices[req.serviceId][req.fnName];
const res = await fn(req);
// assert
expect(res).toMatchObject({
retCode: 0,
result: {
external_addresses: [],
node_version: expect.stringContaining('js'),
air_version: expect.stringContaining('js'),
},
});
});
});
const key = '+cmeYlZKj+MfSa9dpHV+BmLPm6wq4inGlsPlQ1GvtPk=';
const context = (async () => {
const keyBytes = toUint8Array(key);
const kp = await KeyPair.fromEd25519SK(keyBytes);
const res = {
peerKeyPair: kp,
peerId: kp.Libp2pPeerId.toB58String(),
};
return res;
})();
const testData = [1, 2, 3, 4, 5, 6, 7, 9, 10];
// signature produced by KeyPair created from key above (`key` variable)
const testDataSig = [
224, 104, 245, 206, 140, 248, 27, 72, 68, 133, 111, 10, 164, 197, 242, 132, 107, 77, 224, 67, 99, 106, 76, 29, 144,
121, 122, 169, 36, 173, 58, 80, 170, 102, 137, 253, 157, 247, 168, 87, 162, 223, 188, 214, 203, 220, 52, 246, 29,
86, 77, 71, 224, 248, 16, 213, 254, 75, 78, 239, 243, 222, 241, 15,
];
// signature produced by KeyPair created from some random KeyPair
const testDataWrongSig = [
116, 247, 189, 118, 236, 53, 147, 123, 219, 75, 176, 105, 101, 108, 233, 137, 97, 14, 146, 132, 252, 70, 51, 153,
237, 167, 156, 150, 36, 90, 229, 108, 166, 231, 255, 137, 8, 246, 125, 0, 213, 150, 83, 196, 237, 221, 131, 159,
157, 159, 25, 109, 95, 160, 181, 65, 254, 238, 47, 156, 240, 151, 58, 14,
];
const makeTetraplet = (initPeerId: string, serviceId?: string, fnName?: string): CallParams<'data'> => {
return {
initPeerId: initPeerId,
tetraplets: {
data: [
{
function_name: fnName,
service_id: serviceId,
},
],
},
} as any;
};
describe('Sig service tests', () => {
it('sig.sign should create the correct signature', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
const res = await sig.sign(testData, makeTetraplet(ctx.peerId));
expect(res.success).toBe(true);
expect(res.signature).toStrictEqual(testDataSig);
});
it('sig.verify should return true for the correct signature', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
const res = await sig.verify(testDataSig, testData);
expect(res).toBe(true);
});
it('sig.verify should return false for the incorrect signature', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
const res = await sig.verify(testDataWrongSig, testData);
expect(res).toBe(false);
});
it('sign-verify call chain should work', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
const signature = await sig.sign(testData, makeTetraplet(ctx.peerId));
const res = await sig.verify(signature.signature as number[], testData);
expect(res).toBe(true);
});
it('sig.sign with defaultSigGuard should work for correct callParams', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
sig.securityGuard = defaultSigGuard(ctx.peerId);
const signature = await sig.sign(testData, makeTetraplet(ctx.peerId, 'registry', 'get_route_bytes'));
await expect(signature).toBeDefined();
});
it('sig.sign with defaultSigGuard should not allow particles initiated from incorrect service', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
sig.securityGuard = defaultSigGuard(ctx.peerId);
const res = await sig.sign(testData, makeTetraplet(ctx.peerId, 'other_service', 'other_fn'));
await expect(res.success).toBe(false);
await expect(res.error).toBe('Security guard validation failed');
});
it('sig.sign with defaultSigGuard should not allow particles initiated from other peers', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
sig.securityGuard = defaultSigGuard(ctx.peerId);
const res = await sig.sign(
testData,
makeTetraplet((await KeyPair.randomEd25519()).getPeerId(), 'registry', 'get_key_bytes'),
);
await expect(res.success).toBe(false);
await expect(res.error).toBe('Security guard validation failed');
});
it('changing securityGuard should work', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
sig.securityGuard = allowServiceFn('test', 'test');
const successful1 = await sig.sign(testData, makeTetraplet(ctx.peerId, 'test', 'test'));
const unSuccessful1 = await sig.sign(testData, makeTetraplet(ctx.peerId, 'wrong', 'wrong'));
sig.securityGuard = allowServiceFn('wrong', 'wrong');
const successful2 = await sig.sign(testData, makeTetraplet(ctx.peerId, 'wrong', 'wrong'));
const unSuccessful2 = await sig.sign(testData, makeTetraplet(ctx.peerId, 'test', 'test'));
expect(successful1.success).toBe(true);
expect(successful2.success).toBe(true);
expect(unSuccessful1.success).toBe(false);
expect(unSuccessful2.success).toBe(false);
});
});

View File

@ -1,21 +0,0 @@
{
"compilerOptions": {
"outDir": "./dist/",
"baseUrl": ".",
"downlevelIteration": true,
"sourceMap": true,
"inlineSources": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"declaration": true,
"esModuleInterop": true,
"declarationMap": true,
"strict": true,
"skipLibCheck": true
},
"exclude": ["node_modules", "dist", "bundle"],
"include": ["src/**/*"]
}

View File

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

View File

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

View File

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

View File

@ -1,13 +0,0 @@
## Contribute Code
You are welcome to contribute to Fluence.
Things you need to know:
1. You need to **agree to the Contributors License Agreement**. This is a common practice in all major Open Source projects. At the current moment we are unable to accept contributions made on behalf of a company. Only individual contributions will be accepted.
2. **Not all proposed contributions can be accepted**. Some features may e.g. just fit a third-party add-on better. The contribution must fit the overall direction of Fluence and really improve it. The more effort you invest, the better you should clarify in advance whether the contribution fits: the best way would be to just open an issue to discuss the contribution you plan to make.
### Contributor License Agreement
When you contribute, you have to be aware that your contribution is covered by **Apache License 2.0**, but might relicensed under few other software licenses mentioned in the **Contributor License Agreement**.
In particular you need to agree to the [Contributor License Agreement](https://gist.github.com/fluencelabs-org/3f4cbb3cc14c1c0fb9ad99d8f7316ed7). If you agree to its content, you simply have to click on the link posted by the CLA assistant as a comment to the pull request. Click it to check the CLA, then accept it on the following screen if you agree to it. CLA assistant will save this decision for upcoming contributions and will notify you if there is any change to the CLA in the meantime.

View File

@ -1,25 +0,0 @@
{
"name": "@fluencelabs/keypair",
"version": "0.2.0",
"description": "Keypair implementation for Fluence JS Peer",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"scripts": {
"build": "tsc"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"peer-id": "0.16.0",
"libp2p-crypto": "0.21.2",
"js-base64": "3.7.2"
},
"devDependencies": {
"typescript": "4.6.4"
}
}

View File

@ -1,12 +0,0 @@
{
"compilerOptions": {
"outDir": "./dist/",
"lib": ["ES2015"],
"target": "ES5",
"sourceMap": true,
"declaration": true,
"module": "commonjs",
},
"exclude": ["node_modules", "dist"],
"include": ["src/**/*"]
}

View File

@ -0,0 +1,69 @@
{
"name": "@fluencelabs/js-peer",
"version": "0.1.0",
"description": "TypeScript implementation of Fluence Peer",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"engines": {
"node": ">=10",
"pnpm": ">=3"
},
"type": "module",
"scripts": {
"build": "tsc",
"compile-aqua": "aqua -i ./aqua/ -o ./src/internal/_aqua",
"test:smoke": "node ./dist/js-peer/__test__/integration/smokeTest.js",
"test": "NODE_OPTIONS=--experimental-vm-modules pnpm jest",
"test:unit": "NODE_OPTIONS=--experimental-vm-modules pnpm jest --testPathPattern=src/__test__/unit",
"test:integration": "NODE_OPTIONS=--experimental-vm-modules pnpm jest --testPathPattern=src/__test__/integration"
},
"repository": "https://github.com/fluencelabs/fluence-js",
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/avm": "0.31.10",
"@fluencelabs/marine-js": "0.3.44",
"multiformats": "11.0.1",
"async": "3.2.4",
"bs58": "5.0.0",
"buffer": "6.0.3",
"loglevel": "1.8.1",
"@libp2p/peer-id": "2.0.1",
"platform": "1.3.6",
"rxjs": "7.5.5",
"ts-pattern": "3.3.3",
"uuid": "8.3.2",
"threads": "1.7.0",
"@libp2p/crypto": "1.0.8",
"@libp2p/peer-id-factory": "2.0.1",
"@libp2p/interface-peer-id": "2.0.1",
"@libp2p/interface-keys": "1.0.7",
"js-base64": "3.7.2",
"browser-or-node": "2.0.0",
"it-length-prefixed": "8.0.4",
"it-pipe": "2.0.5",
"it-map": "2.0.0",
"uint8arrays": "4.0.3",
"@chainsafe/libp2p-noise": "11.0.0",
"libp2p": "0.42.2",
"@libp2p/interfaces": "3.3.1",
"@libp2p/interface-connection": "3.0.8",
"@libp2p/mplex": "7.1.1",
"@libp2p/websockets": "5.0.3",
"@multiformats/multiaddr": "11.3.0"
},
"devDependencies": {
"@types/node": "16.11.59",
"@fluencelabs/aqua": "0.7.7-362",
"@fluencelabs/aqua-api": "0.9.1-373",
"@fluencelabs/aqua-lib": "0.6.0",
"@fluencelabs/fluence-network-environment": "1.0.13",
"@multiformats/multiaddr": "11.3.0",
"@types/bs58": "4.0.1",
"@types/platform": "1.3.4",
"@types/uuid": "8.3.2",
"@types/jest": "29.4.0",
"jest": "29.4.1",
"ts-jest": "29.0.5"
}
}

View File

@ -13,23 +13,25 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FluenceConnection, ParticleHandler, PeerIdB58 } from '@fluencelabs/interfaces';
// @ts-ignore
import Websockets from 'libp2p-websockets';
// @ts-ignore
import Mplex from 'libp2p-mplex';
import Lib2p2Peer from 'libp2p';
import { decode, encode } from 'it-length-prefixed';
import { FluenceConnection, ParticleHandler, PeerIdB58 } from '../interfaces/index.js';
import { pipe } from 'it-pipe';
import * as log from 'loglevel';
import { Noise } from '@chainsafe/libp2p-noise';
import PeerId from 'peer-id';
import type { MultiaddrInput } from 'multiaddr';
import { Connection } from 'libp2p-interfaces/src/topology';
import { Multiaddr } from 'multiaddr';
// @ts-ignore
import { all as allow_all } from 'libp2p-websockets/src/filters';
import Buffer from './Buffer';
import { encode, decode } from 'it-length-prefixed';
import type { PeerId } from '@libp2p/interface-peer-id';
import { createLibp2p, Libp2p } from 'libp2p';
import { noise } from '@chainsafe/libp2p-noise';
import { mplex } from '@libp2p/mplex';
import { webSockets } from '@libp2p/websockets';
import { all } from '@libp2p/websockets/filters';
import { multiaddr } from '@multiformats/multiaddr';
import type { MultiaddrInput, Multiaddr } from '@multiformats/multiaddr';
import type { Connection } from '@libp2p/interface-connection';
import map from 'it-map';
import { fromString } from 'uint8arrays/from-string';
import { toString } from 'uint8arrays/to-string';
import log from 'loglevel';
export const PROTOCOL_NAME = '/fluence/particle/2.0.0';
@ -53,47 +55,43 @@ export interface FluenceConnectionOptions {
dialTimeoutMs?: number;
}
/*
/**
* Implementation for JS peers which connects to Fluence through relay node
*/
export class RelayConnection extends FluenceConnection {
constructor(
public peerId: PeerIdB58,
private _lib2p2Peer: Lib2p2Peer,
private _lib2p2Peer: Libp2p,
private _relayAddress: Multiaddr,
public readonly relayPeerId: PeerIdB58,
) {
super();
}
private _connection?: Connection;
static async createConnection(options: FluenceConnectionOptions): Promise<RelayConnection> {
const transportKey = Websockets.prototype[Symbol.toStringTag];
const lib2p2Peer = await Lib2p2Peer.create({
const lib2p2Peer = await createLibp2p({
peerId: options.peerId,
modules: {
transport: [Websockets],
streamMuxer: [Mplex],
connEncryption: [new Noise()],
},
config: {
transport: {
[transportKey]: {
filter: allow_all,
},
},
},
dialer: {
dialTimeout: options?.dialTimeoutMs,
},
transports: [
webSockets({
filter: all,
}),
],
streamMuxers: [mplex()],
connectionEncryption: [noise()],
});
const relayMultiaddr = new Multiaddr(options.relayAddress);
const relayMultiaddr = multiaddr(options.relayAddress);
const relayPeerId = relayMultiaddr.getPeerId();
if (relayPeerId === null) {
throw new Error('Specified multiaddr is invalid or missing peer id: ' + options.relayAddress);
}
return new RelayConnection(
// force new line
options.peerId.toB58String(),
options.peerId.toString(),
lib2p2Peer,
relayMultiaddr,
relayPeerId,
@ -113,18 +111,22 @@ export class RelayConnection extends FluenceConnection {
)} instead.`,
);
}
/*
TODO:: find out why this doesn't work and a new connection has to be established each time
if (this._connection.streams.length !== 1) {
throw new Error('Incorrect number of streams in FluenceConnection');
}
const sink = this._connection.streams[0].sink;
*/
const conn = await this._lib2p2Peer.dialProtocol(this._relayAddress, PROTOCOL_NAME);
const sink = conn.stream.sink;
const stream = await this._lib2p2Peer.dialProtocol(this._relayAddress, PROTOCOL_NAME);
const sink = stream.sink;
pipe(
// force new line
[Buffer.from(particle, 'utf8')],
[fromString(particle)],
// @ts-ignore
encode(),
sink,
);
@ -138,7 +140,9 @@ export class RelayConnection extends FluenceConnection {
stream.source,
// @ts-ignore
decode(),
async (source: AsyncIterable<string>) => {
// @ts-ignore
(source) => map(source, (buf) => toString(buf.subarray())),
async (source) => {
try {
for await (const msg of source) {
try {
@ -153,7 +157,10 @@ export class RelayConnection extends FluenceConnection {
},
);
});
log.debug(`dialing to the node with client's address: ` + this._lib2p2Peer.peerId.toB58String());
log.debug(`dialing to the node with client's address: ` + this._lib2p2Peer.peerId.toString());
try {
this._connection = await this._lib2p2Peer.dial(this._relayAddress);
} catch (e: any) {

View File

@ -14,7 +14,7 @@
* limitations under the License.
*/
import type { JSONArray, JSONObject, LogLevel } from '@fluencelabs/marine-js';
import type { JSONArray, JSONObject, LogLevel } from '@fluencelabs/marine-js/dist/types';
import type { RunParameters, CallResultsArray, InterpreterResult } from '@fluencelabs/avm';
import type { WorkerImplementation } from 'threads/dist/types/master';
export type PeerIdB58 = string;

View File

@ -15,26 +15,26 @@
*/
import 'buffer';
import { RelayConnection } from '@fluencelabs/connection';
import { FluenceConnection, IAvmRunner, IMarine } from '@fluencelabs/interfaces';
import { KeyPair } from '@fluencelabs/keypair';
import type { MultiaddrInput } from 'multiaddr';
import { CallServiceData, CallServiceResult, GenericCallServiceHandler, ResultCodes } from './commonTypes';
import { PeerIdB58 } from './commonTypes';
import { Particle, ParticleExecutionStage, ParticleQueueItem } from './Particle';
import { throwIfNotSupported, dataToString, jsonify, isString, ServiceError } from './utils';
import { RelayConnection } from '../connection/index.js';
import { FluenceConnection, IAvmRunner, IMarine } from '../interfaces/index.js';
import { KeyPair } from '../keypair/index.js';
import type { MultiaddrInput } from '@multiformats/multiaddr';
import { CallServiceData, CallServiceResult, GenericCallServiceHandler, ResultCodes } from './commonTypes.js';
import { PeerIdB58 } from './commonTypes.js';
import { Particle, ParticleExecutionStage, ParticleQueueItem } from './Particle.js';
import { throwIfNotSupported, dataToString, jsonify, isString, ServiceError } from './utils.js';
import { concatMap, filter, pipe, Subject, tap } from 'rxjs';
import log from 'loglevel';
import { builtInServices } from './builtins/common';
import { defaultSigGuard, Sig } from './builtins/Sig';
import { registerSig } from './_aqua/services';
import { registerSrv } from './_aqua/single-module-srv';
import { builtInServices } from './builtins/common.js';
import { defaultSigGuard, Sig } from './builtins/Sig.js';
import { registerSig } from './_aqua/services.js';
import { registerSrv } from './_aqua/single-module-srv.js';
import { Buffer } from 'buffer';
import { JSONValue } from '@fluencelabs/avm';
import { NodeUtils, Srv } from './builtins/SingleModuleSrv';
import { registerNodeUtils } from './_aqua/node-utils';
import { LogLevel } from '@fluencelabs/marine-js';
import { NodeUtils, Srv } from './builtins/SingleModuleSrv.js';
import { registerNodeUtils } from './_aqua/node-utils.js';
import { LogLevel } from '@fluencelabs/marine-js/dist/types';
/**
* Node of the Fluence network specified as a pair of node's multiaddr and it's peer id
@ -210,7 +210,7 @@ export class FluencePeer {
if (this.connection === null) {
return {
isInitialized: true,
peerId: this._keyPair.Libp2pPeerId.toB58String(),
peerId: this._keyPair.getPeerId(),
isConnected: false,
relayPeerId: null,
};
@ -219,7 +219,7 @@ export class FluencePeer {
if (this.connection.relayPeerId === null) {
return {
isInitialized: true,
peerId: this._keyPair.Libp2pPeerId.toB58String(),
peerId: this._keyPair.getPeerId(),
isConnected: true,
isDirect: true,
relayPeerId: null,
@ -228,7 +228,7 @@ export class FluencePeer {
return {
isInitialized: true,
peerId: this._keyPair.Libp2pPeerId.toB58String(),
peerId: this._keyPair.getPeerId(),
isConnected: true,
relayPeerId: this.connection.relayPeerId,
};
@ -422,7 +422,7 @@ export class FluencePeer {
async init(config: PeerConfig & Required<Pick<PeerConfig, 'KeyPair'>>) {
this._keyPair = config.KeyPair;
const peerId = this._keyPair.Libp2pPeerId.toB58String();
const peerId = this._keyPair.getPeerId();
if (config?.debug?.printParticleId) {
this._printParticleId = true;
@ -797,7 +797,7 @@ async function configToConnection(
}
const res = await RelayConnection.createConnection({
peerId: keyPair.Libp2pPeerId,
peerId: keyPair.getLibp2pPeerId(),
relayAddress: connectToMultiAddr,
dialTimeoutMs: dialTimeoutMs,
});

View File

@ -13,12 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { fromUint8Array, toUint8Array } from 'js-base64';
import { CallResultsArray, LogLevel } from '@fluencelabs/avm';
import { v4 as uuidv4 } from 'uuid';
import { fromByteArray, toByteArray } from 'base64-js';
import log from 'loglevel';
import { ParticleContext } from './commonTypes';
import { dataToString, jsonify } from './utils';
import { ParticleContext } from './commonTypes.js';
import { dataToString, jsonify } from './utils.js';
import { Buffer } from 'buffer';
export class Particle {
@ -45,7 +46,7 @@ export class Particle {
json.id,
json.timestamp,
json.script,
toByteArray(json.data),
toUint8Array(json.data),
json.ttl,
json.init_peer_id,
);
@ -91,7 +92,7 @@ export class Particle {
script: this.script,
// TODO: copy signature from a particle after signatures will be implemented on nodes
signature: [],
data: this.data && fromByteArray(this.data),
data: this.data && fromUint8Array(this.data),
});
}

View File

@ -1,5 +1,5 @@
import { handleTimeout } from '../../utils';
import { registerHandlersHelper, withPeer } from '../util';
import { handleTimeout } from '../../utils.js';
import { registerHandlersHelper, withPeer } from '../util.js';
describe('Avm spec', () => {
it('Simple call', async () => {

View File

@ -1,7 +1,7 @@
import { Particle } from '../../Particle';
import { doNothing } from '../../utils';
import { FluencePeer } from '../../FluencePeer';
import { mkTestPeer } from '../util';
import { Particle } from '../../Particle.js';
import { doNothing } from '../../utils.js';
import { FluencePeer } from '../../FluencePeer.js';
import { mkTestPeer } from '../util.js';
let peer: FluencePeer;

View File

@ -1,19 +1,21 @@
import fs from 'fs';
import path from 'path';
import { compileAqua, withPeer } from '../util';
import * as fs from 'fs';
import * as url from 'url';
import * as path from 'path';
import { compileAqua, withPeer } from '../util.js';
let aqua: any;
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
describe('Marine js tests', () => {
beforeAll(async () => {
const { services, functions } = await compileAqua(path.join(__dirname, './marine-js.aqua'));
const { services, functions } = await compileAqua(path.join(__dirname, '../data/marine-js.aqua'));
aqua = functions;
});
it('should call marine service correctly', async () => {
await withPeer(async (peer) => {
// arrange
const wasm = await fs.promises.readFile(__dirname + '/greeting.wasm');
const wasm = await fs.promises.readFile(path.join(__dirname, '../data/greeting.wasm'));
await peer.registerMarineService(wasm, 'greeting');
// act
@ -37,7 +39,7 @@ describe('Marine js tests', () => {
marineLogLevel: 'debug',
},
});
const wasm = await fs.promises.readFile(__dirname + '/greeting-record.wasm');
const wasm = await fs.promises.readFile(path.join(__dirname, '../data/greeting-record.wasm'));
await peer.registerMarineService(wasm, 'greeting');
// act

View File

@ -1,9 +1,7 @@
import { Multiaddr } from 'multiaddr';
import { nodes } from '../connection';
import { checkConnection, doNothing, handleTimeout } from '../../utils';
import { registerHandlersHelper, mkTestPeer, withPeer, withConnectedPeer } from '../util';
import { FluencePeer } from '../../FluencePeer';
import { nodes } from '../connection.js';
import { checkConnection, doNothing, handleTimeout } from '../../utils.js';
import { registerHandlersHelper, mkTestPeer, withPeer, withConnectedPeer } from '../util.js';
import { FluencePeer } from '../../FluencePeer.js';
describe('Typescript usage suite', () => {
it('should perform test for FluencePeer class correctly', () => {

View File

@ -1,9 +1,12 @@
import path from 'path';
import { KeyPair } from '@fluencelabs/keypair';
import { allowServiceFn } from '../../builtins/securityGuard';
import { Sig } from '../../builtins/Sig';
import { compileAqua, withPeer } from '../util';
import { registerServiceImpl } from '../../compilerSupport/registerService';
import * as path from 'path';
import * as url from 'url';
import { KeyPair } from '../../../keypair/index.js';
import { allowServiceFn } from '../../builtins/securityGuard.js';
import { Sig } from '../../builtins/Sig.js';
import { compileAqua, withPeer } from '../util.js';
import { registerServiceImpl } from '../../compilerSupport/registerService.js';
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
let aqua: any;
let sigDef: any;
@ -11,7 +14,7 @@ let dataProviderDef: any;
describe('Sig service test suite', () => {
beforeAll(async () => {
const { services, functions } = await compileAqua(path.join(__dirname, './sigService.aqua'));
const { services, functions } = await compileAqua(path.join(__dirname, '../data/sigService.aqua'));
aqua = functions;
sigDef = services.Sig;
dataProviderDef = services.DataProvider;

View File

@ -0,0 +1,67 @@
import { handleTimeout } from '../../utils.js';
import { nodes } from '../connection.js';
import { mkTestPeer, registerHandlersHelper } from '../util.js';
const smokeTest = async () => {
// arrange
const peer = mkTestPeer();
await peer.start({
connectTo: nodes[0],
});
const result = await new Promise<string[]>((resolve, reject) => {
const script = `
(xor
(seq
(call %init_peer_id% ("load" "relay") [] init_relay)
(seq
(call init_relay ("op" "identity") ["hello world!"] result)
(call %init_peer_id% ("callback" "callback") [result])
)
)
(seq
(call init_relay ("op" "identity") [])
(call %init_peer_id% ("callback" "error") [%last_error%])
)
)`;
const particle = peer.internals.createNewParticle(script);
if (particle instanceof Error) {
return reject(particle.message);
}
registerHandlersHelper(peer, particle, {
load: {
relay: () => {
return peer.getStatus().relayPeerId;
},
},
callback: {
callback: (args: any) => {
const [val] = args;
resolve(val);
},
error: (args: any) => {
const [error] = args;
reject(error);
},
},
});
peer.internals.initiateParticle(particle, handleTimeout(reject));
});
await peer.stop();
if (result[0] !== 'hello world!') {
throw new Error('Expecting "hello wrold!" got ' + result[0]);
}
};
smokeTest()
.then(() => {
console.log('Test passed');
})
.catch((err) => {
console.error('Test failed: ', err);
});

View File

@ -1,18 +1,20 @@
import path from 'path';
import { compileAqua, withPeer } from '../util';
import * as path from 'path';
import * as url from 'url';
import { compileAqua, withPeer } from '../util.js';
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
let aqua: any;
describe('Srv service test suite', () => {
beforeAll(async () => {
const { services, functions } = await compileAqua(path.join(__dirname, './srv.aqua'));
const { services, functions } = await compileAqua(path.join(__dirname, '../data/srv.aqua'));
aqua = functions;
});
it('Use custom srv service, success path', async () => {
await withPeer(async (peer) => {
// arrange
const wasm = path.join(__dirname, './greeting.wasm');
const wasm = path.join(__dirname, '../data/greeting.wasm');
// act
const res = await aqua.happy_path(peer, { file_path: wasm });
@ -25,7 +27,7 @@ describe('Srv service test suite', () => {
it('List deployed services', async () => {
await withPeer(async (peer) => {
// arrange
const wasm = path.join(__dirname, './greeting.wasm');
const wasm = path.join(__dirname, '../data/greeting.wasm');
// act
const res = await aqua.list_services(peer, { file_path: wasm });
@ -38,7 +40,7 @@ describe('Srv service test suite', () => {
it('Correct error for removed services', async () => {
await withPeer(async (peer) => {
// arrange
const wasm = path.join(__dirname, './greeting.wasm');
const wasm = path.join(__dirname, '../data/greeting.wasm');
// act
const res = await aqua.service_removed(peer, { file_path: wasm });

View File

@ -1,4 +1,4 @@
import { mkTestPeer } from '../util';
import { mkTestPeer } from '../util.js';
const peer = mkTestPeer();

View File

@ -0,0 +1,304 @@
import { toUint8Array } from 'js-base64';
import { CallParams, CallServiceData } from '../../commonTypes.js';
import { builtInServices } from '../../builtins/common.js';
import { KeyPair } from '../../../keypair/index.js';
import { Sig, defaultSigGuard } from '../../builtins/Sig.js';
import { allowServiceFn } from '../../builtins/securityGuard.js';
const a10b20 = `{
"a": 10,
"b": 20
}`;
const oneTwoThreeFour = `[
1,
2,
3,
4
]`;
describe('Tests for default handler', () => {
test.each`
serviceId | fnName | args | retCode | result
${'op'} | ${'identity'} | ${[]} | ${0} | ${{}}
${'op'} | ${'identity'} | ${[1]} | ${0} | ${1}
${'op'} | ${'identity'} | ${[1, 2]} | ${1} | ${'identity accepts up to 1 arguments, received 2 arguments'}
${'op'} | ${'noop'} | ${[1, 2]} | ${0} | ${{}}
${'op'} | ${'array'} | ${[1, 2, 3]} | ${0} | ${[1, 2, 3]}
${'op'} | ${'array_length'} | ${[[1, 2, 3]]} | ${0} | ${3}
${'op'} | ${'array_length'} | ${[]} | ${1} | ${'array_length accepts exactly one argument, found: 0'}
${'op'} | ${'concat'} | ${[[1, 2], [3, 4], [5, 6]]} | ${0} | ${[1, 2, 3, 4, 5, 6]}
${'op'} | ${'concat'} | ${[[1, 2]]} | ${0} | ${[1, 2]}
${'op'} | ${'concat'} | ${[]} | ${0} | ${[]}
${'op'} | ${'concat'} | ${[1, [1, 2], 1]} | ${1} | ${"All arguments of 'concat' must be arrays: arguments 0, 2 are not"}
${'op'} | ${'string_to_b58'} | ${['test']} | ${0} | ${'3yZe7d'}
${'op'} | ${'string_to_b58'} | ${['test', 1]} | ${1} | ${'string_to_b58 accepts only one string argument'}
${'op'} | ${'string_from_b58'} | ${['3yZe7d']} | ${0} | ${'test'}
${'op'} | ${'string_from_b58'} | ${['3yZe7d', 1]} | ${1} | ${'string_from_b58 accepts only one string argument'}
${'op'} | ${'bytes_to_b58'} | ${[[116, 101, 115, 116]]} | ${0} | ${'3yZe7d'}
${'op'} | ${'bytes_to_b58'} | ${[[116, 101, 115, 116], 1]} | ${1} | ${'bytes_to_b58 accepts only single argument: array of numbers'}
${'op'} | ${'bytes_from_b58'} | ${['3yZe7d']} | ${0} | ${[116, 101, 115, 116]}
${'op'} | ${'bytes_from_b58'} | ${['3yZe7d', 1]} | ${1} | ${'bytes_from_b58 accepts only one string argument'}
${'op'} | ${'sha256_string'} | ${['hello, world!']} | ${0} | ${'QmVQ8pg6L1tpoWYeq6dpoWqnzZoSLCh7E96fCFXKvfKD3u'}
${'op'} | ${'sha256_string'} | ${['hello, world!', true]} | ${0} | ${'84V7ZxLW7qKsx1Qvbd63BdGaHxUc3TfT2MBPqAXM7Wyu'}
${'op'} | ${'sha256_string'} | ${[]} | ${1} | ${'sha256_string accepts 1-3 arguments, found: 0'}
${'op'} | ${'concat_strings'} | ${[]} | ${0} | ${''}
${'op'} | ${'concat_strings'} | ${['a', 'b', 'c']} | ${0} | ${'abc'}
${'peer'} | ${'timeout'} | ${[200, []]} | ${0} | ${[]}
${'peer'} | ${'timeout'} | ${[200, ['test']]} | ${0} | ${['test']}
${'peer'} | ${'timeout'} | ${[]} | ${1} | ${'timeout accepts exactly two arguments: timeout duration in ms and a message string'}
${'peer'} | ${'timeout'} | ${[200, 'test', 1]} | ${1} | ${'timeout accepts exactly two arguments: timeout duration in ms and a message string'}
${'debug'} | ${'stringify'} | ${[]} | ${0} | ${'"<empty argument list>"'}
${'debug'} | ${'stringify'} | ${[{ a: 10, b: 20 }]} | ${0} | ${a10b20}
${'debug'} | ${'stringify'} | ${[1, 2, 3, 4]} | ${0} | ${oneTwoThreeFour}
${'math'} | ${'add'} | ${[2, 2]} | ${0} | ${4}
${'math'} | ${'add'} | ${[2]} | ${1} | ${'Expected 2 argument(s). Got 1'}
${'math'} | ${'sub'} | ${[2, 2]} | ${0} | ${0}
${'math'} | ${'sub'} | ${[2, 3]} | ${0} | ${-1}
${'math'} | ${'mul'} | ${[2, 2]} | ${0} | ${4}
${'math'} | ${'mul'} | ${[2, 0]} | ${0} | ${0}
${'math'} | ${'mul'} | ${[2, -1]} | ${0} | ${-2}
${'math'} | ${'fmul'} | ${[10, 0.66]} | ${0} | ${6}
${'math'} | ${'fmul'} | ${[0.5, 0.5]} | ${0} | ${0}
${'math'} | ${'fmul'} | ${[100.5, 0.5]} | ${0} | ${50}
${'math'} | ${'div'} | ${[2, 2]} | ${0} | ${1}
${'math'} | ${'div'} | ${[2, 3]} | ${0} | ${0}
${'math'} | ${'div'} | ${[10, 5]} | ${0} | ${2}
${'math'} | ${'rem'} | ${[10, 3]} | ${0} | ${1}
${'math'} | ${'pow'} | ${[2, 2]} | ${0} | ${4}
${'math'} | ${'pow'} | ${[2, 0]} | ${0} | ${1}
${'math'} | ${'log'} | ${[2, 2]} | ${0} | ${1}
${'math'} | ${'log'} | ${[2, 4]} | ${0} | ${2}
${'cmp'} | ${'gt'} | ${[2, 4]} | ${0} | ${false}
${'cmp'} | ${'gte'} | ${[2, 4]} | ${0} | ${false}
${'cmp'} | ${'gte'} | ${[4, 2]} | ${0} | ${true}
${'cmp'} | ${'gte'} | ${[2, 2]} | ${0} | ${true}
${'cmp'} | ${'lt'} | ${[2, 4]} | ${0} | ${true}
${'cmp'} | ${'lte'} | ${[2, 4]} | ${0} | ${true}
${'cmp'} | ${'lte'} | ${[4, 2]} | ${0} | ${false}
${'cmp'} | ${'lte'} | ${[2, 2]} | ${0} | ${true}
${'cmp'} | ${'cmp'} | ${[2, 4]} | ${0} | ${-1}
${'cmp'} | ${'cmp'} | ${[2, -4]} | ${0} | ${1}
${'cmp'} | ${'cmp'} | ${[2, 2]} | ${0} | ${0}
${'array'} | ${'sum'} | ${[[1, 2, 3]]} | ${0} | ${6}
${'array'} | ${'dedup'} | ${[['a', 'a', 'b', 'c', 'a', 'b', 'c']]} | ${0} | ${['a', 'b', 'c']}
${'array'} | ${'intersect'} | ${[['a', 'b', 'c'], ['c', 'b', 'd']]} | ${0} | ${['b', 'c']}
${'array'} | ${'diff'} | ${[['a', 'b', 'c'], ['c', 'b', 'd']]} | ${0} | ${['a']}
${'array'} | ${'sdiff'} | ${[['a', 'b', 'c'], ['c', 'b', 'd']]} | ${0} | ${['a', 'd']}
${'json'} | ${'obj'} | ${['a', 10, 'b', 'string', 'c', null]} | ${0} | ${{ a: 10, b: 'string', c: null }}
${'json'} | ${'obj'} | ${['a', 10, 'b', 'string', 'c']} | ${1} | ${'Expected even number of argument(s). Got 5'}
${'json'} | ${'obj'} | ${[]} | ${0} | ${{}}
${'json'} | ${'put'} | ${[{}, 'a', 10]} | ${0} | ${{ a: 10 }}
${'json'} | ${'put'} | ${[{ b: 11 }, 'a', 10]} | ${0} | ${{ a: 10, b: 11 }}
${'json'} | ${'put'} | ${['a', 'a', 11]} | ${1} | ${'Argument 0 expected to be of type object, Got string'}
${'json'} | ${'put'} | ${[{}, 'a', 10, 'b', 20]} | ${1} | ${'Expected 3 argument(s). Got 5'}
${'json'} | ${'put'} | ${[{}]} | ${1} | ${'Expected 3 argument(s). Got 1'}
${'json'} | ${'puts'} | ${[{}, 'a', 10]} | ${0} | ${{ a: 10 }}
${'json'} | ${'puts'} | ${[{ b: 11 }, 'a', 10]} | ${0} | ${{ a: 10, b: 11 }}
${'json'} | ${'puts'} | ${[{}, 'a', 10, 'b', 'string', 'c', null]} | ${0} | ${{ a: 10, b: 'string', c: null }}
${'json'} | ${'puts'} | ${[{ x: 'text' }, 'a', 10, 'b', 'string']} | ${0} | ${{ a: 10, b: 'string', x: 'text' }}
${'json'} | ${'puts'} | ${[{}]} | ${1} | ${'Expected more than 3 argument(s). Got 1'}
${'json'} | ${'puts'} | ${['a', 'a', 11]} | ${1} | ${'Argument 0 expected to be of type object, Got string'}
${'json'} | ${'stringify'} | ${[{ a: 10, b: 'string', c: null }]} | ${0} | ${'{"a":10,"b":"string","c":null}'}
${'json'} | ${'stringify'} | ${[1]} | ${1} | ${'Argument 0 expected to be of type object, Got number'}
${'json'} | ${'parse'} | ${['{"a":10,"b":"string","c":null}']} | ${0} | ${{ a: 10, b: 'string', c: null }}
${'json'} | ${'parse'} | ${['incorrect']} | ${1} | ${'Unexpected token i in JSON at position 0'}
${'json'} | ${'parse'} | ${[10]} | ${1} | ${'Argument 0 expected to be of type string, Got number'}
`(
//
'$fnName with $args expected retcode: $retCode and result: $result',
async ({ serviceId, fnName, args, retCode, result }) => {
// arrange
const req: CallServiceData = {
serviceId: serviceId,
fnName: fnName,
args: args,
tetraplets: [],
particleContext: {
particleId: 'some',
initPeerId: 'init peer id',
timestamp: 595951200,
ttl: 595961200,
signature: 'sig',
},
};
// act
const fn = builtInServices[req.serviceId][req.fnName];
const res = await fn(req);
// assert
expect(res).toMatchObject({
retCode: retCode,
result: result,
});
},
);
it('should return correct error message for identiy service', async () => {
// arrange
const req: CallServiceData = {
serviceId: 'peer',
fnName: 'identify',
args: [],
tetraplets: [],
particleContext: {
particleId: 'some',
initPeerId: 'init peer id',
timestamp: 595951200,
ttl: 595961200,
signature: 'sig',
},
};
// act
const fn = builtInServices[req.serviceId][req.fnName];
const res = await fn(req);
// assert
expect(res).toMatchObject({
retCode: 0,
result: {
external_addresses: [],
node_version: expect.stringContaining('js'),
air_version: expect.stringContaining('js'),
},
});
});
});
const key = '+cmeYlZKj+MfSa9dpHV+BmLPm6wq4inGlsPlQ1GvtPk=';
const context = (async () => {
const keyBytes = toUint8Array(key);
const kp = await KeyPair.fromEd25519SK(keyBytes);
const res = {
peerKeyPair: kp,
peerId: kp.getPeerId(),
};
return res;
})();
const testData = [1, 2, 3, 4, 5, 6, 7, 9, 10];
// signature produced by KeyPair created from key above (`key` variable)
const testDataSig = [
224, 104, 245, 206, 140, 248, 27, 72, 68, 133, 111, 10, 164, 197, 242, 132, 107, 77, 224, 67, 99, 106, 76, 29, 144,
121, 122, 169, 36, 173, 58, 80, 170, 102, 137, 253, 157, 247, 168, 87, 162, 223, 188, 214, 203, 220, 52, 246, 29,
86, 77, 71, 224, 248, 16, 213, 254, 75, 78, 239, 243, 222, 241, 15,
];
// signature produced by KeyPair created from some random KeyPair
const testDataWrongSig = [
116, 247, 189, 118, 236, 53, 147, 123, 219, 75, 176, 105, 101, 108, 233, 137, 97, 14, 146, 132, 252, 70, 51, 153,
237, 167, 156, 150, 36, 90, 229, 108, 166, 231, 255, 137, 8, 246, 125, 0, 213, 150, 83, 196, 237, 221, 131, 159,
157, 159, 25, 109, 95, 160, 181, 65, 254, 238, 47, 156, 240, 151, 58, 14,
];
const makeTetraplet = (initPeerId: string, serviceId?: string, fnName?: string): CallParams<'data'> => {
return {
initPeerId: initPeerId,
tetraplets: {
data: [
{
function_name: fnName,
service_id: serviceId,
},
],
},
} as any;
};
describe('Sig service tests', () => {
it('sig.sign should create the correct signature', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
const res = await sig.sign(testData, makeTetraplet(ctx.peerId));
expect(res.success).toBe(true);
expect(res.signature).toStrictEqual(testDataSig);
});
it('sig.verify should return true for the correct signature', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
const res = await sig.verify(testDataSig, testData);
expect(res).toBe(true);
});
it('sig.verify should return false for the incorrect signature', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
const res = await sig.verify(testDataWrongSig, testData);
expect(res).toBe(false);
});
it('sign-verify call chain should work', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
const signature = await sig.sign(testData, makeTetraplet(ctx.peerId));
const res = await sig.verify(signature.signature as number[], testData);
expect(res).toBe(true);
});
it('sig.sign with defaultSigGuard should work for correct callParams', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
sig.securityGuard = defaultSigGuard(ctx.peerId);
const signature = await sig.sign(testData, makeTetraplet(ctx.peerId, 'registry', 'get_route_bytes'));
await expect(signature).toBeDefined();
});
it('sig.sign with defaultSigGuard should not allow particles initiated from incorrect service', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
sig.securityGuard = defaultSigGuard(ctx.peerId);
const res = await sig.sign(testData, makeTetraplet(ctx.peerId, 'other_service', 'other_fn'));
await expect(res.success).toBe(false);
await expect(res.error).toBe('Security guard validation failed');
});
it('sig.sign with defaultSigGuard should not allow particles initiated from other peers', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
sig.securityGuard = defaultSigGuard(ctx.peerId);
const res = await sig.sign(
testData,
makeTetraplet((await KeyPair.randomEd25519()).getPeerId(), 'registry', 'get_key_bytes'),
);
await expect(res.success).toBe(false);
await expect(res.error).toBe('Security guard validation failed');
});
it('changing securityGuard should work', async () => {
const ctx = await context;
const sig = new Sig(ctx.peerKeyPair);
sig.securityGuard = allowServiceFn('test', 'test');
const successful1 = await sig.sign(testData, makeTetraplet(ctx.peerId, 'test', 'test'));
const unSuccessful1 = await sig.sign(testData, makeTetraplet(ctx.peerId, 'wrong', 'wrong'));
sig.securityGuard = allowServiceFn('wrong', 'wrong');
const successful2 = await sig.sign(testData, makeTetraplet(ctx.peerId, 'wrong', 'wrong'));
const unSuccessful2 = await sig.sign(testData, makeTetraplet(ctx.peerId, 'test', 'test'));
expect(successful1.success).toBe(true);
expect(successful2.success).toBe(true);
expect(unSuccessful1.success).toBe(false);
expect(unSuccessful2.success).toBe(false);
});
});

View File

@ -1,5 +1,4 @@
import each from 'jest-each';
import { aqua2ts, ts2aqua } from '../../../compilerSupport/conversions';
import { aqua2ts, ts2aqua } from '../../../compilerSupport/conversions.js';
const i32 = { tag: 'scalar', name: 'i32' } as const;
@ -152,24 +151,24 @@ const nestedStructs = [
];
describe('Conversion from aqua to typescript', () => {
each`
aqua | ts | type
${1} | ${1} | ${i32}
${[]} | ${null} | ${opt_i32}
${[1]} | ${1} | ${opt_i32}
${[1, 2, 3]} | ${[1, 2, 3]} | ${array_i32}
${[]} | ${[]} | ${array_i32}
${[[1]]} | ${[1]} | ${array_opt_i32}
${[[]]} | ${[null]} | ${array_opt_i32}
${[[1], [2]]} | ${[1, 2]} | ${array_opt_i32}
${[[], [2]]} | ${[null, 2]} | ${array_opt_i32}
${structs[0].aqua} | ${structs[0].ts} | ${labeledProduct}
${structs[1].aqua} | ${structs[1].ts} | ${labeledProduct}
${structs[0].aqua} | ${structs[0].ts} | ${struct}
${structs[1].aqua} | ${structs[1].ts} | ${struct}
${nestedStructs[0].aqua} | ${nestedStructs[0].ts} | ${nestedLabeledProductType}
${nestedStructs[1].aqua} | ${nestedStructs[1].ts} | ${nestedLabeledProductType}
`.test(
test.each`
aqua | ts | type
${1} | ${1} | ${i32}
${[]} | ${null} | ${opt_i32}
${[1]} | ${1} | ${opt_i32}
${[1, 2, 3]} | ${[1, 2, 3]} | ${array_i32}
${[]} | ${[]} | ${array_i32}
${[[1]]} | ${[1]} | ${array_opt_i32}
${[[]]} | ${[null]} | ${array_opt_i32}
${[[1], [2]]} | ${[1, 2]} | ${array_opt_i32}
${[[], [2]]} | ${[null, 2]} | ${array_opt_i32}
${structs[0].aqua} | ${structs[0].ts} | ${labeledProduct}
${structs[1].aqua} | ${structs[1].ts} | ${labeledProduct}
${structs[0].aqua} | ${structs[0].ts} | ${struct}
${structs[1].aqua} | ${structs[1].ts} | ${struct}
${nestedStructs[0].aqua} | ${nestedStructs[0].ts} | ${nestedLabeledProductType}
${nestedStructs[1].aqua} | ${nestedStructs[1].ts} | ${nestedLabeledProductType}
`(
//
'aqua: $aqua. ts: $ts. type: $type',
async ({ aqua, ts, type }) => {

View File

@ -1,17 +1,18 @@
import api from '@fluencelabs/aqua-api/aqua-api';
import { InlinedWorkerLoader } from '@fluencelabs/marine.deps-loader.node';
import * as api from '@fluencelabs/aqua-api/aqua-api.js';
import { promises as fs } from 'fs';
import { FluencePeer, PeerConfig } from '../FluencePeer';
import { Particle } from '../Particle';
import { avmModuleLoader, controlModuleLoader, MakeServiceCall } from '../utils';
import { ServiceDef } from '../compilerSupport/interface';
import { callFunctionImpl } from '../compilerSupport/callFunction';
import { FluencePeer, PeerConfig } from '../FluencePeer.js';
import { Particle } from '../Particle.js';
import { MakeServiceCall } from '../utils.js';
import { avmModuleLoader, controlModuleLoader } from '../utilsForNode.js';
import { ServiceDef } from '../compilerSupport/interface.js';
import { callFunctionImpl } from '../compilerSupport/callFunction.js';
import { marineLogFunction } from '../utils';
import { MarineBackgroundRunner } from '@fluencelabs/marine.background-runner';
import { MarineBasedAvmRunner } from '../avm';
import { nodes } from './connection';
import { marineLogFunction } from '../utils.js';
import { MarineBackgroundRunner } from '../../marine/worker/index.js';
import { MarineBasedAvmRunner } from '../avm.js';
import { nodes } from './connection.js';
import { WorkerLoaderFromFs } from '../../marine/deps-loader/node.js';
export const registerHandlersHelper = (
peer: FluencePeer,
@ -51,7 +52,7 @@ export const compileAqua = async (aquaFile: string): Promise<CompiledFile> => {
};
export const mkTestPeer = () => {
const workerLoader = new InlinedWorkerLoader();
const workerLoader = new WorkerLoaderFromFs('../../marine/worker-script');
const marine = new MarineBackgroundRunner(workerLoader, controlModuleLoader, marineLogFunction);
const avm = new MarineBasedAvmRunner(marine, avmModuleLoader, undefined);

View File

@ -6,9 +6,9 @@
* Aqua version: 0.7.7-362
*
*/
import { CallParams } from '../commonTypes';
import { registerServiceImpl } from '../compilerSupport/registerService';
import { FluencePeer } from '../FluencePeer';
import { CallParams } from '../commonTypes.js';
import { registerServiceImpl } from '../compilerSupport/registerService.js';
import { FluencePeer } from '../FluencePeer.js';
// Services

View File

@ -6,9 +6,9 @@
* Aqua version: 0.7.7-362
*
*/
import { CallParams } from '../commonTypes';
import { registerServiceImpl } from '../compilerSupport/registerService';
import { FluencePeer } from '../FluencePeer';
import { CallParams } from '../commonTypes.js';
import { registerServiceImpl } from '../compilerSupport/registerService.js';
import { FluencePeer } from '../FluencePeer.js';
// Services

Some files were not shown because too many files have changed in this diff Show More