This commit is contained in:
boneyard93501 2022-02-07 18:39:56 -06:00
parent 6dbd940592
commit 5fd2cdbb6c
8 changed files with 8766 additions and 0 deletions

View File

@ -0,0 +1,60 @@
import "@fluencelabs/aqua-lib/builtin.aqua"
-- simple timestamp getter for kademlia neigborhodd which is max size 20
func ts_getter() -> []u64:
-- on this peer
on HOST_PEER_ID:
-- convert peer id to b58
k <- Op.string_to_b58(HOST_PEER_ID)
-- get all neighbors
nodes <- Kademlia.neighborhood(k, nil, nil)
res: *u64
-- for each neighbor
for n <- nodes par:
-- on selected neighbor peer
on n:
-- get the timestamp from that node
res <- Peer.timestamp_ms()
-- hot fix to force switching to peer
Op.noop()
-- join the results, which is tricky rght now since we can't use array len
-- the testnet size n is 10 so n -1
join res[9]
<- res
-- timestap getter with error collector over neighborhood
func ts_getter_with_timeout()-> []u64, []string:
-- timeout in ms
rtt = 1000
res: *u64
-- error value for no timestamp
err_value = 0
-- neighborhood n = 20 decr by 1 for array
n_neighborhood = 19
-- err message
msg = "timeout"
-- collect non-rsponsive peer ids, if any
dead_peers: *string
on HOST_PEER_ID:
k <- Op.string_to_b58(HOST_PEER_ID)
nodes <- Kademlia.neighborhood(k, nil, nil)
for n <- nodes par:
status: *string
on n:
res <- Peer.timestamp_ms()
status <<- "success"
par status <- Peer.timeout(rtt, msg)
if status! != "success":
res <<- err_value
dead_peers <<- n
Op.noop()
join res[n_neighborhood]
<- res, dead_peers

View File

@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ts_getter_with_timeout = exports.ts_getter = void 0;
var v2_1 = require("@fluencelabs/fluence/dist/internal/compilerSupport/v2");
function ts_getter() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var script = "\n (xor\n (seq\n (seq\n (call %init_peer_id% (\"getDataSrv\" \"-relay-\") [] -relay-)\n (new $res\n (seq\n (xor\n (seq\n (seq\n (seq\n (call -relay- (\"op\" \"string_to_b58\") [-relay-] k)\n (call -relay- (\"kad\" \"neighborhood\") [k [] []] nodes)\n )\n (par\n (fold nodes n\n (par\n (seq\n (xor\n (call n (\"peer\" \"timestamp_ms\") [] $res)\n (seq\n (call -relay- (\"op\" \"noop\") [])\n (call %init_peer_id% (\"errorHandlingSrv\" \"error\") [%last_error% 1])\n )\n )\n (call -relay- (\"op\" \"noop\") [])\n )\n (next n)\n )\n )\n (null)\n )\n )\n (call -relay- (\"op\" \"noop\") [$res.$.[9]!])\n )\n (call %init_peer_id% (\"errorHandlingSrv\" \"error\") [%last_error% 2])\n )\n (call %init_peer_id% (\"op\" \"identity\") [$res] res-fix)\n )\n )\n )\n (xor\n (call %init_peer_id% (\"callbackSrv\" \"response\") [res-fix])\n (call %init_peer_id% (\"errorHandlingSrv\" \"error\") [%last_error% 3])\n )\n )\n (call %init_peer_id% (\"errorHandlingSrv\" \"error\") [%last_error% 4])\n )\n ";
return v2_1.callFunction(args, {
"functionName": "ts_getter",
"returnType": {
"tag": "primitive"
},
"argDefs": [],
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
}, script);
}
exports.ts_getter = ts_getter;
function ts_getter_with_timeout() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var script = "\n (xor\n (seq\n (seq\n (call %init_peer_id% (\"getDataSrv\" \"-relay-\") [] -relay-)\n (new $res\n (seq\n (new $dead_peers\n (seq\n (xor\n (seq\n (seq\n (seq\n (call -relay- (\"op\" \"string_to_b58\") [-relay-] k)\n (call -relay- (\"kad\" \"neighborhood\") [k [] []] nodes)\n )\n (par\n (fold nodes n\n (par\n (new $status\n (seq\n (seq\n (par\n (xor\n (seq\n (call n (\"peer\" \"timestamp_ms\") [] $res)\n (ap \"success\" $status)\n )\n (seq\n (call -relay- (\"op\" \"noop\") [])\n (call %init_peer_id% (\"errorHandlingSrv\" \"error\") [%last_error% 1])\n )\n )\n (call -relay- (\"peer\" \"timeout\") [1000 \"timeout\"] $status)\n )\n (xor\n (mismatch $status.$.[0]! \"success\"\n (xor\n (seq\n (ap 0 $res)\n (ap n $dead_peers)\n )\n (call %init_peer_id% (\"errorHandlingSrv\" \"error\") [%last_error% 2])\n )\n )\n (null)\n )\n )\n (call -relay- (\"op\" \"noop\") [])\n )\n )\n (next n)\n )\n )\n (null)\n )\n )\n (call -relay- (\"op\" \"noop\") [$res.$.[19]!])\n )\n (call %init_peer_id% (\"errorHandlingSrv\" \"error\") [%last_error% 3])\n )\n (call %init_peer_id% (\"op\" \"identity\") [$dead_peers] dead_peers-fix)\n )\n )\n (call %init_peer_id% (\"op\" \"identity\") [$res] res-fix)\n )\n )\n )\n (xor\n (call %init_peer_id% (\"callbackSrv\" \"response\") [res-fix dead_peers-fix])\n (call %init_peer_id% (\"errorHandlingSrv\" \"error\") [%last_error% 4])\n )\n )\n (call %init_peer_id% (\"errorHandlingSrv\" \"error\") [%last_error% 5])\n )\n ";
return v2_1.callFunction(args, {
"functionName": "ts_getter_with_timeout",
"returnType": {
"tag": "multiReturn",
"returnItems": [
{
"tag": "primitive"
},
{
"tag": "primitive"
}
]
},
"argDefs": [],
"names": {
"relay": "-relay-",
"getDataSrv": "getDataSrv",
"callbackSrv": "callbackSrv",
"responseSrv": "callbackSrv",
"responseFnName": "response",
"errorHandlingSrv": "errorHandlingSrv",
"errorFnName": "error"
}
}, script);
}
exports.ts_getter_with_timeout = ts_getter_with_timeout;

96
fuzz-client/dist/src/index.js vendored Normal file
View File

@ -0,0 +1,96 @@
"use strict";
/*
* Copyright 2021 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.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var fluence_1 = require("@fluencelabs/fluence");
var fluence_network_environment_1 = require("@fluencelabs/fluence-network-environment");
var timestamp_gatherer_1 = require("./_aqua/timestamp_gatherer");
function main() {
return __awaiter(this, void 0, void 0, function () {
var ts_result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// create the Fluence client for the Krasnodar testnet
return [4 /*yield*/, fluence_1.Fluence.start({ connectTo: fluence_network_environment_1.krasnodar[5] })];
case 1:
// create the Fluence client for the Krasnodar testnet
_a.sent();
console.log("Created a fluence client with peer id %s and relay id %s", fluence_1.Fluence.getStatus().peerId, fluence_1.Fluence.getStatus().relayPeerId);
return [4 /*yield*/, timestamp_gatherer_1.ts_getter()];
case 2:
ts_result = _a.sent();
console.log("simple result: ", ts_result);
// call the get_price_par function -- parallel processing
// func get_price_par(coin: string, currency: string, getter_topo: []NodeServicePair, mean_topo: NodeServicePair) -> Result:
// const network_result_par = await get_price_par("ethereum", "usd", getter_topo, mean_topo[0]
// );
// console.log("par result: ", network_result_par);
return [4 /*yield*/, fluence_1.Fluence.stop()];
case 3:
// call the get_price_par function -- parallel processing
// func get_price_par(coin: string, currency: string, getter_topo: []NodeServicePair, mean_topo: NodeServicePair) -> Result:
// const network_result_par = await get_price_par("ethereum", "usd", getter_topo, mean_topo[0]
// );
// console.log("par result: ", network_result_par);
_a.sent();
return [2 /*return*/];
}
});
});
}
main()
.then(function () { return process.exit(0); })
.catch(function (error) {
console.error(error);
process.exit(1);
});

8175
fuzz-client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

42
fuzz-client/package.json Normal file
View File

@ -0,0 +1,42 @@
{
"name": "timestamp-getter",
"version": "0.1.0",
"description": "Network timestamp getter demo",
"main": "./dist/src/index.js",
"typings": "./dist/src/index.d.ts",
"files": [
"dist/*"
],
"bic": [
"client-peer/*",
"*.aqua",
"package-lock.json"
],
"dependencies": {
"@fluencelabs/aqua-lib": "^0.3.4",
"@fluencelabs/fluence": "0.19.1",
"@fluencelabs/fluence-network-environment": "1.0.13",
"it-all": "^1.0.5",
"ts-node": "^10.5.0"
},
"scripts": {
"start": "node -r ts-node/register src/index.ts",
"compile-aqua": "aqua -i aqua -o src/_aqua/",
"watch-aqua": "chokidar \"**/*.aqua\" -c \"npm run compile-aqua\""
},
"keywords": [
"aqua",
"fluence"
],
"author": "Fluence Labs",
"license": "MIT",
"bugs": {
"url": "git+https://github.com/fluencelabs/examples/issues"
},
"devDependencies": {
"@fluencelabs/aqua": "^0.6.0-272",
"@fluencelabs/aqua-lib": "^0.3.4",
"ts-node": "^10.5.0",
"typescript": "^4.5.5"
}
}

View File

@ -0,0 +1,223 @@
/**
*
* This file is auto-generated. Do not edit manually: changes may be erased.
* Generated by Aqua compiler: https://github.com/fluencelabs/aqua/.
* If you find any bugs, please write an issue on GitHub: https://github.com/fluencelabs/aqua/issues
* Aqua version: 0.6.0-272
*
*/
import { Fluence, FluencePeer } from '@fluencelabs/fluence';
import {
CallParams,
callFunction,
registerService,
} from '@fluencelabs/fluence/dist/internal/compilerSupport/v2';
// Services
// Functions
export function ts_getter(
config?: {ttl?: number}
): Promise<number[]>;
export function ts_getter(
peer: FluencePeer,
config?: {ttl?: number}
): Promise<number[]>;
export function ts_getter(...args: any) {
let script = `
(xor
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(new $res
(seq
(xor
(seq
(seq
(seq
(call -relay- ("op" "string_to_b58") [-relay-] k)
(call -relay- ("kad" "neighborhood") [k [] []] nodes)
)
(par
(fold nodes n
(par
(seq
(xor
(call n ("peer" "timestamp_ms") [] $res)
(seq
(call -relay- ("op" "noop") [])
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 1])
)
)
(call -relay- ("op" "noop") [])
)
(next n)
)
)
(null)
)
)
(call -relay- ("op" "noop") [$res.$.[9]!])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 2])
)
(call %init_peer_id% ("op" "identity") [$res] res-fix)
)
)
)
(xor
(call %init_peer_id% ("callbackSrv" "response") [res-fix])
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 3])
)
)
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 4])
)
`
return callFunction(
args,
{
"functionName" : "ts_getter",
"returnType" : {
"tag" : "primitive"
},
"argDefs" : [
],
"names" : {
"relay" : "-relay-",
"getDataSrv" : "getDataSrv",
"callbackSrv" : "callbackSrv",
"responseSrv" : "callbackSrv",
"responseFnName" : "response",
"errorHandlingSrv" : "errorHandlingSrv",
"errorFnName" : "error"
}
},
script
)
}
export type Ts_getter_with_timeoutResult = [number[], string[]]
export function ts_getter_with_timeout(
config?: {ttl?: number}
): Promise<Ts_getter_with_timeoutResult>;
export function ts_getter_with_timeout(
peer: FluencePeer,
config?: {ttl?: number}
): Promise<Ts_getter_with_timeoutResult>;
export function ts_getter_with_timeout(...args: any) {
let script = `
(xor
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(new $res
(seq
(new $dead_peers
(seq
(xor
(seq
(seq
(seq
(call -relay- ("op" "string_to_b58") [-relay-] k)
(call -relay- ("kad" "neighborhood") [k [] []] nodes)
)
(par
(fold nodes n
(par
(new $status
(seq
(seq
(par
(xor
(seq
(call n ("peer" "timestamp_ms") [] $res)
(ap "success" $status)
)
(seq
(call -relay- ("op" "noop") [])
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 1])
)
)
(call -relay- ("peer" "timeout") [1000 "timeout"] $status)
)
(xor
(mismatch $status.$.[0]! "success"
(xor
(seq
(ap 0 $res)
(ap n $dead_peers)
)
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 2])
)
)
(null)
)
)
(call -relay- ("op" "noop") [])
)
)
(next n)
)
)
(null)
)
)
(call -relay- ("op" "noop") [$res.$.[19]!])
)
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 3])
)
(call %init_peer_id% ("op" "identity") [$dead_peers] dead_peers-fix)
)
)
(call %init_peer_id% ("op" "identity") [$res] res-fix)
)
)
)
(xor
(call %init_peer_id% ("callbackSrv" "response") [res-fix dead_peers-fix])
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 4])
)
)
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 5])
)
`
return callFunction(
args,
{
"functionName" : "ts_getter_with_timeout",
"returnType" : {
"tag" : "multiReturn",
"returnItems" : [
{
"tag" : "primitive"
},
{
"tag" : "primitive"
}
]
},
"argDefs" : [
],
"names" : {
"relay" : "-relay-",
"getDataSrv" : "getDataSrv",
"callbackSrv" : "callbackSrv",
"responseSrv" : "callbackSrv",
"responseFnName" : "response",
"errorHandlingSrv" : "errorHandlingSrv",
"errorFnName" : "error"
}
},
script
)
}

48
fuzz-client/src/index.ts Normal file
View File

@ -0,0 +1,48 @@
/*
* 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 { setLogLevel, Fluence } from "@fluencelabs/fluence";
import { krasnodar, Node } from "@fluencelabs/fluence-network-environment";
import { ts_getter, ts_getter_with_timeout } from "./_aqua/timestamp_gatherer";
async function main() {
// create the Fluence client for the Krasnodar testnet
// and we're using peer 6 to do so
await Fluence.start({ connectTo: krasnodar[5] });
console.log(
"Created a fluence client with peer id %s and relay id %s",
Fluence.getStatus().peerId,
Fluence.getStatus().relayPeerId
);
// call the get_price function -- sequential processing
const ts_result = await ts_getter();
console.log("simple result: ", ts_result);
const ts_result_tuple = await ts_getter_with_timeout();
console.log("raw timestamps: %s\ndead peers: %s ", ts_result_tuple[0].filter(e => e !== 0), ts_result_tuple[1]);
await Fluence.stop();
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

62
fuzz-client/tsconfig.json Normal file
View File

@ -0,0 +1,62 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": ".", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}