Skip to content
This repository was archived by the owner on Jun 19, 2023. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
module.exports = {
parser: '@typescript-eslint/parser',
plugins: [
'@typescript-eslint',
'eslint-plugin-prettier',
'autofix',
'import',
'compat',
'prettier',
'unused-imports',
'react-perf',
],
rules: {
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-var-requires': 0,
'@typescript-eslint/ban-ts-comment': 0,
'@typescript-eslint/no-empty-interface': 0,
'@typescript-eslint/ban-types': 0,
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/no-non-null-assertion': 0,
'prettier/prettier': 'error',
'import/order': 'error',
'function-paren-newline': ['error', 'consistent'],
'array-callback-return': 0,
'@typescript-eslint/no-unused-vars': 1,
'function-paren-newline': 0,
'unused-imports/no-unused-imports-ts': 2,
camelcase: 0,
'react-hooks/exhaustive-deps': 1,
'no-use-before-define': 'off',
'@typescript-eslint/no-use-before-define': ['error'],
},
extends: [
'react-app',
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:import/typescript',
'plugin:markdown/recommended',
],
overrides: [
{
files: ['**/workers/*.ts'],
rules: {
'no-restricted-globals': 'off',
},
},
],
};
45 changes: 45 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
*.swp

pids
logs
results
tmp

# Build
public/css/main.css

# Coverage reports
coverage

# API keys and secrets
.env

# Dependency directory
node_modules
bower_components

# Editors
.idea
*.iml
.vscode/launch.json

# OS metadata
.DS_Store
Thumbs.db

# Ignore built ts files
dist/**/*

# ignore yarn.lock
yarn.lock
package-lock.json


14 changes: 14 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"printWidth":180,
"tabWidth":2,
"useTabs":false,
"semi":true,
"singleQuote":true,
"trailingComma":"es5",
"bracketSpacing":true,
"jsxBracketSameLine":false,
"arrowParens":"always",
"requirePragma":false,
"insertPragma":false,
"proseWrap":"preserve"
}
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.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# @libp2p/webrtc

## Install

## Usage

## API

## Contribute

## License
30 changes: 30 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "js-libp2p-webrtc",
"version": "1.0.0",
"description": "Dial peer using webrtc",
"main": "index.js",
"author": "",
"license": "Apache-2.0 or MIT",
"type": "module",
"scripts": {
"build": "aegir build",
"test": "aegir test",
"format": "prettier --write src/*.ts"
},
"devDependencies": {
"@types/uuid": "^8.3.4",
"@typescript-eslint/parser": "^5.32.0",
"aegir": "^37.4.6",
"prettier": "^2.7.1",
"typescript": "^4.7.4"
},
"dependencies": {
"@libp2p/components": "^2.0.1",
"@libp2p/interface-transport": "^1.0.2",
"@libp2p/interfaces": "^3.0.3",
"@libp2p/logger": "^2.0.0",
"abortable-iterator": "^4.0.2",
"socket.io-client": "^4.1.2",
"uuid": "^8.3.2"
}
}
72 changes: 72 additions & 0 deletions src/connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { Connection } from '@libp2p/interface-connection';
import { ConnectionStat } from '@libp2p/interface-connection';
import { Stream, Direction } from '@libp2p/interface-connection';
import { PeerId } from '@libp2p/interface-peer-id';
import { AbortOptions } from '@libp2p/interfaces';
import { logger } from '@libp2p/logger';
import { Multiaddr } from '@multiformats/multiaddr';
import { v4 as genUuid } from 'uuid';

const log = logger('libp2p:webrtc:connection');

type ConnectionInit = {
id: string;
localPeer: PeerId;
localAddr?: Multiaddr;
remotePeer: PeerId;
remoteAddr: Multiaddr;
direction: Direction;
tags?: string[];
stat: ConnectionStat;
pc: RTCPeerConnection;
credential_string: string;
};

export class WebRTCConnection implements Connection {
id: string;
stat: ConnectionStat;
remoteAddr: Multiaddr;
remotePeer: PeerId;
tags: string[] = [];
streams: Stream[] = [];
direction: Direction;

private peerConnection: RTCPeerConnection;
private ufrag: string;

constructor(init: ConnectionInit) {
this.streams = [];
this.remotePeer = init.remotePeer;
this.remoteAddr = init.remoteAddr;
this.stat = init.stat;
this.id = init.id;
this.direction = init.direction;
this.peerConnection = init.pc;
this.ufrag = init.credential_string;
// for muxing incoming stream
// this._peerConnection.ondatachannel = ({ channel }) => {
// let stream = DataChannelStream(channel)
// this.addStream(stream)
// }
}

async newStream(multicodecs: string | string[], options?: AbortOptions): Promise<Stream> {
// let label = uuid.v4()
// let dc = this._peerConnection.createDataChannel(label, {})
// await datachannel opening
// return DataChannelStream(dc)
log('TODO', this.ufrag);
this.peerConnection.createDataChannel(genUuid());
throw new Error('not implemented');
}

addStream(stream: Stream): void {
throw new Error('not implemented');
}
removeStream(id: string): void {
throw new Error('not implemented');
}
async close(): Promise<void> {
throw new Error('not implemented');
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {};
9 changes: 9 additions & 0 deletions src/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { CreateListenerOptions } from '@libp2p/interface-transport';
import { DialOptions } from '@libp2p/interface-transport';

export interface WebRTCListenerOptions extends CreateListenerOptions {
//, WebRTCInitiatorInit {
// channelOptions?: WebRTCReceiverInit
}

export interface WebRTCDialOptions extends DialOptions {}
73 changes: 73 additions & 0 deletions src/sdp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { logger } from '@libp2p/logger';
import { Multiaddr } from '@multiformats/multiaddr';

const log = logger('libp2p:webrtc:sdp');

const P_XWEBRTC: number = 0x115;
const ANSWER_SDP_FORMAT: string = `
v=0
o=- 0 0 IN %s %s
s=-
c=IN %s %s
t=0 0
m=application %d UDP/DTLS/SCTP webrtc-datachannel
a=mid:0
a=ice-options:ice2
a=ice-ufrag:%s
a=ice-pwd:%s
a=fingerprint:%s
a=setup:actpass
a=sctp-port:5000
a=max-message-size:100000
`;

function ipv(ma: Multiaddr): string {
for (let proto of ma.protoNames()) {
if (proto.startsWith('ip')) {
return proto.toUpperCase();
}
}
log('Warning: multiaddr does not appear to contain IP4 or IP6.', ma);
return 'IP6';
}
function ip(ma: Multiaddr): string {
return ma.toOptions().host;
}
function port(ma: Multiaddr): number {
return ma.toOptions().port;
}
function certhash(ma: Multiaddr): string {
let webrtc_value = ma
.stringTuples()
.filter((tup) => tup[0] == P_XWEBRTC)
.map((tup) => tup[1])[0];
if (webrtc_value) {
return webrtc_value.split('/')[1];
} else {
throw new Error("Couldn't find a webrtc component of multiaddr:" + ma.toString());
}
}

function ma2sdp(ma: Multiaddr, ufrag: string): string {
return ANSWER_SDP_FORMAT.replace('/%s/', ipv(ma))
.replace('/%s/', ip(ma))
.replace('/%s/', ipv(ma))
.replace('/%s/', ip(ma))
.replace('/%s/', port(ma).toString())
.replace('/%s/', ufrag)
.replace('/%s/', ufrag)
.replace('/%s/', certhash(ma));
}

export function fromMultiAddr(ma: Multiaddr, ufrag: string): RTCSessionDescriptionInit {
return {
type: 'offer',
sdp: ma2sdp(ma, ufrag),
};
}

export function munge(desc: RTCSessionDescription, ufrag: string) {
//TODO
desc.sdp.replaceAll(/^a=ice-ufrag=(.*)/, 'a=ice-ufrag=' + ufrag);
desc.sdp.replaceAll(/^a=ice-pwd=(.*)/, 'a=ice-pwd=' + ufrag);
}
Loading