Skip to content
Open

G4 #2

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
17,666 changes: 10,795 additions & 6,871 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
"react-bulma-components": "^3.0.1-7",
"react-dom": "^16.9.0",
"react-leaflet": "^2.4.0",
"react-scripts": "3.1.1",
"tupelo-messages": "^0.5.0-rc6",
"tupelo-wasm-sdk": "^0.5.14",
"react-scripts": "^3.4.0",
"tupelo-messages": "latest",
"tupelo-wasm-sdk": "next",
"typestate": "^1.0.6"
},
"scripts": {
Expand Down
31 changes: 16 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Icon, Point } from 'leaflet'
import { Driver } from './decentracar/driver';
import { Rider } from './decentracar/rider';
import { Container, Button, Columns, Navbar, Content, Box, Media, Image } from 'react-bulma-components';
import {logs} from './decentracar/util/emittinglogger';
import { logs } from './decentracar/util/emittinglogger';

import 'tupelo-wasm-sdk' // in order to get the Go global

Expand All @@ -18,14 +18,14 @@ const subDirectory = window.location.pathname
console.log("subDirectory ", subDirectory)

if (subDirectory !== '/') {
console.log("setting wasmpath to: ", subDirectory + "tupelo.wasm")
Go.setWasmPath(subDirectory + "tupelo.wasm");
console.log("setting wasmpath to: ", subDirectory + "tupelo.wasm")
Go.setWasmPath(subDirectory + "tupelo.wasm");
}

const position: [number, number] = [52.491362, 13.362029];

const driverPng:any = require('./imgs/driver.png')
const riderPng:any = require('./imgs/rider.png')
const driverPng: any = require('./imgs/driver.png')
const riderPng: any = require('./imgs/rider.png')

const driverIcon = new Icon({
iconUrl: driverPng,
Expand Down Expand Up @@ -62,13 +62,14 @@ const RiderMarker = ({ rider }: { rider: Rider }) => {
)
}

const SimulationDisplay = ({ simulation, logs }: { simulation: Simulation, logs:JSX.Element[] }) => {
const SimulationDisplay = ({ simulation, logs }: { simulation: Simulation, logs: JSX.Element[] }) => {
let markers: JSX.Element[] = []
for (let d of simulation.drivers) {
markers.push(<DriverMarker key={d.name} driver={d} />)
}

for (let r of simulation.riders) {
console.log("pushing marker for rider:", r)
markers.push(<RiderMarker key={r.name} rider={r} />)
}

Expand Down Expand Up @@ -99,16 +100,16 @@ const SimulationDisplay = ({ simulation, logs }: { simulation: Simulation, logs:
}


const LogDisplay = ({txt,icon}:{txt:string,icon:any}) => {
const LogDisplay = ({ txt, icon }: { txt: string, icon: any }) => {
return (
<Box key={txt}>
<Media>
<Media.Item>
<Image size={32} src={icon}></Image>
<Image size={32} src={icon}></Image>
</Media.Item>
<Media.Item>
<Content>
<p>{txt}</p>
<p>{txt}</p>
</Content>
</Media.Item>
</Media>
Expand All @@ -134,14 +135,14 @@ const App: React.FC = () => {
})
sim.start()
sim.tickEvery(1000)
logs.on('decentracar:driver', (...logStrings:any[]) => {
appLogs.unshift(<LogDisplay icon={driverPng} txt={logStrings.join(' ')}/>)

logs.on('decentracar:driver', (...logStrings: any[]) => {
appLogs.unshift(<LogDisplay icon={driverPng} txt={logStrings.join(' ')} />)
setAppLogs(appLogs)
})

logs.on('decentracar:rider', (...logStrings:any[]) => {
appLogs.unshift(<LogDisplay icon={riderPng} txt={logStrings.join(' ')}/>)
logs.on('decentracar:rider', (...logStrings: any[]) => {
appLogs.unshift(<LogDisplay icon={riderPng} txt={logStrings.join(' ')} />)
setAppLogs(appLogs)
})

Expand All @@ -158,7 +159,7 @@ const App: React.FC = () => {
{simulation ? <SimulationDisplay simulation={simulation} logs={appLogs} /> :
<Content>
<p>This is a simulation of a simplified decentralized car sharing app.</p>
<p>You can read more about it here: <a href="https://www.tupelo.org/posts/decentracar">https://www.tupelo.org/posts/decentracar</a>.
<p>You can read more about it here: <a href="https://www.tupelo.org/posts/decentracar">https://www.tupelo.org/posts/decentracar</a>.
Github repo is here: <a href="https://github.com/quorumcontrol/decentracar">https://github.com/quorumcontrol/decentracar</a></p>
<p><Button onClick={handleStart}>Click here to start</Button></p>
<p>This simulation only works on desktop browsers (and not safari).</p>
Expand Down
30 changes: 15 additions & 15 deletions src/decentracar/company/service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Community, EcdsaKey, ChainTree, CID, CommunityMessenger, setDataTransaction } from "tupelo-wasm-sdk";
import { Envelope } from "tupelo-messages";
import { messageType, didRegistration, deserialize, serialize } from "../messages";
import { Community, EcdsaKey, ChainTree, CID, setDataTransaction } from "tupelo-wasm-sdk";
import { Messenger, messageType, didRegistration, deserialize, serialize } from "../messages";
import { EventEmitter } from "events";
import { certificationTopic } from '../messages'
import { SimpleSyncher } from "../util/actor";
import {emittingLogger} from '../util/emittinglogger';
import { emittingLogger } from '../util/emittinglogger';

const log = emittingLogger("decentracar:company")

Expand All @@ -24,7 +23,7 @@ export class DecentraCarService extends EventEmitter {
key: EcdsaKey
tree?: ChainTree
private did: string
private messenger?: CommunityMessenger
private messenger?: Messenger
private syncher: SimpleSyncher

constructor(opts: IDecentraCarServiceOptions) {
Expand All @@ -37,20 +36,21 @@ export class DecentraCarService extends EventEmitter {

async start() {
await this._findOrCreateTree()
this.messenger = new CommunityMessenger("integrationtest", 32, this.key, (await this.id()), this.community.node.pubsub)
this.messenger = new Messenger(this.community.node.pubsub)

return this.messenger.subscribe(certificationTopic, this.handleRegistration.bind(this))
}

private async handleRegistration(env: Envelope) {
private async handleRegistration(payload: Uint8Array) {
if (this.tree === undefined || this.messenger === undefined) {
throw new Error("handling a message on a service without a tree or messenger")
}
const msg: didRegistration = deserialize(env.getPayload_asU8())
const msg: didRegistration = deserialize(payload)
const did = msg.did

let tryCount = 0

const getTip = async ()=> {
const getTip = async () => {
let tip

try {
Expand All @@ -69,11 +69,11 @@ export class DecentraCarService extends EventEmitter {
getTip()
}

private async handleNew(tip:any, msg:didRegistration) {
private async handleNew(tip: any, msg: didRegistration) {
if (this.tree === undefined || this.messenger === undefined) {
throw new Error("handling a message on a service without a tree or messenger")
}

const did = msg.did
let tree = new ChainTree({
tip: new CID(tip),
Expand All @@ -89,7 +89,7 @@ export class DecentraCarService extends EventEmitter {
return this.community.playTransactions(this.tree, [setDataTransaction("/_decentracar/validatedriders/" + did, true)])
})
log("registered new rider: ", did)
this.messenger.publish(did, serialize({ type: messageType.didRegistration, did: did } as didRegistration))
this.messenger.publish(did, serialize({ type: messageType.didRegistration, from: (await this.id()), did: did } as didRegistration))
this.emit('rider', did)
break;
case "driver":
Expand All @@ -101,7 +101,7 @@ export class DecentraCarService extends EventEmitter {
return
})
log("registered new driver: ", did)
this.messenger.publish(did, serialize({ type: messageType.didRegistration, did: did } as didRegistration))
this.messenger.publish(did, serialize({ type: messageType.didRegistration, from: (await this.id()), did: did } as didRegistration))
this.emit('driver', did)
break;
default:
Expand Down Expand Up @@ -129,7 +129,7 @@ export class DecentraCarService extends EventEmitter {
// do nothing
}
}
if (CID.isCID(tip)) {
if (tip !== undefined && CID.isCID(tip)) {
this.tree = new ChainTree({
key: this.key,
tip: tip,
Expand All @@ -140,4 +140,4 @@ export class DecentraCarService extends EventEmitter {
}
}

}
}
45 changes: 24 additions & 21 deletions src/decentracar/driver/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { EcdsaKey, ChainTree, Community, CommunityMessenger, setDataTransaction } from 'tupelo-wasm-sdk';
import { EcdsaKey, ChainTree, Community, setDataTransaction } from 'tupelo-wasm-sdk';
import faker from 'faker';
import Vector from '../util/vector'
import { EventEmitter } from 'events';
import { Envelope } from 'tupelo-messages';
import { certificationTopic, ridersTopic, messageType, serialize, dropoff, riding, deserialize, offer, dcMessage, offerAccept, didRegistration } from '../messages';
import { Messenger } from "../messages";
import { certificationTopic, ridersTopic, messageType, serialize, dropoff, riding, deserialize, offer, dcMessage, offerAccept, didRegistration, rideRequest } from '../messages';
import { SimpleSyncher } from '../util/actor';
import {emittingLogger} from "../util/emittinglogger";
import { emittingLogger } from "../util/emittinglogger";

const log = emittingLogger('decentracar:driver')

Expand Down Expand Up @@ -34,12 +34,12 @@ export class Driver extends EventEmitter {
acceptedRider?: string
destination?: Vector
offering: boolean
hasRider:boolean
hasRider: boolean
registered: boolean

private messenger?: CommunityMessenger
private messenger?: Messenger
private startPromise?: Promise<Driver>
private syncher:SimpleSyncher
private syncher: SimpleSyncher

constructor(opts: IDriverOpts) {
super();
Expand Down Expand Up @@ -69,7 +69,7 @@ export class Driver extends EventEmitter {
return
}
this.id = id
this.messenger = new CommunityMessenger("integrationtest", 32, this.key, Buffer.from(this.id, 'utf8'), community.node.pubsub)
this.messenger = new Messenger(community.node.pubsub)
this.messenger.subscribe(this.id, this.handleSelfMessages.bind(this))
this.messenger.subscribe(ridersTopic, this.handleRidersMessage.bind(this))
await this.registerAsDriver()
Expand All @@ -81,43 +81,46 @@ export class Driver extends EventEmitter {

async registerAsDriver() {
log(this.name, " registering as driver")
if (this.messenger === undefined || this.tree === undefined) {
throw new Error("need a tree and messenger to registerAsDriver")
if (this.messenger === undefined || this.tree === undefined || this.id === undefined) {
throw new Error("need a tree, id, and messenger to registerAsDriver")
}
const c = await this.community
await c.playTransactions(this.tree, [setDataTransaction("_decentracar/type", "driver")])
await c.nextUpdate()
this.messenger.publish(certificationTopic, serialize({
type: messageType.didRegistration,
from: Buffer.from(this.id, 'utf8'),
did: this.id,
} as didRegistration))
}

async handleRidersMessage(env: Envelope) {
async handleRidersMessage(payload: Uint8Array) {
if (this.offering) {
return // ignore other messages for now
}
if (this.messenger === undefined || this.tree === undefined || this.id === undefined) {
throw new Error("need an id, tree and messenger to registerAsDriver")
throw new Error("need an tree, id and messenger to handleRidersMessage")
}
// TODO: make a decision if the car should offer or not
this.offering = true
const c = await this.community
await c.playTransactions(this.tree, [setDataTransaction("_decentracar/offering", Buffer.from(env.getFrom_asU8()).toString())])

const msg: rideRequest = deserialize(payload)
await c.playTransactions(this.tree, [setDataTransaction("_decentracar/offering", Buffer.from(msg.from).toString())])
log(this.name, " offering a ride")

this.messenger.publish(Buffer.from(env.getFrom_asU8()).toString(), serialize({
this.messenger.publish(Buffer.from(msg.from).toString(), serialize({
type: messageType.offer,
driverDid: this.id,
driverLocation: [this.location.x, this.location.y],
} as offer))
}

async handleSelfMessages(env: Envelope) {
async handleSelfMessages(payload: Uint8Array) {
if (this.messenger === undefined || this.tree === undefined || this.id === undefined) {
throw new Error("need an id, tree and messenger to handleSelfMessages")
}
const msg: dcMessage = deserialize(env.getPayload_asU8())
const msg: dcMessage = deserialize(payload)
switch (msg.type) {
case messageType.didRegistration:
this.registered = true // for now, for real we'd have to check this
Expand All @@ -138,7 +141,7 @@ export class Driver extends EventEmitter {
this.riderLocation = new Vector(typedMsg.location[0], typedMsg.location[1])
this.destination = new Vector(typedMsg.destination[0], typedMsg.destination[1])
const c = await this.community
this.syncher.send(()=> {
this.syncher.send(() => {
if (this.tree === undefined) {
throw new Error("undefined tree")
}
Expand Down Expand Up @@ -170,7 +173,7 @@ export class Driver extends EventEmitter {
this.hasRider = false
this.riderLocation = undefined
const c = await this.community
await this.syncher.send(()=> {
await this.syncher.send(() => {
if (this.tree === undefined) {
throw new Error("undefined tree")
}
Expand All @@ -196,7 +199,7 @@ export class Driver extends EventEmitter {
} as riding))
this.follow(this.destination, ARRIVAL_DIST) //TODO: not sure what the arrival number should be
}


} else {
this.emit('wandering')
Expand Down Expand Up @@ -224,7 +227,7 @@ export class Driver extends EventEmitter {
dest.setMag(MAX_SPEED);
}



this.applyForce(dest.limit(MAX_FORCE * 2));
}
Expand Down Expand Up @@ -258,4 +261,4 @@ export class Driver extends EventEmitter {
// reset acceleration
this.acceleration.mul(0);
}
}
}
Loading