Compare commits

..

9 Commits

Author SHA1 Message Date
a21733b034 fix tests 2022-01-20 18:28:52 +03:00
a491cf15e2 update service and aqua api 2022-01-20 17:41:22 +03:00
6b6f717c6c add missing example secret key 2022-01-17 02:43:08 +03:00
7ee8cacc03 fix 2022-01-17 02:35:59 +03:00
a207c52ce8 pr fixes 2022-01-17 02:34:05 +03:00
f27a7e635e fix ci 2022-01-11 17:07:10 +03:00
dce846d1c7 pr fix 2022-01-11 17:01:15 +03:00
6384d3d67d fix 2022-01-11 16:55:54 +03:00
bf30873fcb add hl-api, add example with trusted computation 2021-12-30 03:52:16 +03:00
52 changed files with 6284 additions and 25850 deletions

View File

@ -1,6 +0,0 @@
[http]
timeout = 30 # timeout for each HTTP request, in seconds
multiplexing = false # HTTP/2 multiplexing
[net]
retry = 50 # network retries

38
.circleci/config.yml Normal file
View File

@ -0,0 +1,38 @@
version: 2.1
orbs:
docker: circleci/docker@1.5.0
jobs:
Build:
docker:
- image: circleci/rust:latest
resource_class: xlarge
environment:
RUST_BACKTRACE: 1
steps:
- checkout
- run: |
sudo bash .github/download_marine.sh
- restore_cache:
keys:
- trust-graph00-{{ checksum "./Cargo.lock" }}-{{ checksum "./keypair/Cargo.lock" }}
- run: |
rustup target add wasm32-wasi
cargo test --no-fail-fast --release --all-features --
cd ./service
./build.sh
mkdir data
cargo test --no-fail-fast --release --all-features -- --test-threads=1
- save_cache:
paths:
- ~/.cargo
- ~/.rustup
key: trust-graph00-{{ checksum "./Cargo.lock" }-{{ checksum "./service/Cargo.lock" }}}-{{ checksum "./keypair/Cargo.lock" }}
workflows:
version: 2
CircleCI:
jobs:
- Build

View File

@ -3,7 +3,7 @@ set -o pipefail -o errexit -o nounset
set -x
MARINE_RELEASE="https://api.github.com/repos/fluencelabs/marine/releases/latest"
OUT_DIR=~/.bin
OUT_DIR=/usr/local/bin
# get metadata about release
curl -s -H "Accept: application/vnd.github.v3+json" $MARINE_RELEASE |

View File

@ -1,6 +1,5 @@
{
"template": "## Changes since ${{FROM_TAG}}\n\n${{CHANGELOG}}\n\n${{UNCATEGORIZED}}",
"template": "${{CHANGELOG}}\n\n${{UNCATEGORIZED}}",
"pr_template": "- #${{NUMBER}} ${{TITLE}}",
"empty_template": "## No changes since ${{FROM_TAG}}",
"sort": "DESC"
"empty_template": "- no changes"
}

View File

@ -6,35 +6,60 @@ on:
- "v*"
jobs:
release:
npm-publish:
name: "Publish"
runs-on: builder
runs-on: ubuntu-latest
container: rust
defaults:
run:
shell: bash
steps:
### Setup
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v2
- name: Set env
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
- uses: actions/setup-node@v3
with:
node-version: "15"
registry-url: "https://registry.npmjs.org"
cache: npm
cache-dependency-path: "aqua/package-lock.json"
- run: mkdir -p ~/.bin
- run: echo "~/.bin" >> $GITHUB_PATH
- name: Setup Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Download jq
run: |
curl -L https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64 -o /usr/local/bin/jq
chmod +x /usr/local/bin/jq
- name: Download marine
run: bash $GITHUB_WORKSPACE/.github/download_marine.sh
- name: Build trust-graph
- name: Cache npm
uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.os }}-node-v01-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-v01-
- uses: actions/setup-node@v2
with:
node-version: "15"
registry-url: "https://registry.npmjs.org"
- uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Install toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly-2021-09-01
target: wasm32-wasi
override: true
### Build
- name: trust-graph.wasm
working-directory: ./service
run: ./build.sh
@ -44,7 +69,7 @@ jobs:
npm i
npm run build
- name: Create distribution package
- name: Create builtin distribution package
run: |
./builtin-package/package.sh
@ -56,15 +81,15 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
### Publish
- name: Release to GitHub
## Publish
- name: Release
id: release
uses: softprops/action-gh-release@v1
with:
name: trust-graph ${{ env.RELEASE_VERSION }}
tag_name: ${{ env.RELEASE_VERSION }}
files: |
./trust-graph.tar.gz
trust-graph.tar.gz
body: ${{steps.changelog.outputs.changelog}}
draft: false
prerelease: false
@ -72,10 +97,10 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
### Publish Aqua API
- name: Publish Aqua API to NPM
### Publish Aqua API
- name: Publish Aqua API
run: |
npm version ${{ env.RELEASE_VERSION }}
npm version ${{ env.RELEASE_VERSION }} --allow-same-version
npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
@ -84,9 +109,9 @@ jobs:
## Update node-distro repo
- name: Calculate SHA256
run: |
du -hs trust-graph.tar.gz
echo $(sha256sum trust-graph.tar.gz)
echo "SHA256=$(sha256sum trust-graph.tar.gz | awk '{ print $1 }')" >> $GITHUB_ENV
du -hs trust-graph.tar.gz
echo $(sha256sum trust-graph.tar.gz)
echo "SHA256=$(sha256sum trust-graph.tar.gz | awk '{ print $1 }')" >> $GITHUB_ENV
- name: Get tar.gz URL
id: package-url

View File

@ -1,89 +0,0 @@
name: Rust CI
on:
push:
workflow_dispatch:
concurrency:
group: "${{ github.workflow }}-${{ github.ref }}"
cancel-in-progress: true
jobs:
check:
name: cargo nextest
runs-on: builder
defaults:
run:
working-directory: service
shell: bash
steps:
- name: Checkout sources
uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- run: mkdir -p ~/.bin
- run: echo "~/.bin" >> $GITHUB_PATH
- name: Install toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
- name: Add wasm32-wasi target
run: rustup target add wasm32-wasi
- name: Download jq
run: |
curl -L https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64 -o ~/.bin/jq
chmod +x ~/.bin/jq
- name: Download marine
run: bash $GITHUB_WORKSPACE/.github/download_marine.sh
- name: Build
run: ./build.sh
- run: cargo install --locked cargo-nextest --version 0.9.22
- run: cargo nextest run --release --all-features --no-fail-fast --retries 10 --test-threads 10
lints:
name: Lints
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Install toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: rustfmt, clippy
- name: Run cargo fmt
uses: actions-rs/cargo@v1
with:
command: fmt
args: --all -- --check
- name: Run cargo clippy
uses: actions-rs/cargo@v1
with:
command: clippy
args: -Z unstable-options --all
continue-on-error: true # do not fail for now

View File

@ -10,16 +10,8 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Get branch
run: |
BRANCH=${GITHUB_REF#refs/*/}
SANITIZED=$(echo "$BRANCH" | sed -e 's/[^a-zA-Z0-9-]/-/g')
echo "BRANCH=$SANITIZED" >> $GITHUB_ENV
- name: Bump version and push tag
id: tag_version
uses: mathieudutour/github-tag-action@v5.5
with:
append_to_pre_release_tag: ${{ env.BRANCH }}
github_token: ${{ secrets.PERSONAL_TOKEN }}

11
.gitignore vendored
View File

@ -16,14 +16,3 @@ example/src/generated/**
example/generated/**
admin/src/generated/**
admin/generated/**
target
# recommended by Fluence Labs:
.idea
.DS_Store
.fluence
Cargo.lock
**/target/
.vscode/settings.json
.repl_history

672
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -8,9 +8,10 @@ license = "Apache-2.0"
repository = "https://github.com/fluencelabs/trust-graph"
[dependencies]
serde = { version = "1.0.118", features = ["derive"] }
libp2p-core = { package = "fluence-fork-libp2p-core", version = "0.27.2", features = ["secp256k1"] }
serde = { version = "=1.0.118", features = ["derive"] }
fluence-keypair = { path = "./keypair", version = "0.8.1" }
fluence-keypair = { path = "./keypair", version = "0.5.0" }
serde_json = "1.0.58"
bs58 = "0.3.1"
failure = "0.1.6"
@ -29,6 +30,3 @@ members = [
"keypair",
"service"
]
[workspace.dependencies]
libp2p-core = { version = "0.36", default-features = false, features = [ "secp256k1", "rsa" ] }

326
README.md
View File

@ -1,303 +1,20 @@
# Trust Graph
- [Trust Graph](#trust-graph)
- [Overview](#overview)
- [Why is it important?](#why-is-it-important)
- [What is it?](#what-is-it)
- [How to Use it in Aqua](#how-to-use-it-in-aqua)
- [How to import](#how-to-import)
- [How to add roots](#how-to-add-roots)
- [How to issue and add trust](#how-to-issue-and-add-trust)
- [How to revoke the trust](#how-to-revoke-the-trust)
- [How to get certificates](#how-to-get-certificates)
- [How to get weights](#how-to-get-weights)
- [How to use it in TS/JS](#how-to-use-it-in-tsjs)
- [Use cases](#use-cases)
- [Create a trusted subnetwork](#create-a-trusted-subnetwork)
- [Service permission management](#service-permission-management)
- [Label trusted peers and execute computation only on this peers](#label-trusted-peers-and-execute-computation-only-on-this-peers)
- [FAQ](#faq)
- [API](#api)
- [Directory structure](#directory-structure)
- [Learn Aqua](#learn-aqua)
Trust Graph is network-wide peer relationship layer. It's designed to be used to prioritize resources and control permissions in open networks. Being a decentralized graph of relationships, basically a Web of Trust, Trust Graph is distributed among all network peers.
## Overview
The problem of access control and permissions is solved with centralized CAs (Certificate Authority) in web 2.0. However, such problem is urgent and becomes even more challenging considering a decentralized nature of web 3.0. TrustGraph is our point of view on the solution for this challenge.
Specifically, Trust Graph is used to prioritize connections from known peers to counteract Sybil attacks while still keeping network open by reserving resources for unknown peers.
TrustGraph is a bottom layer of trust for open p2p networks: every peer may be provided with SSL-like certificates that promoted over the network. Service providers and peers can treat certificate holders differently based on their certificate set.
At the same time, Trust Graph can be used at the application level in various ways such as prioritization of service execution on authorized peers or to define an interconnected subnetwork among peers of a single protocol.
TrustGraph is a basic component that allows storing and managing certificates without additional logic about how to decide whom to trust and whom to treat as unreliable.
## Why is it important?
The problem of peer choice and prioritization is very urgent in p2p networks. We can't use the network reliably and predictably without trust to any network participant. We also should mark and avoid malicious peers. In addition we need to control our application access and permissions in runtime, so it performs continuously without interruptions and redeployments.
## What is it?
TrustGraph is basically a directed graph with one root at least, vertices are peer ids, and edges are one of the two types of cryptographic relations: trust and revocation.
**Root** is a peer id that we unconditionally trust until it is removed, and is defined by the node owner. Every root has characteristics that represent the maximum length for a chain of trusts.
As a **path to the root**, we consider a path with only trust edges, given the following rule: chain `R -> A -> ...-> C` is not a path if A revoked C.
**Trust** is a cryptographic relation representing that peer A trusts peer B until this trust expires or is revoked. Trust relation is transitive. If peer A trusts peer B, and peer B trusts peer C, it results in peer A trusts peer C transitively. Trust relation means that you trust to connect, compute or store based on your business logic and chosen metrics. For example, if you want to perform some computation and some well-known peers do that, and are trusted by others you trust, so you can safely use them for computing but not to store sensitive information (personal keys, etc).
Trust data structure contains the following fields:
- peer id, trust is issued to
- creation timestamp
- expiration timestamp
- a signature of the issuer that contains all of the previous fields signed
So the trust is signed and tamperproof by design.
**Certificate** is a chain of trusts started with a self-signed root trust. Considering Trust and Certificate data structures, it is possible to track the chain of trust relations: the `issued_for` field of the first trust in a chain indicates a root peer id, second — whom root trusts, etc. So if we have a chain `R->A->B->C` in the certificate it looks like a chain of the following trusts: `R->R`, `R->A`, `A->B`, `B->C`. A certificate is tamperproof since it is a composition of signed trusts.
![image](images/diagram.png)
So peerA is trusted by peerB if there is a path between them in the instance of TrustGraph. The selection of certificates is subjective and defined by a node owner by choice of roots and maximum chain lengths. For now, there are no default metrics for a general case.
**Revocation** is a cryptographic relation representing that a peer A considers a peer C malicious or unreliable. For example, all chains containing paths from A to C will not be treated as valid. So if A trusts a peer B, and B trusts C, a peer A has no trust to C transitively, it would have otherwise.
![image](images/revocation.png)
Every peer has a **weight**. A weight signifies a power of 2 or zero. If there is no path from any root to a peer, given revocations, its weight equals zero. The closer to the root, the bigger the weight. Weights are also subjective and relevant in the scope of a local TrustGraph.
![image](images/weights.png)
TrustGraph is a builtin meaning that every node is bundled with a TrustGraph instance and predefined certificates.
Trust is transitive in terms of cryptographic relations. On the other hand, a subset of trusts and certificates is subjective for each network participant because of the choice of roots.
## How to Use it in Aqua
### How to import
```
import "@fluencelabs/trust-graph/trust-graph-api.aqua"
import "@fluencelabs/trust-graph/trust-graph.aqua"
func my_function(peer_id: string) -> u32:
on HOST_PEER_ID:
result <- get_weight(peer_id)
<- result
```
### How to add roots
- `set_root(peer_id: PeerId, max_chain_len: u32) -> SetRootResult`
- `add_root_trust(node: PeerId, peer_id: PeerId, max_chain_len: u32) -> ?Error`
Let's set our peer id as a root on our relay and add self-signed trust:
```rust
func set_me_as_root(max_chain_len):
result <- add_root_trust(HOST_PEER_ID, INIT_PEER_ID, max_chain_len)
-- if you use peer_id different from INIT_PEER_ID
-- you should add keypair in your Sig service
if result.success:
-- do smth
Op.noop()
else:
-- handle failure
Op.noop()
```
- also you can use `set_root` + `add_trust` to achieve the same goal
- [how to add keypair to Sig service](https://doc.fluence.dev/docs/fluence-js/3_in_depth#signing-service)
- roots can be added only by the service owner
- `max_chain_len` specifies a number of trusts in a chain for the root. Zero for chains that contain only root trust.
### How to issue and add trust
- `issue_trust(issuer: PeerId, issued_for: PeerId, expires_at_sec: u64) -> ?Trust, ?Error`
- `import_trust(trust: Trust, issuer: PeerId) -> ?Error`
- `add_trust(node: PeerId, issuer: PeerId, issued_for: PeerId, expires_at_sec: u64) -> ?Error`
Let's issue trust, and import it to our relay:
```rust
func issue_trust_by_me(issued_for: PeerId, expires_at_sec: u64):
trust, error <- issue_trust(INIT_PEER_ID, issued_for, expires_at_sec)
if trust == nil:
-- handle failure
Op.noop()
else:
on HOST_PEER_ID:
error <- import_trust(trust!, INIT_PEER_ID)
-- handle error
```
- `add_trust` is a combination of `issue_trust` and `import_trust`
- if you want to issue trust not by `INIT_PEER_ID` check the Sig service [docs](https://doc.fluence.dev/docs/fluence-js/3_in_depth#signing-service)
### How to revoke the trust
- `issue_revocation(revoked_by: PeerId, revoked: PeerId) -> ?Revocation, ?Error`
- `import_revocation(revocation: Revocation) -> ?Error`
- `revoke(node: PeerId, revoked_by: PeerId, revoked: PeerId) -> ?Error`
Let's revoke some peers by our peer id:
```rust
func revoke_peer(revoked: PeerId):
revocation, error <- issue_revocation(INIT_PEER_ID, revoked)
if revocation == nil:
-- handle failure
Op.noop()
else:
on HOST_PEER_ID:
error <- import_revocation(revocation!)
-- handle error
```
- `revoke` is a combination of `issue_revocation` and `import_revocation`
- if you want to issue revocation not by `INIT_PEER_ID` check the Sig service [docs](https://doc.fluence.dev/docs/fluence-js/3_in_depth#signing-service)
### How to get certificates
- `get_all_certs(issued_for: PeerId) -> AllCertsResult`
- `get_all_certs_from(issued_for: PeerId, issuer: PeerId) -> AllCertsResult`
- `get_host_certs() -> AllCertsResult`
- `get_host_certs_from(issuer: PeerId) -> AllCertsResult`
Let's get all certificates issued by us to our relay peer id (HOST_PEER_ID):
```rust
func get_certs_issued_by_me() -> AllCertsResult:
on HOST_PEER_ID:
result <- get_host_certs_from(INIT_PEER_ID)
<- result
```
- `get_host_certs` is just an alias for `get_all_certs(HOST_PEER_ID)`
- `_from` calls results contain only certificates with trust issued by `issuer`
### How to get weights
- `get_weight(peer_id: PeerId) -> WeightResult`
- `get_weight_from(peer_id: PeerId, issuer: PeerId) -> WeightResult`
Let's get our weight for certificates which contain trust by our relay
```rust
func get_our_weight() -> ?u32, ?string:
weight: ?u32
error: ?string
on HOST_PEER_ID:
result <- get_weight_from(INIT_PEER_ID, HOST_PEER_ID)
if result.success:
weight <<- result.weight
else:
error <<- result.error
<- weight, error
```
- `get_weight` returns result among all the certificates, on the other hand, `get_weight_from` return certificates containing trust by the issuer only
## How to use it in TS/JS
1. Add `export.aqua` as in the Aqua [documentation](https://doc.fluence.dev/aqua-book/libraries#in-typescript-and-javascript)
2. Add the following to your dependencies
- `@fluencelabs/trust-graph`
- `@fluencelabs/aqua`
- `@fluencelabs/aqua-lib`
- `@fluencelabs/fluence`
- `@fluencelabs/fluence-network-environment`
3. Import dependencies
```typescript
import * as tg from "./generated/export";
import { Fluence, KeyPair } from "@fluencelabs/fluence";
import { krasnodar, Node } from "@fluencelabs/fluence-network-environment";
```
4. Create a client (specify keypair if you are node owner
[link](https://github.com/fluencelabs/node-distro/blob/main/fluence/Config.default.toml#L9))
```typescript
await Fluence.start({ connectTo: relay /*, KeyPair: builtins_keypair*/});
```
5. Add a root and issue root trust.
```typescript
let peer_id = Fluence.getStatus().peerId;
let relay = Fluence.getStatus().relayPeerId;
assert(peer_id !== null);
assert(relay !== null);
let max_chain_len = 2;
let far_future = 99999999999999;
let error = await tg.add_root_trust(relay, peer_id, max_chain_len, far_future);
if (error !== null) {
console.log(error);
}
```
6. By default, trusts/revocations signed with the client's private key. To sign with different keys see the Sig service [documentation](https://doc.fluence.dev/docs/fluence-js/3_in_depth#signing-service).
```typescript
// issue signed trust
let error = await tg.issue_trust(relay, peer_id, issued_for_peer_id, expires_at_sec);
if (error !== null) {
console.log(error);
}
```
## Use cases
### Create a trusted subnetwork
You can organize a subnetwork with peers trusted by your choice or chosen metrics. So you can treat trusts given by a peer (or a key) as evidence.
Let's consider we have peers A, B and C:
- Choose a peer A as an authority, set it as a root for the local TrustGraphs on all peers
- Issue and put self-signed by a peer A trust as a root trust
- Issue trusts by a peer A a to peer B and a peer C, and put them on all peers
- So for a call `get_weight_from(targetPeer, peerA)` will reflect whether targetPeer is in a subnetwork ABC
### Service permission management
You can specify in runtime who can access service functionality based on the local TrustGraph (certificates, weights). It's possible to check where the proof comes from based on [tetraplets](https://doc.fluence.dev/docs/knowledge_security). For example, only peers that have a non-zero weight can execute a service function `trusted_call(weight: WeightResult) -> u8`.
So if you want to have service permission management you should follow the steps:
- Pass `WeightResult` from TrustGraph to the function that you need to control:
```rust
...
weight_result <- get_weight(INIT_PEER_ID)
result <- MyService.trusted_call(weight_result)
...
```
- Inside your service you need to check tetraplets like [this](https://github.com/fluencelabs/registry/blob/main/service/src/misc.rs#L37) to be sure that they are resulted from the local TrustGraph
- Add `INIT_PEER_ID` or another choosen key as a root
- Issue trust to peers that can call this function:
```rust
func grant_access(issued_for: PeerId, expires_at_sec: u64):
error <- add_trust(INIT_PEER_ID, issued_for, expires_at_sec)
if error != nil
-- handle error
```
### Label trusted peers and execute computation only on this peers
## How to Use it in TypeScript
See [example](./example):
- How to call [`trust-graph`](./example/index.ts) functions in TS/JS
- How to call [`trust-graph`](./example/index.ts) functions in TS/JS
- Step-by-step description [`README`](./example/README.md)
## FAQ
- Can a weight change during time?
- If the shortest path to a root changes, in case of trust expiration, importing or revocation, a weight also changes.
- What does a zero weight mean?
- A zero weight means there is no trust and path from any roots to the target peer.
- How we can interpret a certificate and/or a peer weight?
- A certificate contains a path from the root to the target peer we are looking for. A weight represents the presence of these certificates and peers' closeness to the root.
- How are weights calculated and based on what feedback?
- Weights are calculated based on the existence of a chain of trusts from the roots. For example, if we have a root with a maximum chain length equal 4 and have a chain `R -> A -> B -> C`, so the corresponding weights of peers are `8`, `4`, `2`, `1`. Weights are the same if there are no changes in the paths.
As long as we have no metrics, all trust/revocation logic is a TrustGraph user's responsibility.
- How do I set all weights to untrusted and then increase trust in a peer over time?
- All peers are untrusted by default. Trust is unmeasured, weight represents how far the peer is from the root, the bigger weight, the closer to the root, so if you want to increase the weight of the target peer, you should obtain the trust from the root or peers who are closer to the root than this peer.
- How do I know that other peers are using the same processes to update weights?
- Weights calculated **locally** based on certificates that contain immutable signed trusts. Weights are subjective and have meaning only locally to this exact peer.
- Can I start my own instance of a trust graph or is there only a global version available?
- Every Fluence node is bundled with a builtin TrustGraph instance, but you can change or remove any service you want if you're a node owner.
## API
High-level API is defined in the [trust-graph-api.aqua](./aqua/trust-graph-api.aqua) module. API Reference soon will be available in the documentation.
High-level API is defined in the [trust-graph-api.aqua](./aqua/trust-graph-api.aqua) module.
## Directory structure
@ -305,7 +22,7 @@ High-level API is defined in the [trust-graph-api.aqua](./aqua/trust-graph-api.a
- [`keypair`](./keypair) directory is an abstracted cryptographical layer (key pairs, public keys, signatures, etc.)
- [`service`](./service) is a package that provides `marine` API and could be compiled to a Wasm file. It uses` SQLite` as storage
- [`service`](./service) is a package that provides `marine` API and could be compiled to a Wasm file. It is uses `SQLite` as storage
- [`example`](./example) is a `js` script that shows how to use Trust Graph to label peers
@ -318,3 +35,32 @@ High-level API is defined in the [trust-graph-api.aqua](./aqua/trust-graph-api.a
* [Aqua Book](https://fluence.dev/aqua-book/)
* [Aqua Playground](https://github.com/fluencelabs/aqua-playground)
* [Aqua repo](https://github.com/fluencelabs/aqua)
## How to use in Aqua
```
import "@fluencelabs/trust-graph/trust-graph-api.aqua"
import "@fluencelabs/trust-graph/trust-graph.aqua"
func my_function(peer_id: string) -> u32:
on HOST_PEER_ID:
result <- get_weight(peer_id)
<- result
```
## How to use is js
1. Add the following to your dependencies
- `@fluencelabs/trust-graph`
- `@fluencelabs/aqua`
- `@fluencelabs/aqua-lib`
- `@fluencelabs/fluence`
- `@fluencelabs/fluence-network-environment`
2. Import dependencies
```typescript
import * as tg from "./generated/export";
import { Fluence, KeyPair } from "@fluencelabs/fluence";
import { krasnodar, Node } from "@fluencelabs/fluence-network-environment";
```
3. Add root and issue root trust.
4. For now, trusts/revocations can only be signed by client's private key.

View File

@ -60,23 +60,22 @@ async function main(environment: Node[]) {
console.log("Issuer private key: %s", issuer_sk_b58);
let cur_time = await timestamp_sec(node);
let expires_at = cur_time + 60 * 60 * 24 * 365 * 2;
let expires_at = cur_time + 60 * 60 * 24 * 365;
let certificates = [];
let common_chain = [] as any;
// self-signed root trust
let root_trust = await issue_trust_helper(node, root_kp, root_kp.Libp2pPeerId.toB58String(), root_kp.Libp2pPeerId.toB58String(), expires_at, cur_time);
common_chain.push(await issue_trust_helper(node, root_kp, root_kp.Libp2pPeerId.toB58String(), root_kp.Libp2pPeerId.toB58String(), expires_at, cur_time));
// from root to issuer
let issuer_trust = await issue_trust_helper(node, root_kp, root_kp.Libp2pPeerId.toB58String(), issuer_kp.Libp2pPeerId.toB58String(), expires_at, cur_time);
common_chain.push(await issue_trust_helper(node, root_kp, root_kp.Libp2pPeerId.toB58String(), issuer_kp.Libp2pPeerId.toB58String(), expires_at, cur_time));
// from root to example
let example_trust = await issue_trust_helper(node, root_kp, root_kp.Libp2pPeerId.toB58String(), example_kp.Libp2pPeerId.toB58String(), expires_at, cur_time);
// cert for example key
certificates.push({chain: [root_trust, example_trust]});
let trust = await issue_trust_helper(node, root_kp, root_kp.Libp2pPeerId.toB58String(), example_kp.Libp2pPeerId.toB58String(), expires_at, cur_time);
let cert = {chain: [...common_chain, trust]};
certificates.push(cert);
for (let i = 0; i < krasnodar.length; i++) {
// from issuer to node
let node_trust = await issue_trust_helper(node, issuer_kp, issuer_kp.Libp2pPeerId.toB58String(), krasnodar[i].peerId, expires_at, cur_time);
// cert for every krasnodar node
let cert = {chain: [root_trust, issuer_trust, node_trust]};
let trust = await issue_trust_helper(node, issuer_kp, issuer_kp.Libp2pPeerId.toB58String(), krasnodar[i].peerId, expires_at, cur_time);
let cert = {chain: [...common_chain, trust]};
certificates.push(cert);
}

11041
admin/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -13,10 +13,10 @@
"author": "Fluence Labs",
"license": "MIT",
"dependencies": {
"@fluencelabs/aqua": "^0.9.1-374",
"@fluencelabs/aqua-lib": "^0.6.0",
"@fluencelabs/fluence": "^0.27.5",
"@fluencelabs/fluence-network-environment": "^1.0.13",
"@fluencelabs/aqua": "^0.5.2-257",
"@fluencelabs/aqua-lib": "^0.3.2",
"@fluencelabs/fluence": "^0.18.0",
"@fluencelabs/fluence-network-environment": "^1.0.10",
"@fluencelabs/trust-graph": "file:../aqua",
"bs58": "^4.0.1"
},

View File

@ -1,39 +0,0 @@
import "misc.aqua"
import get_host_certs_from from "trust-graph-api.aqua"
alias Error: string
-- TrustGraph builtin distributed with predefined certificates which used to identify Fluence Labs peers.
-- Each certificate contains 3 trusts: self-signed fluence root trust, trust for label trust and trust to target peer.
--
-- Usage:
-- on target_node:
-- result, error <- isFluencePeer()
--
-- Returns:
-- `true, nil` if `target_node` is identified as official Fluence Labs peer
-- `false, nil` otherwise
--
-- Errors:
-- if get_host_certs_from failed, `nil, error_msg` is returned
func isFluencePeer() -> ?bool, ?Error:
fluence_root_peer_id = "12D3KooWNbZKaPWRZ8wgjGvrxdJFz9Fq5uVwkR6ERV1f74HhPdyB"
label_peer_id = "12D3KooWM45u7AQxsb4MuQJNYT3NWHHMLU7JTbBV66RTfF3KSzdR"
result: ?bool
error: *Error
-- get all certs issued by `label_peer_id` to current host
certs_result <- get_host_certs_from(label_peer_id)
if certs_result.success:
for cert <- certs_result.certificates:
len <- TrustOp.array_length(cert.chain)
if len == 3:
if cert.chain!0.issued_for == fluence_root_peer_id:
if cert.chain!1.issued_for == label_peer_id:
result <<- true
if result == nil:
result <<- false
else:
error <<- certs_result.error
<- result, error

View File

@ -1,15 +1,8 @@
import "trust-graph.aqua"
alias Error: string
-- helpers for isFluencePeer
service TrustOp("op"):
array_length(a: []Trust) -> u32
service BoolOp("op"):
array_length(a: []bool) -> u32
-- check if error is not nil and append to error_stream
func append_error(error_stream: *Error, error: ?Error):
if error != nil:
error_stream <<- error!

9335
aqua/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@
"*.aqua"
],
"dependencies": {
"@fluencelabs/aqua-lib": "^0.5.2"
"@fluencelabs/aqua-lib": "^0.3.1"
},
"scripts": {
"generate-aqua": "../service/build.sh",
@ -31,6 +31,6 @@
},
"homepage": "https://github.com/fluencelabs/trust-graph#readme",
"devDependencies": {
"@fluencelabs/aqua": "^0.7.4-322"
"@fluencelabs/aqua": "^0.5.2-257"
}
}

View File

@ -1,11 +1,11 @@
import Sig, Peer, PeerId from "@fluencelabs/aqua-lib/builtin.aqua"
import "misc.aqua"
import "trust-graph.aqua"
import "misc.aqua"
import Sig, Peer from "@fluencelabs/aqua-lib/builtin.aqua"
alias PeerId: string
alias Error: string
-- Call context: any node with registered `trust-graph` service
-- Set `peer_id` as a root
-- Set peer_id as a root to TG instance on current node
-- Self-signed trust should be added in next call for correct behaviour
-- `max_chain_len` specifies maximum chain length after root trust,
-- if `max_chain_len` is zero there is no trusts except self-signed root trust in certificates for this root
@ -13,146 +13,138 @@ func set_root(peer_id: PeerId, max_chain_len: u32) -> SetRootResult:
result <- TrustGraph.set_root(peer_id, max_chain_len)
<- result
-- Call context: %init_peer_id%
-- Create on relay and sign trust on client
-- If `issuer` is not %init_peer_id%, Sig service with `issuer` peer id as service id should be defined
-- Errors:
-- If TrustGraph.get_trust_bytes or TrustGraph.issue_trust fails, (nil, error) is returned.
func issue_trust(issuer: PeerId, issued_for: PeerId, expires_at_sec: u64) -> ?Trust, ?Error:
-- after marine-web release this will be done on %init_peer_id%
-- Create and sign trust with private key from 'sig_id' service
-- If `sig_id` is nil, default Sig service will be used with %init_peer_id% private key
func issue_trust(issued_for: PeerId, expires_at_sec: u64, sig_id: ?string) -> ?Trust, ?Error:
on HOST_PEER_ID:
issued_at_sec <- Peer.timestamp_sec()
bytes <- TrustGraph.get_trust_bytes(issued_for, expires_at_sec, issued_at_sec)
result: ?Trust
error: *Error
error: ?string
if bytes.success:
Sig issuer
sig_res <- Sig.sign(bytes.result)
if sig_res.success:
on HOST_PEER_ID:
issue_result <- TrustGraph.issue_trust(issued_for, expires_at_sec, issued_at_sec, sig_res.signature!)
if issue_result.success:
result <<- issue_result.trust
else:
error <<- issue_result.error
sig_service: ?string
if sig_id != nil:
sig_service <<- sig_id!
else:
error <<- sig_res.error!
sig_service <<- "sig"
Sig sig_service!
signature <- Sig.sign(bytes.result)
on HOST_PEER_ID:
issue_result <- TrustGraph.issue_trust(issued_for, expires_at_sec, issued_at_sec, signature)
if issue_result.success:
result <<- issue_result.trust
else:
error <<- issue_result.error
else:
error <<- bytes.error
<- result, error
-- Call context: any node with registered `trust-graph` service
-- Add trust to TG
-- Errors:
-- If TrustGraph.add_trust fails, error is returned.
-- Add trust to TG instance on current node
func import_trust(trust: Trust, issuer: PeerId) -> ?Error:
error: *Error
error: ?string
timestamp_sec <- Peer.timestamp_sec()
add_result <- TrustGraph.add_trust(trust, issuer, timestamp_sec)
if add_result.success != true:
error <<- add_result.error
<- error
-- Call context: %init_peer_id%
-- Issue trust and add to TG instance on `node`
-- If `issuer` is not %init_peer_id%, Sig service with `issuer` peer id as service id should be defined
-- Errors:
-- If issue_trust or import_trust fails, error is returned.
-- If `issuer` != %init_peer_id%, Sig service should be registered with issuer's peer id as a service id.
func add_trust(node: PeerId, issuer: PeerId, issued_for: PeerId, expires_at_sec: u64) -> ?Error:
trust, issue_error <- issue_trust(issuer, issued_for, expires_at_sec)
sig_service: ?string
if issuer != %init_peer_id%:
sig_service <<- issuer
error: *Error
if issue_error != nil:
error <<- issue_error!
trust, issue_error <- issue_trust(issued_for, expires_at_sec, sig_service)
error: *?Error
if trust == nil:
error <<- issue_error
else:
on node:
import_error <- import_trust(trust!, issuer)
append_error(error, import_error)
<- error
error <- import_trust(trust!, issuer)
<- error!
-- Call context: %init_peer_id%
-- Set `peer_id` as a root and add self-signed trust to TG instance on `node`
-- If `peer_id` is not %init_peer_id%, Sig service with `peer_id` as service id should be defined
-- Errors:
-- If issue_trust, import_trust or set_root fails, error is returned.
-- If `peer_id` != %init_peer_id%, Sig service should be registered with this peer id as a service id.
func add_root_trust(node: PeerId, peer_id: PeerId, max_chain_len: u32, expires_at_sec: u64) -> ?Error:
trust, issue_error <- issue_trust(peer_id, peer_id, expires_at_sec)
sig_service: ?string
if peer_id != %init_peer_id%:
sig_service <<- peer_id
error: *Error
if issue_error != nil:
error <<- issue_error!
trust, issue_error <- issue_trust(peer_id, expires_at_sec, sig_service)
error: *?Error
if trust == nil:
error <<- issue_error
else:
on node:
set_root_result <- set_root(peer_id, max_chain_len)
if set_root_result.success:
import_error <- import_trust(trust!, peer_id)
append_error(error, import_error)
error <- import_trust(trust!, peer_id)
else:
error <<- set_root_result.error
-- converting string to ?string
tmp: *string
tmp <<- set_root_result.error
error <<- tmp
<- error
<- error!
-- Call context: any node with registered `trust-graph` service
-- Check signature and expiration time of trust
func verify_trust(trust: Trust, issuer: PeerId) -> VerifyTrustResult:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.verify_trust(trust, issuer, timestamp_sec)
<- result
-- Call context: any node with registered `trust-graph` service
-- Get the maximum weight of trust for `peer_id`
-- Get the maximum weight of trust for one peer id
-- Trust has weight if there is at least 1 trust chain from one of the roots
func get_weight(peer_id: PeerId) -> WeightResult:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.get_weight(peer_id, timestamp_sec)
<- result
-- Call context: any node with registered `trust-graph` service
-- Get maximum weight of trust for `peer_id` among all chains which contain trust from `issuer`
-- Get maximum weight of trust among all chains which contain trust from `issuer`
func get_weight_from(peer_id: PeerId, issuer: PeerId) -> WeightResult:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.get_weight_from(peer_id, issuer, timestamp_sec)
<- result
-- Call context: %init_peer_id%
-- Create revocation signed by %init_peer_id%
-- If `revoked_by` is not %init_peer_id%, Sig service with `revoked_by` peer id as service id should be defined
-- Errors:
-- If TrustGraph.get_revocation_bytes or TrustGraph.issue_revocation fails, (nil, error) is returned.
func issue_revocation(revoked_by: PeerId, revoked: PeerId) -> ?Revocation, ?Error:
-- after marine-web release this will be done on %init_peer_id%
-- If `sig_id` is nil, default Sig service will be used with %init_peer_id% private key
func issue_revocation(revoked_by: PeerId, revoked: PeerId, sig_id: ?string) -> ?Revocation, ?Error:
on HOST_PEER_ID:
issued_at_sec <- Peer.timestamp_sec()
bytes <- TrustGraph.get_revocation_bytes(revoked, issued_at_sec)
result: ?Revocation
error: *Error
error: ?string
if bytes.success:
Sig revoked_by
sig_res <- Sig.sign(bytes.result)
if sig_res.success:
on HOST_PEER_ID:
issue_result <- TrustGraph.issue_revocation(revoked_by, revoked, issued_at_sec, sig_res.signature!)
if issue_result.success:
result <<- issue_result.revocation
else:
error <<- issue_result.error
sig_service: ?string
if sig_id != nil:
sig_service <<- sig_id!
else:
error <<- sig_res.error!
sig_service <<- "sig"
Sig sig_service!
signature <- Sig.sign(bytes.result)
on HOST_PEER_ID:
issue_result <- TrustGraph.issue_revocation(revoked_by, revoked, issued_at_sec, signature)
if issue_result.success:
result <<- issue_result.revocation
else:
error <<- issue_result.error
else:
error <<- bytes.error
<- result, error
-- Call context: any node with registered `trust-graph` service
-- Import revocation to TG
-- Errors:
-- If TrustGraph.revoke fails, error is returned.
-- Import revocation to current node's TG instance
func import_revocation(revocation: Revocation) -> ?Error:
error: *Error
error: ?string
timestamp_sec <- Peer.timestamp_sec()
add_result <- TrustGraph.revoke(revocation, timestamp_sec)
if add_result.success != true:
@ -160,55 +152,72 @@ func import_revocation(revocation: Revocation) -> ?Error:
<- error
-- Call context: %init_peer_id%
-- Revoke all certificates on `node` TG instance
-- which contain path from %init_peer_id% to `revoked_peer_id`
-- If `revoked_by` is not %init_peer_id%, Sig service with `revoked_by` peer id as service id should be defined
-- Errors:
-- if issue_revocation or import_revocation fails, error is returned.
-- If `revoked_by` != %init_peer_id%, Sig service should be registered with this peer id as a service id.
func revoke(node: PeerId, revoked_by: PeerId, revoked: PeerId) -> ?Error:
revocation, issue_error <- issue_revocation(revoked_by, revoked)
sig_service: ?string
if revoked_by != %init_peer_id%:
sig_service <<- revoked_by
error: *Error
revocation, issue_error <- issue_revocation(revoked_by, revoked, sig_service)
error: *?string
if revocation == nil:
error <<- issue_error!
error <<- issue_error
else:
on node:
import_error <- import_revocation(revocation!)
append_error(error, import_error)
<- error
error <- import_revocation(revocation!)
<- error!
-- Call context: any node with registered `trust-graph` service
-- Return all certificates issued for current node which contains trust from `issuer`
func get_host_certs_from(issuer: PeerId) -> AllCertsResult:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.get_host_certs_from(issuer, timestamp_sec)
<- result
-- Call context: any node with registered `trust-graph` service
-- Return all certificates issued for given peer id
func get_all_certs(issued_for: PeerId) -> AllCertsResult:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.get_all_certs(issued_for, timestamp_sec)
<- result
-- Call context: any node with registered `trust-graph` service
-- Return all certificates issued for given peer id which contains trust from `issuer`
func get_all_certs_from(issued_for: PeerId, issuer: PeerId) -> AllCertsResult:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.get_all_certs_from(issued_for, issuer, timestamp_sec)
<- result
-- Call context: any node with registered `trust-graph` service
-- Return all certificates issued for current node
func get_host_certs() -> AllCertsResult:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.get_host_certs(timestamp_sec)
<- result
-- Call context: any node with registered `trust-graph` service
-- Insert certificate to TG instance on current node
func insert_cert(certificate: Certificate) -> InsertResult:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.insert_cert(certificate, timestamp_sec)
<- result
-- returns `true` if current node is identified as official Fluence Labs peer
-- returns `false` otherwise
func isFluencePeer() -> ?bool, ?Error:
certs_result <- get_host_certs_from("12D3KooWM45u7AQxsb4MuQJNYT3NWHHMLU7JTbBV66RTfF3KSzdR")
result: ?bool
error: ?string
if certs_result.success:
for cert <- certs_result.certificates:
len <- TrustOp.array_length(cert.chain)
if len == 3:
if cert.chain!0.issued_for == "12D3KooWNbZKaPWRZ8wgjGvrxdJFz9Fq5uVwkR6ERV1f74HhPdyB":
if cert.chain!1.issued_for == "12D3KooWM45u7AQxsb4MuQJNYT3NWHHMLU7JTbBV66RTfF3KSzdR":
result <<- true
if result == nil:
result <<- false
else:
error <<- certs_result.error
<- result, error

View File

@ -1,6 +1,5 @@
(seq
(seq
; set fluence root peer id as TG root
(call relay ("trust-graph" "set_root") ["12D3KooWNbZKaPWRZ8wgjGvrxdJFz9Fq5uVwkR6ERV1f74HhPdyB" 5] add_root_res)
(xor
(match add_root_res.$.success! true
@ -15,7 +14,6 @@
(seq
(seq
(call relay ("peer" "timestamp_sec") [] cur_time)
; insert all certificates from on_start.json
(call relay ("trust-graph" "insert_cert") [i cur_time] insert_result)
)
(xor

File diff suppressed because one or more lines are too long

View File

@ -1,49 +1,10 @@
## Description
This example shows how to use Trust Graph for code execution only on trusted peers. There are some `trusted_computation` which can only be performed on a trusted peer. The label is determined by the presence of the certificate from `INIT_PEER_ID` to this peer. We use peer id from [`example_secret_key.ed25519`](../example_secret_key.ed25519) as `INIT_PEER_ID` since every node bundled with the certificate issued to this key, it should be used only for test purposes.
## Run example on network
1. Run `npm i`
2. Run `npm run start`
## Run example on network
1. Run `npm i`
2. Run `npm run start`
This example shows how to use Trust Graph to label peers. There are some `trusted_computation` which can only be executed
on labeled peer. The label is determined by the presence of certificate from `%init_peer_id` to this peer.
## Run example locally
1. Go to `local-network`
2. Run `docker compose up -d` to start Fluence node
3. It takes some time depending on your machine for node to start and builtin services deployed. Wait for this log line: `[2022-07-06T11:33:50.782054Z INFO particle_node] Fluence has been successfully started.`
4. Go back to `../example`
5. Run `npm i`
6. Run `npm run start local`
## Expected output
After successful execution you will get this result:
```
In this example we try to execute some trusted computations based on trusts
📘 Will connect to testNet
📗 created a fluence peer 12D3KooWD2vAZva1u3TQgoxebBUBsaGMNawKjVkp57M6UcwNwXNv with relay 12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9
📕 Trusted computation on node 12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9 failed, error: there is no certs for this peer
📕 Trusted computation on node 12D3KooWMhVpgfQxBLkQkJed8VFNvgN4iE6MD7xCybb1ZYWW2Gtz failed, error: there is no certs for this peer
📕 Trusted computation on node 12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er failed, error: there is no certs for this peer
🌀 Issue trust to nodeB 12D3KooWMhVpgfQxBLkQkJed8VFNvgN4iE6MD7xCybb1ZYWW2Gtz and nodeC: 12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er
Trust issued for 12D3KooWMhVpgfQxBLkQkJed8VFNvgN4iE6MD7xCybb1ZYWW2Gtz successfully added
Trust issued for 12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er successfully added
📕 Trusted computation on node 12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9 failed, error: there is no certs for this peer
📗 Trusted computation on node 12D3KooWMhVpgfQxBLkQkJed8VFNvgN4iE6MD7xCybb1ZYWW2Gtz successful, result is 5
📗 Trusted computation on node 12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er successful, result is 5
🚫 Revoke trust to nodeB
Trust issued for 12D3KooWMhVpgfQxBLkQkJed8VFNvgN4iE6MD7xCybb1ZYWW2Gtz revoked
📕 Trusted computation on node 12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9 failed, error: there is no certs for this peer
📕 Trusted computation on node 12D3KooWMhVpgfQxBLkQkJed8VFNvgN4iE6MD7xCybb1ZYWW2Gtz failed, error: there is no certs for this peer
📗 Trusted computation on node 12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er successful, result is 5
```
3. Go back to `../example`
4. Run `npm i`
5. Run `npm run start`

View File

@ -11,9 +11,8 @@ service CertOp("op"):
service TrustedComputation("op"):
identity(s: u64) -> u64
func trusted_computation(node: string) -> ?u64, ?string:
func trusted_computation(node: string) -> ?u64:
result: ?u64
error: ?string
-- on our trusted relay
on HOST_PEER_ID:
-- get all certificates issued for given node by our client's peer id
@ -21,11 +20,8 @@ func trusted_computation(node: string) -> ?u64, ?string:
if certs_result.success:
len <- CertOp.array_length(certs_result.certificates)
-- if there is any certificate node is trusted and computation is possible
if len != 0:
on node:
result <- TrustedComputation.identity(5)
else:
error <<- "there is no certs for this peer"
else:
error <<- certs_result.error
<- result, error
if len != 0:
on node:
result <- TrustedComputation.identity(5)
<- result

View File

@ -1,6 +1,5 @@
module Export
import add_root_trust, add_trust, revoke from "@fluencelabs/trust-graph/trust-graph-api.aqua"
export add_root_trust, add_trust, revoke, timestamp_sec
export add_root_trust, add_trust, revoke
import Peer from "@fluencelabs/aqua-lib/builtin.aqua"
alias PeerId: string
@ -9,3 +8,6 @@ func timestamp_sec() -> u64:
on HOST_PEER_ID:
result <- Peer.timestamp_sec()
<- result
service Sig:
sign(msg: []u8) -> []u8

View File

@ -14,11 +14,12 @@
* limitations under the License.
*/
import { trusted_computation } from "./generated/computation";
import {trusted_computation} from "./generated/computation";
import * as tg from "./generated/export";
import { Fluence, FluencePeer, KeyPair } from "@fluencelabs/fluence";
import { krasnodar, Node, testNet, stage } from "@fluencelabs/fluence-network-environment";
import {Fluence, FluencePeer, KeyPair} from "@fluencelabs/fluence";
import {krasnodar, Node, testNet, stage} from "@fluencelabs/fluence-network-environment";
import assert from "assert";
import {add_root_trust, registerSig} from "./generated/export";
const bs58 = require('bs58');
let local: Node[] = [
@ -39,14 +40,19 @@ let local: Node[] = [
},
];
async function revoke_all(relay: string, revoked_by: string, nodes: Node[]) {
for (var node of nodes) {
async function revoke_all(relay: string, revoked_by: string) {
for (var node of local) {
let error = await tg.revoke(relay, revoked_by, node.peerId);
if (error !== null) {
console.log(error)
}
console.log(error)
assert(error == null);
}
}
async function add_root(relay: string, peer_id: string) {
let current_time = await tg.timestamp_sec();
let far_future = current_time + 9999999;
let error = await tg.add_root_trust(relay, peer_id, 2, far_future);
assert(error == null);
}
async function add_new_trust_checked(relay: string, issuer: string, issued_for_peer_id: string, expires_at_sec: number) {
let error = await tg.add_trust(relay, issuer, issued_for_peer_id, expires_at_sec);
@ -67,23 +73,24 @@ async function revoke_checked(relay: string, revoked_by: string, revoked_peer_id
}
async function exec_trusted_computation(node: string) {
let [result, error] = await trusted_computation(node)
let result = await trusted_computation(node)
if (result !== null) {
console.log("📗 Trusted computation on node %s successful, result is %s", node, result)
} else {
console.log("📕 Trusted computation on node %s failed, error:", node, error)
console.log("📕 Trusted computation on node %s failed", node)
}
}
async function main(nodes: Node[]) {
// example_secret_key.ed25519
let sk = bs58.decode("E5ay3731i4HN8XjJozouV92RDMGAn3qSnb9dKSnujiWv");
async function main() {
console.log("In this example we try to execute some trusted computations based on trusts");
console.log("📘 Will connect to local nodes");
// key from local-network/builtins_secret_key.ed25519 to connect as builtins owner
let sk = bs58.decode("5FwE32bDcphFzuMca7Y2qW1gdR64fTBYoRNvD4MLE1hecDGhCMQGKn8aseMr5wRo4Xo2CRFdrEAawUNLYkgQD78K").slice(0, 32); // first 32 bytes - secret key, second - public key
let builtins_keypair = await KeyPair.fromEd25519SK(sk);
let relay = nodes[0];
await Fluence.start({ connectTo: relay, KeyPair: builtins_keypair });
let relay = local[0];
await Fluence.start({ connectTo: relay, KeyPair: builtins_keypair});
console.log(
"📗 created a fluence peer %s with relay %s",
Fluence.getStatus().peerId,
@ -96,55 +103,41 @@ async function main(nodes: Node[]) {
let far_future = current_time + 9999999;
// clear all trusts from our peer id on relay
await revoke_all(relay.peerId, local_peer_id, nodes.slice(0, 3));
await revoke_all(relay.peerId, local_peer_id);
// wait to be sure that last revocation will be older than future trusts at least on 1 second (because timestamp in secs)
await new Promise(f => setTimeout(f, 1000));
let nodeA = nodes[0].peerId
let nodeB = nodes[1].peerId
let nodeC = nodes[2].peerId
// set our peer id as root to our relay
await add_root(relay.peerId, local_peer_id);
let nodeA = local[0].peerId
let nodeB = local[1].peerId
let nodeC = local[2].peerId
console.log();
// try to exec computation on every node, will fail
await exec_trusted_computation(nodeA); // fail
await exec_trusted_computation(nodeB); // fail
await exec_trusted_computation(nodeC); // fail
console.log();
console.log("🌀 Issue trust to nodeB %s and nodeC: %s", nodeB, nodeC);
console.log("🌀 Issue trust to nodeB: %s", nodeB);
await add_new_trust_checked(relay.peerId, local_peer_id, nodeB, far_future);
await add_new_trust_checked(relay.peerId, local_peer_id, nodeC, far_future);
console.log();
await exec_trusted_computation(nodeA); // fail
await exec_trusted_computation(nodeB); // success
await exec_trusted_computation(nodeC); // success
console.log();
await exec_trusted_computation(nodeC); // fail
await new Promise(f => setTimeout(f, 1000));
console.log("🚫 Revoke trust to nodeB");
await revoke_checked(relay.peerId, local_peer_id, nodeB);
console.log();
await exec_trusted_computation(nodeA); // fail
await exec_trusted_computation(nodeB); // fail
await exec_trusted_computation(nodeC); // success
await exec_trusted_computation(nodeC); // fail
return;
}
console.log("In this example we try to execute some trusted computations based on trusts");
let args = process.argv.slice(2);
var environment: Node[];
if (args.length >= 1 && args[0] == "local") {
environment = local;
console.log("📘 Will connect to local nodes");
} else {
environment = testNet;
console.log("📘 Will connect to testNet");
}
main(environment)
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);

8294
example/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -13,14 +13,14 @@
"author": "Fluence Labs",
"license": "MIT",
"dependencies": {
"@fluencelabs/aqua-lib": "^0.5.2",
"@fluencelabs/fluence": "^0.23.0",
"@fluencelabs/aqua": "^0.5.2-257",
"@fluencelabs/aqua-lib": "^0.3.2",
"@fluencelabs/fluence": "^0.18.0",
"@fluencelabs/fluence-network-environment": "^1.0.10",
"@fluencelabs/trust-graph": "3.0.2",
"@fluencelabs/trust-graph": "file:../aqua",
"bs58": "^4.0.1"
},
"devDependencies": {
"typescript": "^4.5.2",
"@fluencelabs/aqua": "^0.7.4-325"
"typescript": "^4.5.2"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 295 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

View File

@ -1,24 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.8.1] - 2022-10-06
### Added
- *(keypair)* add KeyPair::from_secret_key (#50)
### Other
- set version of fluence-keypair to 0.8.0
- fluence-keypair 0.8.0
- libp2p-core 0.33.0 (#49)
- remove circle, update gh, add lints; remove warnings (#43)
- fluence-keypair 0.6.0
- libp2p-core 0.31.0 (from crates.io) (#37)
- Remove serde version lock (#15)
- Fix revocations logic (#34)
- Trust Graph: implement WASM built-in (#18)
- Move fluence-identity to fluence-keypair (#17)

1497
keypair/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
[package]
name = "fluence-keypair"
version = "0.8.1"
version = "0.5.1"
authors = ["Fluence Labs"]
edition = "2018"
description = "identity"
@ -8,7 +8,7 @@ license = "Apache-2.0"
repository = "https://github.com/fluencelabs/trust-graph"
[dependencies]
serde = { version = "1.0.118", features = ["derive"] }
serde = { version = "=1.0.118", features = ["derive"] }
serde_json = "1.0.58"
bs58 = "0.3.1"
ed25519-dalek = { version = "1.0.1", features = ["serde", "std"] }
@ -18,12 +18,12 @@ ed25519 = "1.0.3"
serde_with = "1.6.0"
thiserror = "1.0.23"
lazy_static = "1.2"
libsecp256k1 = "0.7.1"
libsecp256k1 = "0.3.1"
asn1_der = "0.6.1"
sha2 = "0.9.1"
zeroize = "1"
serde_bytes = "0.11"
libp2p-core = { workspace = true }
libp2p-core = { package = "fluence-fork-libp2p-core", version = "0.27.2", features = ["secp256k1"]}
eyre = "0.6.5"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]

View File

@ -1,3 +0,0 @@
[toolchain]
channel = "nightly-2022-08-30"
targets = [ "x86_64-apple-darwin", "x86_64-unknown-linux-gnu" ]

View File

@ -68,7 +68,7 @@ pub enum SigningError {
Secp256k1(
#[from]
#[source]
libsecp256k1::Error,
secp256k1::Error,
),
}
@ -83,5 +83,5 @@ pub enum VerificationError {
Rsa(#[source] ring::error::Unspecified, String, String),
#[error("Failed to verify signature {1} with {2} secp256k1 public key: {0}")]
Secp256k1(#[source] libsecp256k1::Error, String, String),
Secp256k1(#[source] secp256k1::Error, String, String),
}

View File

@ -219,17 +219,6 @@ impl KeyPair {
}
}
pub fn from_secret_key(bytes: Vec<u8>, format: KeyFormat) -> Result<Self, DecodingError> {
use KeyPair::*;
match format {
KeyFormat::Ed25519 => Ok(Ed25519(ed25519::SecretKey::from_bytes(bytes)?.into())),
KeyFormat::Secp256k1 => Ok(Secp256k1(secp256k1::SecretKey::from_bytes(bytes)?.into())),
#[cfg(not(target_arch = "wasm32"))]
KeyFormat::Rsa => Err(DecodingError::KeypairDecodingIsNotSupported),
}
}
pub fn get_peer_id(&self) -> PeerId {
self.public().to_peer_id()
}

View File

@ -109,7 +109,7 @@ impl PublicKey {
}
pub fn to_peer_id(&self) -> PeerId {
PeerId::from_public_key(&self.clone().into())
PeerId::from_public_key(self.clone().into())
}
pub fn get_key_format(&self) -> KeyFormat {
@ -164,26 +164,13 @@ impl TryFrom<libp2p_core::PeerId> for PublicKey {
type Error = DecodingError;
fn try_from(peer_id: libp2p_core::PeerId) -> Result<Self, Self::Error> {
Ok(as_public_key(&peer_id)
.ok_or_else(|| DecodingError::PublicKeyNotInlined(peer_id.to_base58()))?
Ok(peer_id
.as_public_key()
.ok_or(DecodingError::PublicKeyNotInlined(peer_id.to_base58()))?
.into())
}
}
/// Convert PeerId to libp2p's PublicKey
fn as_public_key(peer_id: &PeerId) -> Option<libp2p_core::PublicKey> {
use libp2p_core::multihash;
let mhash = peer_id.as_ref();
match multihash::Code::try_from(mhash.code()) {
Ok(multihash::Code::Identity) => {
libp2p_core::PublicKey::from_protobuf_encoding(mhash.digest()).ok()
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@ -23,8 +23,8 @@ use crate::error::{DecodingError, SigningError, VerificationError};
use asn1_der::{DerObject, FromDerObject};
use core::fmt;
use libsecp256k1::Message;
use rand::RngCore;
use secp256k1::Message;
use serde::de::Error as SerdeError;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_bytes::{ByteBuf as SerdeByteBuf, Bytes as SerdeBytes};
@ -66,7 +66,7 @@ impl fmt::Debug for Keypair {
/// Promote a Secp256k1 secret key into a keypair.
impl From<SecretKey> for Keypair {
fn from(secret: SecretKey) -> Self {
let public = PublicKey(libsecp256k1::PublicKey::from_secret_key(&secret.0));
let public = PublicKey(secp256k1::PublicKey::from_secret_key(&secret.0));
Keypair { secret, public }
}
}
@ -80,7 +80,7 @@ impl From<Keypair> for SecretKey {
/// A Secp256k1 secret key.
#[derive(Clone)]
pub struct SecretKey(libsecp256k1::SecretKey);
pub struct SecretKey(secp256k1::SecretKey);
impl fmt::Debug for SecretKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@ -92,12 +92,12 @@ impl SecretKey {
/// Generate a new Secp256k1 secret key.
pub fn generate() -> Self {
let mut r = rand::thread_rng();
let mut b = [0; libsecp256k1::util::SECRET_KEY_SIZE];
let mut b = [0; secp256k1::util::SECRET_KEY_SIZE];
// This is how it is done in `secp256k1::SecretKey::random` which
// we do not use here because it uses `rand::Rng` from rand-0.4.
loop {
r.fill_bytes(&mut b);
if let Ok(k) = libsecp256k1::SecretKey::parse(&b) {
if let Ok(k) = secp256k1::SecretKey::parse(&b) {
return SecretKey(k);
}
}
@ -108,8 +108,8 @@ impl SecretKey {
/// error is returned.
pub fn from_bytes(mut sk: impl AsMut<[u8]>) -> Result<Self, DecodingError> {
let sk_bytes = sk.as_mut();
let secret = libsecp256k1::SecretKey::parse_slice(&*sk_bytes)
.map_err(|_| DecodingError::Secp256k1)?;
let secret =
secp256k1::SecretKey::parse_slice(&*sk_bytes).map_err(|_| DecodingError::Secp256k1)?;
sk_bytes.zeroize();
Ok(SecretKey(secret))
}
@ -149,7 +149,7 @@ impl SecretKey {
/// ECDSA signature.
pub fn sign_hashed(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
let m = Message::parse_slice(msg).map_err(SigningError::Secp256k1)?;
Ok(libsecp256k1::sign(&m, &self.0)
Ok(secp256k1::sign(&m, &self.0)
.0
.serialize_der()
.as_ref()
@ -159,7 +159,7 @@ impl SecretKey {
/// A Secp256k1 public key.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct PublicKey(libsecp256k1::PublicKey);
pub struct PublicKey(secp256k1::PublicKey);
impl PublicKey {
/// Verify the Secp256k1 signature on a message using the public key.
@ -171,8 +171,7 @@ impl PublicKey {
pub fn verify_hashed(&self, msg: &[u8], sig: &[u8]) -> Result<(), VerificationError> {
Message::parse_slice(msg)
.and_then(|m| {
libsecp256k1::Signature::parse_der(sig)
.map(|s| libsecp256k1::verify(&m, &s, &self.0))
secp256k1::Signature::parse_der(sig).map(|s| secp256k1::verify(&m, &s, &self.0))
})
.map_err(|e| {
VerificationError::Secp256k1(
@ -198,7 +197,7 @@ impl PublicKey {
/// Decode a public key from a byte slice in the the format produced
/// by `encode`.
pub fn decode(bytes: &[u8]) -> Result<Self, DecodingError> {
libsecp256k1::PublicKey::parse_slice(bytes, Some(libsecp256k1::PublicKeyFormat::Compressed))
secp256k1::PublicKey::parse_slice(bytes, Some(secp256k1::PublicKeyFormat::Compressed))
.map_err(|_| DecodingError::Secp256k1)
.map(PublicKey)
}

View File

@ -7,7 +7,7 @@ services:
RUST_BACKTRACE: full
RUST_LOG: info,network=trace,aquamarine=info,aquamarine::actor=info,tokio_threadpool=info,tokio_reactor=info,mio=info,tokio_io=info,soketto=info,yamux=info,multistream_select=info,libp2p_secio=info,libp2p_websocket::framed=info,libp2p_ping=info,libp2p_core::upgrade::apply=info,libp2p_kad::kbucket=info,cranelift_codegen=info,wasmer_wasi=info,async_io=info,polling=info,wasmer_interface_types_fl=info,cranelift_codegen=info,wasmer_wasi=info,async_io=info,polling=info,wasmer_interface_types_fl=info,particle_server::behaviour::identify=info,libp2p_mplex=info,libp2p_identify=info,walrus=info,particle_protocol::libp2p_protocol::upgrade=info,kademlia::behaviour=info
WASM_LOG: info
image: fluencelabs/node:latest
image: fluencelabs/node:tg-hl-api_v345
ports:
- 7770:7770 # tcp
- 9990:9990 # ws
@ -29,7 +29,7 @@ services:
RUST_BACKTRACE: full
RUST_LOG: info,network=trace,aquamarine=info,aquamarine::actor=info,tokio_threadpool=info,tokio_reactor=info,mio=info,tokio_io=info,soketto=info,yamux=info,multistream_select=info,libp2p_secio=info,libp2p_websocket::framed=info,libp2p_ping=info,libp2p_core::upgrade::apply=info,libp2p_kad::kbucket=info,cranelift_codegen=info,wasmer_wasi=info,async_io=info,polling=info,wasmer_interface_types_fl=info,cranelift_codegen=info,wasmer_wasi=info,async_io=info,polling=info,wasmer_interface_types_fl=info,particle_server::behaviour::identify=info,libp2p_mplex=info,libp2p_identify=info,walrus=info,particle_protocol::libp2p_protocol::upgrade=info,kademlia::behaviour=info
WASM_LOG: info
image: fluencelabs/node:latest
image: fluencelabs/node:tg-hl-api_v345
ports:
- 7771:7771 # tcp
- 9991:9991 # ws
@ -51,7 +51,7 @@ services:
RUST_BACKTRACE: full
RUST_LOG: info,network=trace,aquamarine=info,aquamarine::actor=info,tokio_threadpool=info,tokio_reactor=info,mio=info,tokio_io=info,soketto=info,yamux=info,multistream_select=info,libp2p_secio=info,libp2p_websocket::framed=info,libp2p_ping=info,libp2p_core::upgrade::apply=info,libp2p_kad::kbucket=info,cranelift_codegen=info,wasmer_wasi=info,async_io=info,polling=info,wasmer_interface_types_fl=info,cranelift_codegen=info,wasmer_wasi=info,async_io=info,polling=info,wasmer_interface_types_fl=info,particle_server::behaviour::identify=info,libp2p_mplex=info,libp2p_identify=info,walrus=info,particle_protocol::libp2p_protocol::upgrade=info,kademlia::behaviour=info
WASM_LOG: info
image: fluencelabs/node:latest
image: fluencelabs/node:tg-hl-api_v345
ports:
- 7772:7772 # tcp
- 9992:9992 # ws

View File

@ -1,3 +1,3 @@
[toolchain]
channel = "nightly-2022-12-06"
targets = [ "x86_64-apple-darwin", "wasm32-wasi", "wasm32-unknown-unknown", "x86_64-unknown-linux-gnu" ]
channel = "nightly-2021-09-01"
targets = [ "x86_64-apple-darwin", "x86_64-unknown-linux-gnu" ]

View File

@ -1,30 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.3.1] - 2022-10-06
### Added
- *(keypair)* add KeyPair::from_secret_key (#50)
### Fixed
- fix bug get_all_certs_from, update example (#44)
- fix db paths (#28)
### Other
- set version of fluence-keypair to 0.8.0
- fluence-keypair 0.8.0
- libp2p-core 0.33.0 (#49)
- remove circle, update gh, add lints; remove warnings (#43)
- Add memory leak temporary mitigation (#42)
- High-level Aqua API (#35)
- fluence-keypair 0.6.0
- libp2p-core 0.31.0 (from crates.io) (#37)
- Fix revocations logic (#34)
- Remove mutex from TG instance (#31)
- refactoring (#30)
- Trust Graph: implement WASM built-in (#18)

View File

@ -1,11 +1,10 @@
[package]
name = "trust-graph-wasm"
version = "0.3.1"
version = "0.3.0"
authors = ["Fluence Labs"]
edition = "2018"
description = "trust graph wasm"
license = "Apache-2.0"
publish = false
[[bin]]
name = "trust-graph"
@ -13,11 +12,11 @@ path = "src/main.rs"
[dependencies]
trust-graph = { version = "0.3.0", path = "../." }
fluence-keypair = { version = "0.8.1", path = "../keypair" }
fluence-keypair = { version = "0.5.0", path = "../keypair" }
marine-rs-sdk = { version = "0.6.14", features = ["logger"] }
marine-sqlite-connector = "0.5.2"
libp2p-core = { workspace = true }
libp2p-core = { package = "fluence-fork-libp2p-core", version = "0.27.2", features = ["secp256k1"]}
log = "0.4.8"
anyhow = "1.0.31"

View File

@ -15,5 +15,5 @@ cp ../target/wasm32-wasi/release/trust-graph.wasm artifacts/
# download SQLite 3 to use in tests
curl -L https://github.com/fluencelabs/sqlite/releases/download/v0.15.0_w/sqlite3.wasm -o artifacts/sqlite3.wasm
# # generate Aqua bindings
# marine aqua artifacts/trust-graph.wasm -s TrustGraph -i trust-graph > ../aqua/trust-graph.aqua
# generate Aqua bindings
marine aqua artifacts/trust-graph.wasm -s TrustGraph -i trust-graph > ../aqua/trust-graph.aqua

View File

@ -1,3 +1,3 @@
[toolchain]
channel = "nightly-2022-12-06"
targets = [ "x86_64-apple-darwin", "wasm32-wasi", "wasm32-unknown-unknown", "x86_64-unknown-linux-gnu" ]
channel = "nightly-2021-09-01"
targets = [ "x86_64-apple-darwin", "x86_64-unknown-linux-gnu" ]

View File

@ -40,7 +40,7 @@ pub struct Certificate {
impl From<trust_graph::Certificate> for Certificate {
fn from(c: trust_graph::Certificate) -> Self {
let chain: Vec<Trust> = c.chain.into_iter().map(|t| t.into()).collect();
Certificate { chain }
return Certificate { chain };
}
}
@ -51,10 +51,10 @@ impl TryFrom<Certificate> for trust_graph::Certificate {
let chain: Result<Vec<trust_graph::Trust>, DtoConversionError> = c
.chain
.into_iter()
.map(trust_graph::Trust::try_from)
.map(|t| trust_graph::Trust::try_from(t))
.collect();
let chain = chain?;
Ok(trust_graph::Certificate { chain })
return Ok(trust_graph::Certificate { chain });
}
}
@ -85,12 +85,12 @@ impl TryFrom<Trust> for trust_graph::Trust {
let signature = Signature::from_bytes(KeyFormat::from_str(&t.sig_type)?, signature);
let expires_at = Duration::from_secs(t.expires_at);
let issued_at = Duration::from_secs(t.issued_at);
Ok(trust_graph::Trust {
return Ok(trust_graph::Trust {
issued_for,
expires_at,
signature,
issued_at,
})
});
}
}
@ -101,13 +101,13 @@ impl From<trust_graph::Trust> for Trust {
let signature = bs58::encode(raw_signature.bytes).into_string();
let expires_at = t.expires_at.as_secs();
let issued_at = t.issued_at.as_secs();
Trust {
return Trust {
issued_for,
expires_at,
signature,
sig_type: raw_signature.sig_type.into(),
issued_at,
}
};
}
}
@ -142,12 +142,12 @@ impl TryFrom<Revocation> for trust_graph::Revocation {
let signature = bs58::decode(&r.signature).into_vec()?;
let signature = Signature::from_bytes(KeyFormat::from_str(&r.sig_type)?, signature);
let revoked_at = Duration::from_secs(r.revoked_at);
Ok(trust_graph::Revocation {
return Ok(trust_graph::Revocation {
pk: revoked_pk,
revoked_at,
revoked_by: revoked_by_pk,
signature,
})
});
}
}
@ -158,12 +158,12 @@ impl From<trust_graph::Revocation> for Revocation {
let raw_signature = r.signature.get_raw_signature();
let signature = bs58::encode(raw_signature.bytes).into_string();
let revoked_at = r.revoked_at.as_secs();
Revocation {
return Revocation {
revoked_peer_id,
revoked_at,
signature,
sig_type: raw_signature.sig_type.into(),
revoked_by,
}
};
}
}

View File

@ -13,31 +13,10 @@ mod results;
mod service_api;
mod storage_impl;
mod tests;
/*
_initialize function that calls __wasm_call_ctors is required to mitigade memory leak
that is described in https://github.com/WebAssembly/wasi-libc/issues/298
In short, without this code rust wraps every export function
with __wasm_call_ctors/__wasm_call_dtors calls. This causes memory leaks. When compiler sees
an explicit call to __wasm_call_ctors in _initialize function, it disables export wrapping.
TODO: remove when updating to marine-rs-sdk with fix
*/
extern "C" {
pub fn __wasm_call_ctors();
}
#[no_mangle]
fn _initialize() {
unsafe {
__wasm_call_ctors();
}
}
//------------------------------
pub static TRUSTED_TIMESTAMP: (&str, &str) = ("peer", "timestamp_sec");
pub fn main() {
_initialize(); // As __wasm_call_ctors still does necessary work, we call it at the start of the module
WasmLoggerBuilder::new()
.with_log_level(log::LevelFilter::Trace)
.build()

View File

@ -15,7 +15,7 @@ use std::time::Duration;
use trust_graph::TrustGraph;
#[marine]
/// Only service owner can set roots
/// could set only a owner of a trust graph service
fn set_root(peer_id: String, max_chain_len: u32) -> SetRootResult {
let call_parameters: CallParameters = marine_rs_sdk::get_call_parameters();
let init_peer_id = call_parameters.init_peer_id;
@ -27,10 +27,10 @@ fn set_root(peer_id: String, max_chain_len: u32) -> SetRootResult {
})
.into()
} else {
SetRootResult {
return SetRootResult {
success: false,
error: ServiceError::NotOwner.to_string(),
}
};
}
}
@ -98,7 +98,7 @@ fn get_all_certs(issued_for: String, timestamp_sec: u64) -> AllCertsResult {
fn get_all_certs_from(issued_for: String, issuer: String, timestamp_sec: u64) -> AllCertsResult {
with_tg(|tg| {
let cp = get_call_parameters();
check_timestamp_tetraplets(&cp, 2)?;
check_timestamp_tetraplets(&cp, 1)?;
get_certs_from(tg, issued_for, issuer, timestamp_sec)
})
.into()

View File

@ -272,7 +272,7 @@ impl Storage for SQLiteStorage {
statement.bind(6, &Value::Binary(relation.signature().encode()))?;
statement.next()?;
Ok(())
Ok({})
}
fn get_root_weight_factor(&self, pk: &PK) -> Result<Option<WeightFactor>, Self::Error> {
@ -309,7 +309,7 @@ impl Storage for SQLiteStorage {
])?;
cursor.next()?;
Ok(())
Ok({})
}
fn root_keys(&self) -> Result<Vec<PK>, Self::Error> {

View File

@ -887,40 +887,4 @@ mod service_tests {
assert_eq!(*trust, trusts[i].trust);
}
}
#[test]
fn test_get_all_cert_from() {
let mut trust_graph = ServiceInterface::new();
clear_env();
let (key_pairs, trusts) =
generate_trust_chain_with_len(&mut trust_graph, 5, HashMap::new());
let cur_time = current_time();
let root_peer_id = key_pairs[0].get_peer_id();
set_root_peer_id(&mut trust_graph, root_peer_id, 10);
for auth in trusts.iter() {
add_trust_checked(&mut trust_graph, auth.trust.clone(), auth.issuer, cur_time);
}
let cp = get_correct_timestamp_cp_with_host_id(
2,
key_pairs.last().unwrap().get_peer_id().to_base58(),
);
let certs = trust_graph.get_all_certs_from_cp(
key_pairs[4].get_peer_id().to_base58(),
key_pairs[3].get_peer_id().to_base58(),
cur_time,
cp,
);
assert!(certs.success, "{}", certs.error);
let certs = certs.certificates;
assert_eq!(certs.len(), 1);
assert_eq!(certs[0].chain.len(), 5);
for (i, trust) in certs[0].chain.iter().enumerate() {
assert_eq!(*trust, trusts[i].trust);
}
}
}

View File

@ -74,26 +74,14 @@ impl Certificate {
Self { chain }
}
pub fn new_from_root_trust(
root_trust: Trust,
issued_trust: Trust,
cur_time: Duration,
) -> Result<Self, CertificateError> {
pub fn new_from_root_trust(root_trust: Trust, issued_trust: Trust, cur_time: Duration) -> Result<Self, CertificateError> {
Trust::verify(&root_trust, &root_trust.issued_for, cur_time).map_err(MalformedRoot)?;
Trust::verify(&issued_trust, &root_trust.issued_for, cur_time)
.map_err(|e| VerificationError(1, e))?;
Trust::verify(&issued_trust, &root_trust.issued_for, cur_time).map_err(|e| VerificationError(1, e))?;
Ok(Self {
chain: vec![root_trust, issued_trust],
})
Ok(Self { chain: vec![root_trust, issued_trust] })
}
pub fn issue_with_trust(
issued_by: PublicKey,
trust: Trust,
extend_cert: &Certificate,
cur_time: Duration,
) -> Result<Self, CertificateError> {
pub fn issue_with_trust(issued_by: PublicKey, trust: Trust, extend_cert: &Certificate, cur_time: Duration) -> Result<Self, CertificateError> {
if trust.expires_at.lt(&trust.issued_at) {
return Err(ExpirationError {
expires_at: format!("{:?}", trust.expires_at),
@ -101,11 +89,7 @@ impl Certificate {
});
}
Certificate::verify(
extend_cert,
&[extend_cert.chain[0].issued_for.clone()],
cur_time,
)?;
Certificate::verify(extend_cert, &[extend_cert.chain[0].issued_for.clone()], cur_time)?;
// check if `issued_by` is allowed to issue a certificate (i.e., theres a trust for it in a chain)
let mut previous_trust_num: i32 = -1;
for pk_id in 0..extend_cert.chain.len() {
@ -130,6 +114,7 @@ impl Certificate {
Ok(Self { chain: new_chain })
}
/// Creates new certificate with root trust (self-signed public key) from a key pair.
#[allow(dead_code)]
pub fn issue_root(
@ -166,11 +151,7 @@ impl Certificate {
}
// first, verify given certificate
Certificate::verify(
extend_cert,
&[extend_cert.chain[0].issued_for.clone()],
cur_time,
)?;
Certificate::verify(extend_cert, &[extend_cert.chain[0].issued_for.clone()], cur_time)?;
let issued_by_pk = issued_by.public();
@ -328,7 +309,7 @@ impl FromStr for Certificate {
str_lines[i + 2],
str_lines[i + 3],
)
.map_err(|e| DecodeTrustError(i, e))?;
.map_err(|e| DecodeTrustError(i, e))?;
trusts.push(trust);
}
@ -372,7 +353,7 @@ mod tests {
cur_time,
cur_time,
)
.unwrap();
.unwrap();
let serialized = new_cert.to_string();
let deserialized = Certificate::from_str(&serialized);
@ -399,7 +380,7 @@ mod tests {
cur_time,
cur_time,
)
.unwrap();
.unwrap();
let serialized = new_cert.encode();
let deserialized = Certificate::decode(serialized.as_slice());
@ -487,7 +468,7 @@ mod tests {
cur_time.checked_sub(one_minute()).unwrap(),
cur_time,
)
.unwrap();
.unwrap();
assert!(Certificate::verify(&new_cert, &trusted_roots, cur_time).is_err());
}
@ -509,7 +490,7 @@ mod tests {
cur_time,
cur_time,
)
.unwrap();
.unwrap();
let new_cert = Certificate::issue(
&third_kp,
fourth_kp.public(),
@ -547,7 +528,7 @@ mod tests {
cur_time,
cur_time,
)
.unwrap();
.unwrap();
let new_cert = Certificate::issue(
&second_kp,
fourth_kp.public(),

View File

@ -48,6 +48,7 @@ pub struct Revocation {
}
impl Revocation {
#[allow(dead_code)]
pub fn new(
revoked_by: PublicKey,
pk: PublicKey,
@ -63,6 +64,7 @@ impl Revocation {
}
/// Creates new revocation signed by a revoker.
#[allow(dead_code)]
pub fn create(revoker: &KeyPair, to_revoke: PublicKey, revoked_at: Duration) -> Self {
let msg = Revocation::signature_bytes(&to_revoke, revoked_at);
let signature = revoker.sign(&msg).unwrap();

View File

@ -95,7 +95,7 @@ impl From<TrustGraphError> for String {
}
fn get_weight_factor(max_chain_len: u32) -> u32 {
MAX_WEIGHT_FACTOR.saturating_sub(max_chain_len)
MAX_WEIGHT_FACTOR.checked_sub(max_chain_len).unwrap_or(0u32)
}
pub fn get_weight_from_factor(wf: WeightFactor) -> u32 {