Skip to content

Commit

Permalink
feat: add delegated routing example (#90)
Browse files Browse the repository at this point in the history
Restores old example but updates it for use with modern delegates.
  • Loading branch information
achingbrain authored Dec 4, 2023
0 parents commit 00376da
Show file tree
Hide file tree
Showing 15 changed files with 475 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# ⚠️ IMPORTANT ⚠️

# Please do not create a Pull Request for this repository

The contents of this repository are automatically synced from the parent [js-libp2p Examples Project](https://github.com/libp2p/js-libp2p-examples) so any changes made to the standalone repository will be lost after the next sync.

Please open a PR against [js-libp2p Examples](https://github.com/libp2p/js-libp2p-examples) instead.

## Contributing

Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.

1. Fork the [js-libp2p Examples Project](https://github.com/libp2p/js-libp2p-examples)
2. Create your Feature Branch (`git checkout -b feature/amazing-example`)
3. Commit your Changes (`git commit -a -m 'feat: add some amazing example'`)
4. Push to the Branch (`git push origin feature/amazing-example`)
5. Open a Pull Request
19 changes: 19 additions & 0 deletions .github/workflows/sync.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: pull

on:
workflow_dispatch

jobs:
sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Pull from another repository
uses: ipfs-examples/actions-pull-directory-from-repo@main
with:
source-repo: libp2p/js-libp2p-examples
source-folder-path: examples/${{ github.event.repository.name }}
source-branch: main
target-branch: main
git-username: github-actions
git-email: [email protected]
4 changes: 4 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
This project is dual licensed under MIT and Apache-2.0.

MIT: https://www.opensource.org/licenses/mit
Apache-2.0: https://www.apache.org/licenses/license-2.0
5 changes: 5 additions & 0 deletions LICENSE-APACHE
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
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.
19 changes: 19 additions & 0 deletions LICENSE-MIT
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
The MIT License (MIT)

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# @libp2p/example-delegated-routing-example <!-- omit in toc -->

[![libp2p.io](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](http://libp2p.io/)
[![Discuss](https://img.shields.io/discourse/https/discuss.libp2p.io/posts.svg?style=flat-square)](https://discuss.libp2p.io)
[![codecov](https://img.shields.io/codecov/c/github/libp2p/js-libp2p-examples.svg?style=flat-square)](https://codecov.io/gh/libp2p/js-libp2p-examples)
[![CI](https://img.shields.io/github/actions/workflow/status/libp2p/js-libp2p-examples/ci.yml?branch=main\&style=flat-square)](https://github.com/libp2p/js-libp2p-examples/actions/workflows/ci.yml?query=branch%3Amain)

> How to configure libp2p delegated routers
## Table of contents <!-- omit in toc -->

- [Running this example](#running-this-example)
- [Finding Content Providers via the Delegate](#finding-content-providers-via-the-delegate)
- [Finding Peers via the Delegate](#finding-peers-via-the-delegate)
- [License](#license)
- [Contribution](#contribution)

Delegated routing allows a libp2p node running in a constrained environment (for example a browser) to offload network operations and queries to a more capable node running elsewhere.

The [libp2p node](./src/libp2p.js) created by this app has no transports, connection encrypters or muxers - it uses only a [Delegated Routing V1 HTTP API client](https://specs.ipfs.tech/routing/http-routing-v1/) to look up CID providers and Peer Info from a more capable libp2p node running in a separate process.

## Running this example

1. Install the example dependencies
```console
$ npm i
```
2. Start the Helia node in `./server.js` - this is the node we will delegate operations to
```console
$ node ./server.js
```
3. Start the lightweight browser libp2p node
```console
$ npm start
```

This should open your browser to <http://localhost:3000>. If it does not, go ahead and do that now.

### Finding Content Providers via the Delegate

1. Enter the CID of the block you wish to find providers for, one is pre-filled for your convenience
2. Click "Find Providers"
3. If any exist, provders will start to appear in the box beneath the input fields

### Finding Peers via the Delegate

1. Enter the PeerId of the peer you wish to find, one is pre-filled for your convenience
2. Click "Find PeerInfo"
3. If found, multiaddrs for the peer will appear in the box beneath the input fields

## License

Licensed under either of

- Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT ([LICENSE-MIT](LICENSE-MIT) / <http://opensource.org/licenses/MIT>)

## Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
42 changes: 42 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "@libp2p/example-delegated-routing-example",
"version": "0.0.0",
"description": "How to use other libp2p nodes to perform delegated routing",
"license": "Apache-2.0 OR MIT",
"homepage": "https://github.com/libp2p/js-libp2p-examples/tree/main/examples/js-libp2p-example-delegated-routing#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/libp2p/js-libp2p-examples.git"
},
"bugs": {
"url": "https://github.com/libp2p/js-libp2p-examples/issues"
},
"type": "module",
"scripts": {
"build": "BUILD_PATH=dist PUBLIC_URL=/ react-scripts build",
"start": "PUBLIC_URL=/ react-scripts start",
"test:firefox": "npm run build && playwright test --browser=firefox test",
"test:chrome": "npm run build && playwright test test",
"test": "npm run build && test-browser-example test"
},
"dependencies": {
"@helia/delegated-routing-v1-http-api-client": "^1.1.0",
"@helia/delegated-routing-v1-http-api-server": "^1.0.3",
"helia": "^2.1.0",
"libp2p": "^1.0.8",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "^5.0.1"
},
"devDependencies": {
"test-ipfs-example": "^1.0.0",
"eslint-config-ipfs": "^6.0.0"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"private": true
}
Binary file added public/favicon.ico
Binary file not shown.
16 changes: 16 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<title>Delegated Routing</title>
<link rel="stylesheet" type="text/css" href="%PUBLIC_URL%/main.css">
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
</body>
</html>
67 changes: 67 additions & 0 deletions public/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}

section * {
margin: 10px;
}

header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
}

.center {
text-align: center;
}

pre {
background-color: bisque;
min-height: 100px;
margin: 0px;
padding: 10px;
}

.loader {
text-align: center;
height: 64px;
margin-bottom: -64px;
}

.loading .lds-ripple {
display: inline-block;
position: relative;
width: 64px;
height: 64px;
}
.loading .lds-ripple div {
position: absolute;
border: 4px solid #000;
opacity: 1;
border-radius: 50%;
animation: lds-ripple 1s cubic-bezier(0, 0.2, 0.8, 1) infinite;
margin: auto;
}
.loading .lds-ripple div:nth-child(2) {
animation-delay: -0.5s;
}
@keyframes lds-ripple {
0% {
top: 28px;
left: 28px;
width: 0;
height: 0;
opacity: 1;
}
100% {
top: -1px;
left: -1px;
width: 58px;
height: 58px;
opacity: 0;
}
}
15 changes: 15 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/* eslint-disable no-console */
import { createDelegatedRoutingV1HttpApiServer } from '@helia/delegated-routing-v1-http-api-server'
import { createHelia } from 'helia'

const helia = await createHelia()

const fastify = await createDelegatedRoutingV1HttpApiServer(helia, {
listen: {
host: '127.0.0.1',
port: 9832,
listenTextResolver: (address) => { return `server is listening at ${address}` }
}
})

console.info(`Server listening on http://${fastify.server.address().address}:${fastify.server.address().port}`)
120 changes: 120 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/* eslint-disable no-console */
// eslint-disable-next-line
'use strict'

import { peerIdFromString } from '@libp2p/peer-id'
import { CID } from 'multiformats/cid'
import React from 'react'
import { configureLibp2p } from './libp2p.js'

const Component = React.Component

class App extends Component {
constructor (props) {
super(props)
this.state = {
// This hash is the 'hello world' string
hash: 'bafkreifzjut3te2nhyekklss27nh3k72ysco7y32koao5eei66wof36n5e',
// This peer is one of the Bootstrap nodes for Helia
peer: 'QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',
isLoading: 0
}
this.peerInterval = null

this.handleHashChange = this.handleHashChange.bind(this)
this.handleHashSubmit = this.handleHashSubmit.bind(this)
this.handlePeerChange = this.handlePeerChange.bind(this)
this.handlePeerSubmit = this.handlePeerSubmit.bind(this)
}

handleHashChange (event) {
this.setState({
hash: event.target.value
})
}

handlePeerChange (event) {
this.setState({
peer: event.target.value
})
}

async handleHashSubmit (event) {
event.preventDefault()
this.setState({
isLoading: this.state.isLoading + 1
})

const providers = []

for await (const provider of this.libp2p.contentRouting.findProviders(CID.parse(this.state.hash))) {
providers.push(provider)

this.setState({
response: JSON.stringify(providers, null, 2),
isLoading: this.state.isLoading - 1
})
}
}

async handlePeerSubmit (event) {
event.preventDefault()
this.setState({
isLoading: this.state.isLoading + 1
})

try {
const peerInfo = await this.libp2p.peerRouting.findPeer(peerIdFromString(this.state.peer))

this.setState({
response: JSON.stringify(peerInfo, null, 2),
isLoading: this.state.isLoading - 1
})
} catch (err) {
this.setState({
response: `Error finding peer: ${err.message}`,
isLoading: this.state.isLoading - 1
})
}
}

async componentDidMount () {
window.libp2p = this.libp2p = await configureLibp2p()
}

render () {
return (
<div>
<header className="center">
<h1>Delegated Routing</h1>
</header>
<section className="center">
<form onSubmit={this.handleHashSubmit}>
<label>
Find providers of CID:
<input type="text" value={this.state.hash} onChange={this.handleHashChange} id="find-providers-input" />
<input type="submit" value="Find Providers" id="find-providers-button" />
</label>
</form>
<form onSubmit={this.handlePeerSubmit}>
<label>
Find peer:
<input type="text" value={this.state.peer} onChange={this.handlePeerChange} id="find-peer-input" />
<input type="submit" value="Find PeerInfo" id="find-peer-button" />
</label>
</form>
</section>
<section className={[this.state.isLoading > 0 ? 'loading' : '', 'loader'].join(' ')}>
<div className="lds-ripple"><div></div><div></div></div>
</section>
<section>
<pre id="output">
{this.state.response}
</pre>
</section>
</div>
)
}
}

export default App
Loading

0 comments on commit 00376da

Please sign in to comment.